LLVM 18.0.0git
MachineFunction.cpp
Go to the documentation of this file.
1//===- MachineFunction.cpp ------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Collect native machine code information for a function. This allows
10// target-specific information about the generated code to be stored with each
11// function.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/BitVector.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/ADT/Twine.h"
42#include "llvm/Config/llvm-config.h"
43#include "llvm/IR/Attributes.h"
44#include "llvm/IR/BasicBlock.h"
45#include "llvm/IR/Constant.h"
46#include "llvm/IR/DataLayout.h"
49#include "llvm/IR/Function.h"
50#include "llvm/IR/GlobalValue.h"
51#include "llvm/IR/Instruction.h"
53#include "llvm/IR/Metadata.h"
54#include "llvm/IR/Module.h"
56#include "llvm/IR/Value.h"
57#include "llvm/MC/MCContext.h"
58#include "llvm/MC/MCSymbol.h"
59#include "llvm/MC/SectionKind.h"
68#include <algorithm>
69#include <cassert>
70#include <cstddef>
71#include <cstdint>
72#include <iterator>
73#include <string>
74#include <type_traits>
75#include <utility>
76#include <vector>
77
79
80using namespace llvm;
81
82#define DEBUG_TYPE "codegen"
83
85 "align-all-functions",
86 cl::desc("Force the alignment of all functions in log2 format (e.g. 4 "
87 "means align on 16B boundaries)."),
89
92
93 // clang-format off
94 switch(Prop) {
95 case P::FailedISel: return "FailedISel";
96 case P::IsSSA: return "IsSSA";
97 case P::Legalized: return "Legalized";
98 case P::NoPHIs: return "NoPHIs";
99 case P::NoVRegs: return "NoVRegs";
100 case P::RegBankSelected: return "RegBankSelected";
101 case P::Selected: return "Selected";
102 case P::TracksLiveness: return "TracksLiveness";
103 case P::TiedOpsRewritten: return "TiedOpsRewritten";
104 case P::FailsVerification: return "FailsVerification";
105 case P::TracksDebugUserValues: return "TracksDebugUserValues";
106 }
107 // clang-format on
108 llvm_unreachable("Invalid machine function property");
109}
110
112 if (!F.hasFnAttribute(Attribute::SafeStack))
113 return;
114
115 auto *Existing =
116 dyn_cast_or_null<MDTuple>(F.getMetadata(LLVMContext::MD_annotation));
117
118 if (!Existing || Existing->getNumOperands() != 2)
119 return;
120
121 auto *MetadataName = "unsafe-stack-size";
122 if (auto &N = Existing->getOperand(0)) {
123 if (N.equalsStr(MetadataName)) {
124 if (auto &Op = Existing->getOperand(1)) {
125 auto Val = mdconst::extract<ConstantInt>(Op)->getZExtValue();
126 FrameInfo.setUnsafeStackSize(Val);
127 }
128 }
129 }
130}
131
132// Pin the vtable to this file.
133void MachineFunction::Delegate::anchor() {}
134
136 const char *Separator = "";
137 for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
138 if (!Properties[I])
139 continue;
140 OS << Separator << getPropertyName(static_cast<Property>(I));
141 Separator = ", ";
142 }
143}
144
145//===----------------------------------------------------------------------===//
146// MachineFunction implementation
147//===----------------------------------------------------------------------===//
148
149// Out-of-line virtual method.
151
154}
155
157 const Function &F) {
158 if (auto MA = F.getFnStackAlign())
159 return *MA;
160 return STI->getFrameLowering()->getStackAlign();
161}
162
164 const TargetSubtargetInfo &STI,
165 unsigned FunctionNum, MachineModuleInfo &mmi)
166 : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
167 FunctionNumber = FunctionNum;
168 init();
169}
170
171void MachineFunction::handleInsertion(MachineInstr &MI) {
172 if (TheDelegate)
173 TheDelegate->MF_HandleInsertion(MI);
174}
175
176void MachineFunction::handleRemoval(MachineInstr &MI) {
177 if (TheDelegate)
178 TheDelegate->MF_HandleRemoval(MI);
179}
180
182 const MCInstrDesc &TID) {
183 if (TheDelegate)
184 TheDelegate->MF_HandleChangeDesc(MI, TID);
185}
186
187void MachineFunction::init() {
188 // Assume the function starts in SSA form with correct liveness.
191 if (STI->getRegisterInfo())
192 RegInfo = new (Allocator) MachineRegisterInfo(this);
193 else
194 RegInfo = nullptr;
195
196 MFInfo = nullptr;
197
198 // We can realign the stack if the target supports it and the user hasn't
199 // explicitly asked us not to.
200 bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
201 !F.hasFnAttribute("no-realign-stack");
202 FrameInfo = new (Allocator) MachineFrameInfo(
203 getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
204 /*ForcedRealign=*/CanRealignSP &&
205 F.hasFnAttribute(Attribute::StackAlignment));
206
207 setUnsafeStackSize(F, *FrameInfo);
208
209 if (F.hasFnAttribute(Attribute::StackAlignment))
210 FrameInfo->ensureMaxAlignment(*F.getFnStackAlign());
211
213 Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
214
215 // FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
216 // FIXME: Use Function::hasOptSize().
217 if (!F.hasFnAttribute(Attribute::OptimizeForSize))
218 Alignment = std::max(Alignment,
220
221 // -fsanitize=function and -fsanitize=kcfi instrument indirect function calls
222 // to load a type hash before the function label. Ensure functions are aligned
223 // by a least 4 to avoid unaligned access, which is especially important for
224 // -mno-unaligned-access.
225 if (F.hasMetadata(LLVMContext::MD_func_sanitize) ||
226 F.getMetadata(LLVMContext::MD_kcfi_type))
227 Alignment = std::max(Alignment, Align(4));
228
230 Alignment = Align(1ULL << AlignAllFunctions);
231
232 JumpTableInfo = nullptr;
233
235 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
236 WinEHInfo = new (Allocator) WinEHFuncInfo();
237 }
238
240 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
241 WasmEHInfo = new (Allocator) WasmEHFuncInfo();
242 }
243
244 assert(Target.isCompatibleDataLayout(getDataLayout()) &&
245 "Can't create a MachineFunction using a Module with a "
246 "Target-incompatible DataLayout attached\n");
247
248 PSVManager = std::make_unique<PseudoSourceValueManager>(getTarget());
249}
250
252 const TargetSubtargetInfo &STI) {
253 assert(!MFInfo && "MachineFunctionInfo already set");
254 MFInfo = Target.createMachineFunctionInfo(Allocator, F, &STI);
255}
256
258 clear();
259}
260
261void MachineFunction::clear() {
262 Properties.reset();
263 // Don't call destructors on MachineInstr and MachineOperand. All of their
264 // memory comes from the BumpPtrAllocator which is about to be purged.
265 //
266 // Do call MachineBasicBlock destructors, it contains std::vectors.
267 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
268 I->Insts.clearAndLeakNodesUnsafely();
269 MBBNumbering.clear();
270
271 InstructionRecycler.clear(Allocator);
272 OperandRecycler.clear(Allocator);
273 BasicBlockRecycler.clear(Allocator);
274 CodeViewAnnotations.clear();
276 if (RegInfo) {
277 RegInfo->~MachineRegisterInfo();
278 Allocator.Deallocate(RegInfo);
279 }
280 if (MFInfo) {
281 MFInfo->~MachineFunctionInfo();
282 Allocator.Deallocate(MFInfo);
283 }
284
285 FrameInfo->~MachineFrameInfo();
286 Allocator.Deallocate(FrameInfo);
287
288 ConstantPool->~MachineConstantPool();
289 Allocator.Deallocate(ConstantPool);
290
291 if (JumpTableInfo) {
292 JumpTableInfo->~MachineJumpTableInfo();
293 Allocator.Deallocate(JumpTableInfo);
294 }
295
296 if (WinEHInfo) {
297 WinEHInfo->~WinEHFuncInfo();
298 Allocator.Deallocate(WinEHInfo);
299 }
300
301 if (WasmEHInfo) {
302 WasmEHInfo->~WasmEHFuncInfo();
303 Allocator.Deallocate(WasmEHInfo);
304 }
305}
306
308 return F.getParent()->getDataLayout();
309}
310
311/// Get the JumpTableInfo for this function.
312/// If it does not already exist, allocate one.
314getOrCreateJumpTableInfo(unsigned EntryKind) {
315 if (JumpTableInfo) return JumpTableInfo;
316
317 JumpTableInfo = new (Allocator)
319 return JumpTableInfo;
320}
321
323 return F.getDenormalMode(FPType);
324}
325
326/// Should we be emitting segmented stack stuff for the function
328 return getFunction().hasFnAttribute("split-stack");
329}
330
331[[nodiscard]] unsigned
333 FrameInstructions.push_back(Inst);
334 return FrameInstructions.size() - 1;
335}
336
337/// This discards all of the MachineBasicBlock numbers and recomputes them.
338/// This guarantees that the MBB numbers are sequential, dense, and match the
339/// ordering of the blocks within the function. If a specific MachineBasicBlock
340/// is specified, only that block and those after it are renumbered.
342 if (empty()) { MBBNumbering.clear(); return; }
344 if (MBB == nullptr)
345 MBBI = begin();
346 else
347 MBBI = MBB->getIterator();
348
349 // Figure out the block number this should have.
350 unsigned BlockNo = 0;
351 if (MBBI != begin())
352 BlockNo = std::prev(MBBI)->getNumber() + 1;
353
354 for (; MBBI != E; ++MBBI, ++BlockNo) {
355 if (MBBI->getNumber() != (int)BlockNo) {
356 // Remove use of the old number.
357 if (MBBI->getNumber() != -1) {
358 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
359 "MBB number mismatch!");
360 MBBNumbering[MBBI->getNumber()] = nullptr;
361 }
362
363 // If BlockNo is already taken, set that block's number to -1.
364 if (MBBNumbering[BlockNo])
365 MBBNumbering[BlockNo]->setNumber(-1);
366
367 MBBNumbering[BlockNo] = &*MBBI;
368 MBBI->setNumber(BlockNo);
369 }
370 }
371
372 // Okay, all the blocks are renumbered. If we have compactified the block
373 // numbering, shrink MBBNumbering now.
374 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
375 MBBNumbering.resize(BlockNo);
376}
377
378/// This method iterates over the basic blocks and assigns their IsBeginSection
379/// and IsEndSection fields. This must be called after MBB layout is finalized
380/// and the SectionID's are assigned to MBBs.
383 auto CurrentSectionID = front().getSectionID();
384 for (auto MBBI = std::next(begin()), E = end(); MBBI != E; ++MBBI) {
385 if (MBBI->getSectionID() == CurrentSectionID)
386 continue;
388 std::prev(MBBI)->setIsEndSection();
389 CurrentSectionID = MBBI->getSectionID();
390 }
392}
393
394/// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
396 DebugLoc DL,
397 bool NoImplicit) {
398 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
399 MachineInstr(*this, MCID, std::move(DL), NoImplicit);
400}
401
402/// Create a new MachineInstr which is a copy of the 'Orig' instruction,
403/// identical in all ways except the instruction has no parent, prev, or next.
406 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
407 MachineInstr(*this, *Orig);
408}
409
412 const MachineInstr &Orig) {
413 MachineInstr *FirstClone = nullptr;
415 while (true) {
416 MachineInstr *Cloned = CloneMachineInstr(&*I);
417 MBB.insert(InsertBefore, Cloned);
418 if (FirstClone == nullptr) {
419 FirstClone = Cloned;
420 } else {
421 Cloned->bundleWithPred();
422 }
423
424 if (!I->isBundledWithSucc())
425 break;
426 ++I;
427 }
428 // Copy over call site info to the cloned instruction if needed. If Orig is in
429 // a bundle, copyCallSiteInfo takes care of finding the call instruction in
430 // the bundle.
431 if (Orig.shouldUpdateCallSiteInfo())
432 copyCallSiteInfo(&Orig, FirstClone);
433 return *FirstClone;
434}
435
436/// Delete the given MachineInstr.
437///
438/// This function also serves as the MachineInstr destructor - the real
439/// ~MachineInstr() destructor must be empty.
441 // Verify that a call site info is at valid state. This assertion should
442 // be triggered during the implementation of support for the
443 // call site info of a new architecture. If the assertion is triggered,
444 // back trace will tell where to insert a call to updateCallSiteInfo().
445 assert((!MI->isCandidateForCallSiteEntry() || !CallSitesInfo.contains(MI)) &&
446 "Call site info was not updated!");
447 // Strip it for parts. The operand array and the MI object itself are
448 // independently recyclable.
449 if (MI->Operands)
450 deallocateOperandArray(MI->CapOperands, MI->Operands);
451 // Don't call ~MachineInstr() which must be trivial anyway because
452 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
453 // destructors.
454 InstructionRecycler.Deallocate(Allocator, MI);
455}
456
457/// Allocate a new MachineBasicBlock. Use this instead of
458/// `new MachineBasicBlock'.
461 std::optional<UniqueBBID> BBID) {
463 new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
464 MachineBasicBlock(*this, BB);
465 // Set BBID for `-basic-block=sections=labels` and
466 // `-basic-block-sections=list` to allow robust mapping of profiles to basic
467 // blocks.
468 if (Target.getBBSectionsType() == BasicBlockSection::Labels ||
469 Target.getBBSectionsType() == BasicBlockSection::List)
470 MBB->setBBID(BBID.has_value() ? *BBID : UniqueBBID{NextBBID++, 0});
471 return MBB;
472}
473
474/// Delete the given MachineBasicBlock.
476 assert(MBB->getParent() == this && "MBB parent mismatch!");
477 // Clean up any references to MBB in jump tables before deleting it.
478 if (JumpTableInfo)
479 JumpTableInfo->RemoveMBBFromJumpTables(MBB);
480 MBB->~MachineBasicBlock();
481 BasicBlockRecycler.Deallocate(Allocator, MBB);
482}
483
486 Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
487 SyncScope::ID SSID, AtomicOrdering Ordering,
488 AtomicOrdering FailureOrdering) {
489 return new (Allocator)
490 MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
491 SSID, Ordering, FailureOrdering);
492}
493
496 Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
497 SyncScope::ID SSID, AtomicOrdering Ordering,
498 AtomicOrdering FailureOrdering) {
499 return new (Allocator)
500 MachineMemOperand(PtrInfo, f, MemTy, base_alignment, AAInfo, Ranges, SSID,
501 Ordering, FailureOrdering);
502}
503
505 const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, uint64_t Size) {
506 return new (Allocator)
507 MachineMemOperand(PtrInfo, MMO->getFlags(), Size, MMO->getBaseAlign(),
508 AAMDNodes(), nullptr, MMO->getSyncScopeID(),
510}
511
513 const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, LLT Ty) {
514 return new (Allocator)
515 MachineMemOperand(PtrInfo, MMO->getFlags(), Ty, MMO->getBaseAlign(),
516 AAMDNodes(), nullptr, MMO->getSyncScopeID(),
518}
519
522 int64_t Offset, LLT Ty) {
523 const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
524
525 // If there is no pointer value, the offset isn't tracked so we need to adjust
526 // the base alignment.
527 Align Alignment = PtrInfo.V.isNull()
529 : MMO->getBaseAlign();
530
531 // Do not preserve ranges, since we don't necessarily know what the high bits
532 // are anymore.
533 return new (Allocator) MachineMemOperand(
534 PtrInfo.getWithOffset(Offset), MMO->getFlags(), Ty, Alignment,
535 MMO->getAAInfo(), nullptr, MMO->getSyncScopeID(),
537}
538
541 const AAMDNodes &AAInfo) {
542 MachinePointerInfo MPI = MMO->getValue() ?
543 MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
545
546 return new (Allocator) MachineMemOperand(
547 MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(), AAInfo,
548 MMO->getRanges(), MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
549 MMO->getFailureOrdering());
550}
551
555 return new (Allocator) MachineMemOperand(
556 MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(),
557 MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(),
559}
560
561MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo(
562 ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol,
563 MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker, MDNode *PCSections,
564 uint32_t CFIType) {
565 return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
566 PostInstrSymbol, HeapAllocMarker,
567 PCSections, CFIType);
568}
569
571 char *Dest = Allocator.Allocate<char>(Name.size() + 1);
572 llvm::copy(Name, Dest);
573 Dest[Name.size()] = 0;
574 return Dest;
575}
576
578 unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
579 unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
580 uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
581 memset(Mask, 0, Size * sizeof(Mask[0]));
582 return Mask;
583}
584
586 int* AllocMask = Allocator.Allocate<int>(Mask.size());
587 copy(Mask, AllocMask);
588 return {AllocMask, Mask.size()};
589}
590
591#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
593 print(dbgs());
594}
595#endif
596
598 return getFunction().getName();
599}
600
601void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
602 OS << "# Machine code for function " << getName() << ": ";
604 OS << '\n';
605
606 // Print Frame Information
607 FrameInfo->print(*this, OS);
608
609 // Print JumpTable Information
610 if (JumpTableInfo)
611 JumpTableInfo->print(OS);
612
613 // Print Constant Pool
614 ConstantPool->print(OS);
615
617
618 if (RegInfo && !RegInfo->livein_empty()) {
619 OS << "Function Live Ins: ";
621 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
622 OS << printReg(I->first, TRI);
623 if (I->second)
624 OS << " in " << printReg(I->second, TRI);
625 if (std::next(I) != E)
626 OS << ", ";
627 }
628 OS << '\n';
629 }
630
633 for (const auto &BB : *this) {
634 OS << '\n';
635 // If we print the whole function, print it at its most verbose level.
636 BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
637 }
638
639 OS << "\n# End machine code for function " << getName() << ".\n\n";
640}
641
642/// True if this function needs frame moves for debug or exceptions.
644 return getMMI().hasDebugInfo() ||
647}
648
649namespace llvm {
650
651 template<>
654
655 static std::string getGraphName(const MachineFunction *F) {
656 return ("CFG for '" + F->getName() + "' function").str();
657 }
658
659 std::string getNodeLabel(const MachineBasicBlock *Node,
660 const MachineFunction *Graph) {
661 std::string OutStr;
662 {
663 raw_string_ostream OSS(OutStr);
664
665 if (isSimple()) {
666 OSS << printMBBReference(*Node);
667 if (const BasicBlock *BB = Node->getBasicBlock())
668 OSS << ": " << BB->getName();
669 } else
670 Node->print(OSS);
671 }
672
673 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
674
675 // Process string output to make it nicer...
676 for (unsigned i = 0; i != OutStr.length(); ++i)
677 if (OutStr[i] == '\n') { // Left justify
678 OutStr[i] = '\\';
679 OutStr.insert(OutStr.begin()+i+1, 'l');
680 }
681 return OutStr;
682 }
683 };
684
685} // end namespace llvm
686
688{
689#ifndef NDEBUG
690 ViewGraph(this, "mf" + getName());
691#else
692 errs() << "MachineFunction::viewCFG is only available in debug builds on "
693 << "systems with Graphviz or gv!\n";
694#endif // NDEBUG
695}
696
698{
699#ifndef NDEBUG
700 ViewGraph(this, "mf" + getName(), true);
701#else
702 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
703 << "systems with Graphviz or gv!\n";
704#endif // NDEBUG
705}
706
707/// Add the specified physical register as a live-in value and
708/// create a corresponding virtual register for it.
710 const TargetRegisterClass *RC) {
712 Register VReg = MRI.getLiveInVirtReg(PReg);
713 if (VReg) {
714 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
715 (void)VRegRC;
716 // A physical register can be added several times.
717 // Between two calls, the register class of the related virtual register
718 // may have been constrained to match some operation constraints.
719 // In that case, check that the current register class includes the
720 // physical register and is a sub class of the specified RC.
721 assert((VRegRC == RC || (VRegRC->contains(PReg) &&
722 RC->hasSubClassEq(VRegRC))) &&
723 "Register class mismatch!");
724 return VReg;
725 }
726 VReg = MRI.createVirtualRegister(RC);
727 MRI.addLiveIn(PReg, VReg);
728 return VReg;
729}
730
731/// Return the MCSymbol for the specified non-empty jump table.
732/// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
733/// normal 'L' label is returned.
735 bool isLinkerPrivate) const {
736 const DataLayout &DL = getDataLayout();
737 assert(JumpTableInfo && "No jump tables");
738 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
739
740 StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
741 : DL.getPrivateGlobalPrefix();
744 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
745 return Ctx.getOrCreateSymbol(Name);
746}
747
748/// Return a function-local symbol to represent the PIC base.
750 const DataLayout &DL = getDataLayout();
751 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
752 Twine(getFunctionNumber()) + "$pb");
753}
754
755/// \name Exception Handling
756/// \{
757
760 unsigned N = LandingPads.size();
761 for (unsigned i = 0; i < N; ++i) {
762 LandingPadInfo &LP = LandingPads[i];
763 if (LP.LandingPadBlock == LandingPad)
764 return LP;
765 }
766
767 LandingPads.push_back(LandingPadInfo(LandingPad));
768 return LandingPads[N];
769}
770
772 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
774 LP.BeginLabels.push_back(BeginLabel);
775 LP.EndLabels.push_back(EndLabel);
776}
777
779 MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
781 LP.LandingPadLabel = LandingPadLabel;
782
783 const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
784 if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
785 // If there's no typeid list specified, then "cleanup" is implicit.
786 // Otherwise, id 0 is reserved for the cleanup action.
787 if (LPI->isCleanup() && LPI->getNumClauses() != 0)
788 LP.TypeIds.push_back(0);
789
790 // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
791 // correct, but we need to do it this way because of how the DWARF EH
792 // emitter processes the clauses.
793 for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
794 Value *Val = LPI->getClause(I - 1);
795 if (LPI->isCatch(I - 1)) {
796 LP.TypeIds.push_back(
797 getTypeIDFor(dyn_cast<GlobalValue>(Val->stripPointerCasts())));
798 } else {
799 // Add filters in a list.
800 auto *CVal = cast<Constant>(Val);
801 SmallVector<unsigned, 4> FilterList;
802 for (const Use &U : CVal->operands())
803 FilterList.push_back(
804 getTypeIDFor(cast<GlobalValue>(U->stripPointerCasts())));
805
806 LP.TypeIds.push_back(getFilterIDFor(FilterList));
807 }
808 }
809
810 } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
811 for (unsigned I = CPI->arg_size(); I != 0; --I) {
812 auto *TypeInfo =
813 dyn_cast<GlobalValue>(CPI->getArgOperand(I - 1)->stripPointerCasts());
814 LP.TypeIds.push_back(getTypeIDFor(TypeInfo));
815 }
816
817 } else {
818 assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
819 }
820
821 return LandingPadLabel;
822}
823
825 ArrayRef<unsigned> Sites) {
826 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
827}
828
830 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
831 if (TypeInfos[i] == TI) return i + 1;
832
833 TypeInfos.push_back(TI);
834 return TypeInfos.size();
835}
836
838 // If the new filter coincides with the tail of an existing filter, then
839 // re-use the existing filter. Folding filters more than this requires
840 // re-ordering filters and/or their elements - probably not worth it.
841 for (unsigned i : FilterEnds) {
842 unsigned j = TyIds.size();
843
844 while (i && j)
845 if (FilterIds[--i] != TyIds[--j])
846 goto try_next;
847
848 if (!j)
849 // The new filter coincides with range [i, end) of the existing filter.
850 return -(1 + i);
851
852try_next:;
853 }
854
855 // Add the new filter.
856 int FilterID = -(1 + FilterIds.size());
857 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
858 llvm::append_range(FilterIds, TyIds);
859 FilterEnds.push_back(FilterIds.size());
860 FilterIds.push_back(0); // terminator
861 return FilterID;
862}
863
865MachineFunction::getCallSiteInfo(const MachineInstr *MI) {
866 assert(MI->isCandidateForCallSiteEntry() &&
867 "Call site info refers only to call (MI) candidates");
868
869 if (!Target.Options.EmitCallSiteInfo)
870 return CallSitesInfo.end();
871 return CallSitesInfo.find(MI);
872}
873
874/// Return the call machine instruction or find a call within bundle.
876 if (!MI->isBundle())
877 return MI;
878
879 for (const auto &BMI : make_range(getBundleStart(MI->getIterator()),
880 getBundleEnd(MI->getIterator())))
881 if (BMI.isCandidateForCallSiteEntry())
882 return &BMI;
883
884 llvm_unreachable("Unexpected bundle without a call site candidate");
885}
886
888 assert(MI->shouldUpdateCallSiteInfo() &&
889 "Call site info refers only to call (MI) candidates or "
890 "candidates inside bundles");
891
892 const MachineInstr *CallMI = getCallInstr(MI);
893 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI);
894 if (CSIt == CallSitesInfo.end())
895 return;
896 CallSitesInfo.erase(CSIt);
897}
898
900 const MachineInstr *New) {
902 "Call site info refers only to call (MI) candidates or "
903 "candidates inside bundles");
904
905 if (!New->isCandidateForCallSiteEntry())
906 return eraseCallSiteInfo(Old);
907
908 const MachineInstr *OldCallMI = getCallInstr(Old);
909 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
910 if (CSIt == CallSitesInfo.end())
911 return;
912
913 CallSiteInfo CSInfo = CSIt->second;
914 CallSitesInfo[New] = CSInfo;
915}
916
918 const MachineInstr *New) {
920 "Call site info refers only to call (MI) candidates or "
921 "candidates inside bundles");
922
923 if (!New->isCandidateForCallSiteEntry())
924 return eraseCallSiteInfo(Old);
925
926 const MachineInstr *OldCallMI = getCallInstr(Old);
927 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
928 if (CSIt == CallSitesInfo.end())
929 return;
930
931 CallSiteInfo CSInfo = std::move(CSIt->second);
932 CallSitesInfo.erase(CSIt);
933 CallSitesInfo[New] = CSInfo;
934}
935
938}
939
942 unsigned Subreg) {
943 // Catch any accidental self-loops.
944 assert(A.first != B.first);
945 // Don't allow any substitutions _from_ the memory operand number.
946 assert(A.second != DebugOperandMemNumber);
947
948 DebugValueSubstitutions.push_back({A, B, Subreg});
949}
950
952 MachineInstr &New,
953 unsigned MaxOperand) {
954 // If the Old instruction wasn't tracked at all, there is no work to do.
955 unsigned OldInstrNum = Old.peekDebugInstrNum();
956 if (!OldInstrNum)
957 return;
958
959 // Iterate over all operands looking for defs to create substitutions for.
960 // Avoid creating new instr numbers unless we create a new substitution.
961 // While this has no functional effect, it risks confusing someone reading
962 // MIR output.
963 // Examine all the operands, or the first N specified by the caller.
964 MaxOperand = std::min(MaxOperand, Old.getNumOperands());
965 for (unsigned int I = 0; I < MaxOperand; ++I) {
966 const auto &OldMO = Old.getOperand(I);
967 auto &NewMO = New.getOperand(I);
968 (void)NewMO;
969
970 if (!OldMO.isReg() || !OldMO.isDef())
971 continue;
972 assert(NewMO.isDef());
973
974 unsigned NewInstrNum = New.getDebugInstrNum();
975 makeDebugValueSubstitution(std::make_pair(OldInstrNum, I),
976 std::make_pair(NewInstrNum, I));
977 }
978}
979
983 const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
984
985 // Check whether this copy-like instruction has already been salvaged into
986 // an operand pair.
987 Register Dest;
988 if (auto CopyDstSrc = TII.isCopyInstr(MI)) {
989 Dest = CopyDstSrc->Destination->getReg();
990 } else {
991 assert(MI.isSubregToReg());
992 Dest = MI.getOperand(0).getReg();
993 }
994
995 auto CacheIt = DbgPHICache.find(Dest);
996 if (CacheIt != DbgPHICache.end())
997 return CacheIt->second;
998
999 // Calculate the instruction number to use, or install a DBG_PHI.
1000 auto OperandPair = salvageCopySSAImpl(MI);
1001 DbgPHICache.insert({Dest, OperandPair});
1002 return OperandPair;
1003}
1004
1007 MachineRegisterInfo &MRI = getRegInfo();
1008 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
1009 const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
1010
1011 // Chase the value read by a copy-like instruction back to the instruction
1012 // that ultimately _defines_ that value. This may pass:
1013 // * Through multiple intermediate copies, including subregister moves /
1014 // copies,
1015 // * Copies from physical registers that must then be traced back to the
1016 // defining instruction,
1017 // * Or, physical registers may be live-in to (only) the entry block, which
1018 // requires a DBG_PHI to be created.
1019 // We can pursue this problem in that order: trace back through copies,
1020 // optionally through a physical register, to a defining instruction. We
1021 // should never move from physreg to vreg. As we're still in SSA form, no need
1022 // to worry about partial definitions of registers.
1023
1024 // Helper lambda to interpret a copy-like instruction. Takes instruction,
1025 // returns the register read and any subregister identifying which part is
1026 // read.
1027 auto GetRegAndSubreg =
1028 [&](const MachineInstr &Cpy) -> std::pair<Register, unsigned> {
1029 Register NewReg, OldReg;
1030 unsigned SubReg;
1031 if (Cpy.isCopy()) {
1032 OldReg = Cpy.getOperand(0).getReg();
1033 NewReg = Cpy.getOperand(1).getReg();
1034 SubReg = Cpy.getOperand(1).getSubReg();
1035 } else if (Cpy.isSubregToReg()) {
1036 OldReg = Cpy.getOperand(0).getReg();
1037 NewReg = Cpy.getOperand(2).getReg();
1038 SubReg = Cpy.getOperand(3).getImm();
1039 } else {
1040 auto CopyDetails = *TII.isCopyInstr(Cpy);
1041 const MachineOperand &Src = *CopyDetails.Source;
1042 const MachineOperand &Dest = *CopyDetails.Destination;
1043 OldReg = Dest.getReg();
1044 NewReg = Src.getReg();
1045 SubReg = Src.getSubReg();
1046 }
1047
1048 return {NewReg, SubReg};
1049 };
1050
1051 // First seek either the defining instruction, or a copy from a physreg.
1052 // During search, the current state is the current copy instruction, and which
1053 // register we've read. Accumulate qualifying subregisters into SubregsSeen;
1054 // deal with those later.
1055 auto State = GetRegAndSubreg(MI);
1056 auto CurInst = MI.getIterator();
1057 SmallVector<unsigned, 4> SubregsSeen;
1058 while (true) {
1059 // If we've found a copy from a physreg, first portion of search is over.
1060 if (!State.first.isVirtual())
1061 break;
1062
1063 // Record any subregister qualifier.
1064 if (State.second)
1065 SubregsSeen.push_back(State.second);
1066
1067 assert(MRI.hasOneDef(State.first));
1068 MachineInstr &Inst = *MRI.def_begin(State.first)->getParent();
1069 CurInst = Inst.getIterator();
1070
1071 // Any non-copy instruction is the defining instruction we're seeking.
1072 if (!Inst.isCopyLike() && !TII.isCopyInstr(Inst))
1073 break;
1074 State = GetRegAndSubreg(Inst);
1075 };
1076
1077 // Helper lambda to apply additional subregister substitutions to a known
1078 // instruction/operand pair. Adds new (fake) substitutions so that we can
1079 // record the subregister. FIXME: this isn't very space efficient if multiple
1080 // values are tracked back through the same copies; cache something later.
1081 auto ApplySubregisters =
1083 for (unsigned Subreg : reverse(SubregsSeen)) {
1084 // Fetch a new instruction number, not attached to an actual instruction.
1085 unsigned NewInstrNumber = getNewDebugInstrNum();
1086 // Add a substitution from the "new" number to the known one, with a
1087 // qualifying subreg.
1088 makeDebugValueSubstitution({NewInstrNumber, 0}, P, Subreg);
1089 // Return the new number; to find the underlying value, consumers need to
1090 // deal with the qualifying subreg.
1091 P = {NewInstrNumber, 0};
1092 }
1093 return P;
1094 };
1095
1096 // If we managed to find the defining instruction after COPYs, return an
1097 // instruction / operand pair after adding subregister qualifiers.
1098 if (State.first.isVirtual()) {
1099 // Virtual register def -- we can just look up where this happens.
1100 MachineInstr *Inst = MRI.def_begin(State.first)->getParent();
1101 for (auto &MO : Inst->all_defs()) {
1102 if (MO.getReg() != State.first)
1103 continue;
1104 return ApplySubregisters({Inst->getDebugInstrNum(), MO.getOperandNo()});
1105 }
1106
1107 llvm_unreachable("Vreg def with no corresponding operand?");
1108 }
1109
1110 // Our search ended in a copy from a physreg: walk back up the function
1111 // looking for whatever defines the physreg.
1112 assert(CurInst->isCopyLike() || TII.isCopyInstr(*CurInst));
1113 State = GetRegAndSubreg(*CurInst);
1114 Register RegToSeek = State.first;
1115
1116 auto RMII = CurInst->getReverseIterator();
1117 auto PrevInstrs = make_range(RMII, CurInst->getParent()->instr_rend());
1118 for (auto &ToExamine : PrevInstrs) {
1119 for (auto &MO : ToExamine.all_defs()) {
1120 // Test for operand that defines something aliasing RegToSeek.
1121 if (!TRI.regsOverlap(RegToSeek, MO.getReg()))
1122 continue;
1123
1124 return ApplySubregisters(
1125 {ToExamine.getDebugInstrNum(), MO.getOperandNo()});
1126 }
1127 }
1128
1129 MachineBasicBlock &InsertBB = *CurInst->getParent();
1130
1131 // We reached the start of the block before finding a defining instruction.
1132 // There are numerous scenarios where this can happen:
1133 // * Constant physical registers,
1134 // * Several intrinsics that allow LLVM-IR to read arbitary registers,
1135 // * Arguments in the entry block,
1136 // * Exception handling landing pads.
1137 // Validating all of them is too difficult, so just insert a DBG_PHI reading
1138 // the variable value at this position, rather than checking it makes sense.
1139
1140 // Create DBG_PHI for specified physreg.
1141 auto Builder = BuildMI(InsertBB, InsertBB.getFirstNonPHI(), DebugLoc(),
1142 TII.get(TargetOpcode::DBG_PHI));
1143 Builder.addReg(State.first);
1144 unsigned NewNum = getNewDebugInstrNum();
1145 Builder.addImm(NewNum);
1146 return ApplySubregisters({NewNum, 0u});
1147}
1148
1150 auto *TII = getSubtarget().getInstrInfo();
1151
1152 auto MakeUndefDbgValue = [&](MachineInstr &MI) {
1153 const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_VALUE_LIST);
1154 MI.setDesc(RefII);
1155 MI.setDebugValueUndef();
1156 };
1157
1159 for (auto &MBB : *this) {
1160 for (auto &MI : MBB) {
1161 if (!MI.isDebugRef())
1162 continue;
1163
1164 bool IsValidRef = true;
1165
1166 for (MachineOperand &MO : MI.debug_operands()) {
1167 if (!MO.isReg())
1168 continue;
1169
1170 Register Reg = MO.getReg();
1171
1172 // Some vregs can be deleted as redundant in the meantime. Mark those
1173 // as DBG_VALUE $noreg. Additionally, some normal instructions are
1174 // quickly deleted, leaving dangling references to vregs with no def.
1175 if (Reg == 0 || !RegInfo->hasOneDef(Reg)) {
1176 IsValidRef = false;
1177 break;
1178 }
1179
1180 assert(Reg.isVirtual());
1181 MachineInstr &DefMI = *RegInfo->def_instr_begin(Reg);
1182
1183 // If we've found a copy-like instruction, follow it back to the
1184 // instruction that defines the source value, see salvageCopySSA docs
1185 // for why this is important.
1186 if (DefMI.isCopyLike() || TII->isCopyInstr(DefMI)) {
1187 auto Result = salvageCopySSA(DefMI, ArgDbgPHIs);
1188 MO.ChangeToDbgInstrRef(Result.first, Result.second);
1189 } else {
1190 // Otherwise, identify the operand number that the VReg refers to.
1191 unsigned OperandIdx = 0;
1192 for (const auto &DefMO : DefMI.operands()) {
1193 if (DefMO.isReg() && DefMO.isDef() && DefMO.getReg() == Reg)
1194 break;
1195 ++OperandIdx;
1196 }
1197 assert(OperandIdx < DefMI.getNumOperands());
1198
1199 // Morph this instr ref to point at the given instruction and operand.
1200 unsigned ID = DefMI.getDebugInstrNum();
1201 MO.ChangeToDbgInstrRef(ID, OperandIdx);
1202 }
1203 }
1204
1205 if (!IsValidRef)
1206 MakeUndefDbgValue(MI);
1207 }
1208 }
1209}
1210
1212 // Disable instr-ref at -O0: it's very slow (in compile time). We can still
1213 // have optimized code inlined into this unoptimized code, however with
1214 // fewer and less aggressive optimizations happening, coverage and accuracy
1215 // should not suffer.
1216 if (getTarget().getOptLevel() == CodeGenOptLevel::None)
1217 return false;
1218
1219 // Don't use instr-ref if this function is marked optnone.
1220 if (F.hasFnAttribute(Attribute::OptimizeNone))
1221 return false;
1222
1223 if (llvm::debuginfoShouldUseDebugInstrRef(getTarget().getTargetTriple()))
1224 return true;
1225
1226 return false;
1227}
1228
1230 return UseDebugInstrRef;
1231}
1232
1235}
1236
1237// Use one million as a high / reserved number.
1238const unsigned MachineFunction::DebugOperandMemNumber = 1000000;
1239
1240/// \}
1241
1242//===----------------------------------------------------------------------===//
1243// MachineJumpTableInfo implementation
1244//===----------------------------------------------------------------------===//
1245
1246/// Return the size of each entry in the jump table.
1248 // The size of a jump table entry is 4 bytes unless the entry is just the
1249 // address of a block, in which case it is the pointer size.
1250 switch (getEntryKind()) {
1252 return TD.getPointerSize();
1255 return 8;
1259 return 4;
1261 return 0;
1262 }
1263 llvm_unreachable("Unknown jump table encoding!");
1264}
1265
1266/// Return the alignment of each entry in the jump table.
1268 // The alignment of a jump table entry is the alignment of int32 unless the
1269 // entry is just the address of a block, in which case it is the pointer
1270 // alignment.
1271 switch (getEntryKind()) {
1273 return TD.getPointerABIAlignment(0).value();
1276 return TD.getABIIntegerTypeAlignment(64).value();
1280 return TD.getABIIntegerTypeAlignment(32).value();
1282 return 1;
1283 }
1284 llvm_unreachable("Unknown jump table encoding!");
1285}
1286
1287/// Create a new jump table entry in the jump table info.
1289 const std::vector<MachineBasicBlock*> &DestBBs) {
1290 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
1291 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
1292 return JumpTables.size()-1;
1293}
1294
1295/// If Old is the target of any jump tables, update the jump tables to branch
1296/// to New instead.
1298 MachineBasicBlock *New) {
1299 assert(Old != New && "Not making a change?");
1300 bool MadeChange = false;
1301 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
1302 ReplaceMBBInJumpTable(i, Old, New);
1303 return MadeChange;
1304}
1305
1306/// If MBB is present in any jump tables, remove it.
1308 bool MadeChange = false;
1309 for (MachineJumpTableEntry &JTE : JumpTables) {
1310 auto removeBeginItr = std::remove(JTE.MBBs.begin(), JTE.MBBs.end(), MBB);
1311 MadeChange |= (removeBeginItr != JTE.MBBs.end());
1312 JTE.MBBs.erase(removeBeginItr, JTE.MBBs.end());
1313 }
1314 return MadeChange;
1315}
1316
1317/// If Old is a target of the jump tables, update the jump table to branch to
1318/// New instead.
1320 MachineBasicBlock *Old,
1321 MachineBasicBlock *New) {
1322 assert(Old != New && "Not making a change?");
1323 bool MadeChange = false;
1324 MachineJumpTableEntry &JTE = JumpTables[Idx];
1325 for (MachineBasicBlock *&MBB : JTE.MBBs)
1326 if (MBB == Old) {
1327 MBB = New;
1328 MadeChange = true;
1329 }
1330 return MadeChange;
1331}
1332
1334 if (JumpTables.empty()) return;
1335
1336 OS << "Jump Tables:\n";
1337
1338 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
1339 OS << printJumpTableEntryReference(i) << ':';
1340 for (const MachineBasicBlock *MBB : JumpTables[i].MBBs)
1341 OS << ' ' << printMBBReference(*MBB);
1342 if (i != e)
1343 OS << '\n';
1344 }
1345
1346 OS << '\n';
1347}
1348
1349#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1351#endif
1352
1354 return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
1355}
1356
1357//===----------------------------------------------------------------------===//
1358// MachineConstantPool implementation
1359//===----------------------------------------------------------------------===//
1360
1361void MachineConstantPoolValue::anchor() {}
1362
1364 return DL.getTypeAllocSize(Ty);
1365}
1366
1369 return Val.MachineCPVal->getSizeInBytes(DL);
1370 return DL.getTypeAllocSize(Val.ConstVal->getType());
1371}
1372
1375 return true;
1376 return Val.ConstVal->needsDynamicRelocation();
1377}
1378
1381 if (needsRelocation())
1383 switch (getSizeInBytes(*DL)) {
1384 case 4:
1386 case 8:
1388 case 16:
1390 case 32:
1392 default:
1393 return SectionKind::getReadOnly();
1394 }
1395}
1396
1398 // A constant may be a member of both Constants and MachineCPVsSharingEntries,
1399 // so keep track of which we've deleted to avoid double deletions.
1401 for (const MachineConstantPoolEntry &C : Constants)
1402 if (C.isMachineConstantPoolEntry()) {
1403 Deleted.insert(C.Val.MachineCPVal);
1404 delete C.Val.MachineCPVal;
1405 }
1406 for (MachineConstantPoolValue *CPV : MachineCPVsSharingEntries) {
1407 if (Deleted.count(CPV) == 0)
1408 delete CPV;
1409 }
1410}
1411
1412/// Test whether the given two constants can be allocated the same constant pool
1413/// entry referenced by \param A.
1414static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
1415 const DataLayout &DL) {
1416 // Handle the trivial case quickly.
1417 if (A == B) return true;
1418
1419 // If they have the same type but weren't the same constant, quickly
1420 // reject them.
1421 if (A->getType() == B->getType()) return false;
1422
1423 // We can't handle structs or arrays.
1424 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
1425 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
1426 return false;
1427
1428 // For now, only support constants with the same size.
1429 uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
1430 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
1431 return false;
1432
1433 bool ContainsUndefOrPoisonA = A->containsUndefOrPoisonElement();
1434
1435 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
1436
1437 // Try constant folding a bitcast of both instructions to an integer. If we
1438 // get two identical ConstantInt's, then we are good to share them. We use
1439 // the constant folding APIs to do this so that we get the benefit of
1440 // DataLayout.
1441 if (isa<PointerType>(A->getType()))
1442 A = ConstantFoldCastOperand(Instruction::PtrToInt,
1443 const_cast<Constant *>(A), IntTy, DL);
1444 else if (A->getType() != IntTy)
1445 A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
1446 IntTy, DL);
1447 if (isa<PointerType>(B->getType()))
1448 B = ConstantFoldCastOperand(Instruction::PtrToInt,
1449 const_cast<Constant *>(B), IntTy, DL);
1450 else if (B->getType() != IntTy)
1451 B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
1452 IntTy, DL);
1453
1454 if (A != B)
1455 return false;
1456
1457 // Constants only safely match if A doesn't contain undef/poison.
1458 // As we'll be reusing A, it doesn't matter if B contain undef/poison.
1459 // TODO: Handle cases where A and B have the same undef/poison elements.
1460 // TODO: Merge A and B with mismatching undef/poison elements.
1461 return !ContainsUndefOrPoisonA;
1462}
1463
1464/// Create a new entry in the constant pool or return an existing one.
1465/// User must specify the log2 of the minimum required alignment for the object.
1467 Align Alignment) {
1468 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1469
1470 // Check to see if we already have this constant.
1471 //
1472 // FIXME, this could be made much more efficient for large constant pools.
1473 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1474 if (!Constants[i].isMachineConstantPoolEntry() &&
1475 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
1476 if (Constants[i].getAlign() < Alignment)
1477 Constants[i].Alignment = Alignment;
1478 return i;
1479 }
1480
1481 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
1482 return Constants.size()-1;
1483}
1484
1486 Align Alignment) {
1487 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1488
1489 // Check to see if we already have this constant.
1490 //
1491 // FIXME, this could be made much more efficient for large constant pools.
1492 int Idx = V->getExistingMachineCPValue(this, Alignment);
1493 if (Idx != -1) {
1494 MachineCPVsSharingEntries.insert(V);
1495 return (unsigned)Idx;
1496 }
1497
1498 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
1499 return Constants.size()-1;
1500}
1501
1503 if (Constants.empty()) return;
1504
1505 OS << "Constant Pool:\n";
1506 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1507 OS << " cp#" << i << ": ";
1508 if (Constants[i].isMachineConstantPoolEntry())
1509 Constants[i].Val.MachineCPVal->print(OS);
1510 else
1511 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
1512 OS << ", align=" << Constants[i].getAlign().value();
1513 OS << "\n";
1514 }
1515}
1516
1517//===----------------------------------------------------------------------===//
1518// Template specialization for MachineFunction implementation of
1519// ProfileSummaryInfo::getEntryCount().
1520//===----------------------------------------------------------------------===//
1521template <>
1522std::optional<Function::ProfileCount>
1523ProfileSummaryInfo::getEntryCount<llvm::MachineFunction>(
1524 const llvm::MachineFunction *F) const {
1525 return F->getFunction().getEntryCount();
1526}
1527
1528#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1530#endif
unsigned SubReg
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder MachineInstrBuilder & DefMI
aarch64 promote const
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
This file implements the BitVector class.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:510
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
std::string Name
uint64_t Size
Symbol * Sym
Definition: ELF_riscv.cpp:477
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
static Align getFnStackAlignment(const TargetSubtargetInfo *STI, const Function &F)
static cl::opt< unsigned > AlignAllFunctions("align-all-functions", cl::desc("Force the alignment of all functions in log2 format (e.g. 4 " "means align on 16B boundaries)."), cl::init(0), cl::Hidden)
static const MachineInstr * getCallInstr(const MachineInstr *MI)
Return the call machine instruction or find a call within bundle.
static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B, const DataLayout &DL)
Test whether the given two constants can be allocated the same constant pool entry referenced by.
void setUnsafeStackSize(const Function &F, MachineFrameInfo &FrameInfo)
static const char * getPropertyName(MachineFunctionProperties::Property Prop)
unsigned const TargetRegisterInfo * TRI
unsigned Reg
This file contains the declarations for metadata subclasses.
Module.h This file contains the declarations for the Module class.
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isSimple(Instruction *I)
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
This file defines the SmallString class.
This file defines the SmallVector class.
This file describes how to lower LLVM code to machine code.
void clear(AllocatorType &Allocator)
Release all the tracked allocations to the allocator.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:154
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
iterator begin() const
Definition: ArrayRef.h:153
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:399
LLVM_ATTRIBUTE_RETURNS_NONNULL void * Allocate(size_t Size, Align Alignment)
Allocate space at the specified alignment.
Definition: Allocator.h:148
void Deallocate(const void *Ptr, size_t Size, size_t)
Definition: Allocator.h:218
This is an important base class in LLVM.
Definition: Constant.h:41
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Align getABIIntegerTypeAlignment(unsigned BitWidth) const
Returns the minimum ABI-required alignment for an integer type of the specified bitwidth.
Definition: DataLayout.h:533
unsigned getPointerSize(unsigned AS=0) const
Layout pointer size in bytes, rounded up to a whole number of bytes.
Definition: DataLayout.cpp:750
Align getPointerABIAlignment(unsigned AS) const
Layout pointer alignment.
Definition: DataLayout.cpp:742
A debug info location.
Definition: DebugLoc.h:33
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
bool erase(const KeyT &Val)
Definition: DenseMap.h:329
iterator end()
Definition: DenseMap.h:84
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:145
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
MaybeAlign getFnStackAlign() const
Return the stack alignment for the function.
Definition: Function.h:446
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:846
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1867
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
Definition: Function.cpp:725
bool needsUnwindTableEntry() const
True if this function needs an unwind table.
Definition: Function.h:652
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.cpp:666
bool hasMetadata() const
Return true if this value has any metadata attached to it.
Definition: Value.h:589
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Value.h:565
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:652
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:285
This class describes a target machine that is implemented with the LLVM target-independent code gener...
Context object for machine code objects.
Definition: MCContext.h:76
MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
Definition: MCContext.cpp:321
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:200
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:198
unsigned getNumRegs() const
Return the number of registers this target has (useful for sizing arrays holding per register informa...
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:40
Metadata node.
Definition: Metadata.h:1037
void setBBID(const UniqueBBID &V)
Sets the fixed BBID of this basic block.
void setIsEndSection(bool V=true)
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
MBBSectionID getSectionID() const
Returns the section ID of this basic block.
iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Instructions::const_iterator const_instr_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void setIsBeginSection(bool V=true)
This class is a data container for one entry in a MachineConstantPool.
bool needsRelocation() const
This method classifies the entry according to whether or not it may generate a relocation entry.
bool isMachineConstantPoolEntry() const
isMachineConstantPoolEntry - Return true if the MachineConstantPoolEntry is indeed a target specific ...
unsigned getSizeInBytes(const DataLayout &DL) const
SectionKind getSectionKind(const DataLayout *DL) const
union llvm::MachineConstantPoolEntry::@195 Val
The constant itself.
Abstract base class for all machine specific constantpool value subclasses.
virtual unsigned getSizeInBytes(const DataLayout &DL) const
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
void dump() const
dump - Call print(cerr) to be called from the debugger.
void print(raw_ostream &OS) const
print - Used by the MachineFunction printer to print information about constant pool objects.
unsigned getConstantPoolIndex(const Constant *C, Align Alignment)
getConstantPoolIndex - Create a new entry in the constant pool or return an existing one.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void ensureMaxAlignment(Align Alignment)
Make sure the function is at least Align bytes aligned.
void print(const MachineFunction &MF, raw_ostream &OS) const
Used by the MachineFunction printer to print information about stack objects.
void setUnsafeStackSize(uint64_t Size)
void print(raw_ostream &OS) const
Print the MachineFunctionProperties in human-readable form.
MachineFunctionProperties & set(Property P)
MachineFunctionProperties & reset(Property P)
virtual void MF_HandleChangeDesc(MachineInstr &MI, const MCInstrDesc &TID)
Callback before changing MCInstrDesc.
virtual void MF_HandleRemoval(MachineInstr &MI)=0
Callback before a removal. This should not modify the MI directly.
virtual void MF_HandleInsertion(MachineInstr &MI)=0
Callback after an insertion. This should not modify the MI directly.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, Align base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
int getFilterIDFor(ArrayRef< unsigned > TyIds)
Return the id of the filter encoded by TyIds. This is function wide.
bool UseDebugInstrRef
Flag for whether this function contains DBG_VALUEs (false) or DBG_INSTR_REF (true).
std::pair< unsigned, unsigned > DebugInstrOperandPair
Pair of instruction number and operand number.
unsigned addFrameInst(const MCCFIInstruction &Inst)
bool useDebugInstrRef() const
Returns true if the function's variable locations are tracked with instruction referencing.
SmallVector< DebugSubstitution, 8 > DebugValueSubstitutions
Debug value substitutions: a collection of DebugSubstitution objects, recording changes in where a va...
unsigned getFunctionNumber() const
getFunctionNumber - Return a unique ID for the current function.
MCSymbol * getPICBaseSymbol() const
getPICBaseSymbol - Return a function-local symbol to represent the PIC base.
void viewCFGOnly() const
viewCFGOnly - This function is meant for use from the debugger.
ArrayRef< int > allocateShuffleMask(ArrayRef< int > Mask)
void substituteDebugValuesForInst(const MachineInstr &Old, MachineInstr &New, unsigned MaxOperand=UINT_MAX)
Create substitutions for any tracked values in Old, to point at New.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineInstr & cloneMachineInstrBundle(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig)
Clones instruction or the whole instruction bundle Orig and insert into MBB before InsertBefore.
MachineJumpTableInfo * getOrCreateJumpTableInfo(unsigned JTEntryKind)
getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it does already exist,...
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
void dump() const
dump - Print the current MachineFunction to cerr, useful for debugger use.
MachineInstr * CreateMachineInstr(const MCInstrDesc &MCID, DebugLoc DL, bool NoImplicit=false)
CreateMachineInstr - Allocate a new MachineInstr.
void makeDebugValueSubstitution(DebugInstrOperandPair, DebugInstrOperandPair, unsigned SubReg=0)
Create a substitution between one <instr,operand> value to a different, new value.
bool needsFrameMoves() const
True if this function needs frame moves for debug or exceptions.
unsigned getTypeIDFor(const GlobalValue *TI)
Return the type id for the specified typeinfo. This is function wide.
void finalizeDebugInstrRefs()
Finalise any partially emitted debug instructions.
void deallocateOperandArray(OperandCapacity Cap, MachineOperand *Array)
Dellocate an array of MachineOperands and recycle the memory.
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
void copyCallSiteInfo(const MachineInstr *Old, const MachineInstr *New)
Copy the call site info from Old to \ New.
void deleteMachineInstr(MachineInstr *MI)
DeleteMachineInstr - Delete the given MachineInstr.
void initTargetMachineFunctionInfo(const TargetSubtargetInfo &STI)
Initialize the target specific MachineFunctionInfo.
const char * createExternalSymbolName(StringRef Name)
Allocate a string and populate it with the given external symbol name.
uint32_t * allocateRegMask()
Allocate and initialize a register mask with NumRegister bits.
MCSymbol * getJTISymbol(unsigned JTI, MCContext &Ctx, bool isLinkerPrivate=false) const
getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
void setCallSiteLandingPad(MCSymbol *Sym, ArrayRef< unsigned > Sites)
Map the landing pad's EH symbol to the call site indexes.
void setUseDebugInstrRef(bool UseInstrRef)
Set whether this function will use instruction referencing or not.
MCContext & getContext() const
LandingPadInfo & getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad)
Find or create an LandingPadInfo for the specified MachineBasicBlock.
unsigned size() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
MCSymbol * addLandingPad(MachineBasicBlock *LandingPad)
Add a new panding pad, and extract the exception handling information from the landingpad instruction...
unsigned DebugInstrNumberingCount
A count of how many instructions in the function have had numbers assigned to them.
void deleteMachineBasicBlock(MachineBasicBlock *MBB)
DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
void handleChangeDesc(MachineInstr &MI, const MCInstrDesc &TID)
static const unsigned int DebugOperandMemNumber
A reserved operand number representing the instructions memory operand, for instructions that have a ...
Function & getFunction()
Return the LLVM function that this machine code represents.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
DebugInstrOperandPair salvageCopySSAImpl(MachineInstr &MI)
const MachineBasicBlock & back() const
MachineModuleInfo & getMMI() const
BasicBlockListType::iterator iterator
void setDebugInstrNumberingCount(unsigned Num)
Set value of DebugInstrNumberingCount field.
bool shouldSplitStack() const
Should we be emitting segmented stack stuff for the function.
void viewCFG() const
viewCFG - This function is meant for use from the debugger.
bool shouldUseDebugInstrRef() const
Determine whether, in the current machine configuration, we should use instruction referencing or not...
const MachineFunctionProperties & getProperties() const
Get the function properties.
MachineInstr * CloneMachineInstr(const MachineInstr *Orig)
Create a new MachineInstr which is a copy of Orig, identical in all ways except the instruction has n...
void eraseCallSiteInfo(const MachineInstr *MI)
Following functions update call site info.
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them.
const MachineBasicBlock & front() const
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
void moveCallSiteInfo(const MachineInstr *Old, const MachineInstr *New)
Move the call site info from Old to \New call site info.
void print(raw_ostream &OS, const SlotIndexes *=nullptr) const
print - Print out the MachineFunction in a format suitable for debugging to the specified stream.
void addInvoke(MachineBasicBlock *LandingPad, MCSymbol *BeginLabel, MCSymbol *EndLabel)
Provide the begin and end labels of an invoke style call and associate it with a try landing pad bloc...
MachineInstr::ExtraInfo * createMIExtraInfo(ArrayRef< MachineMemOperand * > MMOs, MCSymbol *PreInstrSymbol=nullptr, MCSymbol *PostInstrSymbol=nullptr, MDNode *HeapAllocMarker=nullptr, MDNode *PCSections=nullptr, uint32_t CFIType=0)
Allocate and construct an extra info structure for a MachineInstr.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
VariableDbgInfoMapTy VariableDbgInfos
void assignBeginEndSections()
Assign IsBeginSection IsEndSection fields for basic blocks in this function.
MachineFunction(Function &F, const LLVMTargetMachine &Target, const TargetSubtargetInfo &STI, unsigned FunctionNum, MachineModuleInfo &MMI)
DebugInstrOperandPair salvageCopySSA(MachineInstr &MI, DenseMap< Register, DebugInstrOperandPair > &DbgPHICache)
Find the underlying defining instruction / operand for a COPY instruction while in SSA form.
Representation of each machine instruction.
Definition: MachineInstr.h:68
void bundleWithPred()
Bundle this instruction with its predecessor.
bool isCopyLike() const
Return true if the instruction behaves like a copy.
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:546
unsigned peekDebugInstrNum() const
Examine the instruction number of this MachineInstr.
Definition: MachineInstr.h:519
bool shouldUpdateCallSiteInfo() const
Return true if copying, moving, or erasing this instruction requires updating Call Site Info (see cop...
unsigned getDebugInstrNum()
Fetch the instruction number of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:553
iterator_range< filtered_mop_iterator > all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
Definition: MachineInstr.h:730
bool RemoveMBBFromJumpTables(MachineBasicBlock *MBB)
RemoveMBBFromJumpTables - If MBB is present in any jump tables, remove it.
bool ReplaceMBBInJumpTables(MachineBasicBlock *Old, MachineBasicBlock *New)
ReplaceMBBInJumpTables - If Old is the target of any jump tables, update the jump tables to branch to...
void print(raw_ostream &OS) const
print - Used by the MachineFunction printer to print information about jump tables.
unsigned getEntrySize(const DataLayout &TD) const
getEntrySize - Return the size of each entry in the jump table.
unsigned createJumpTableIndex(const std::vector< MachineBasicBlock * > &DestBBs)
createJumpTableIndex - Create a new jump table.
void dump() const
dump - Call to stderr.
bool ReplaceMBBInJumpTable(unsigned Idx, MachineBasicBlock *Old, MachineBasicBlock *New)
ReplaceMBBInJumpTable - If Old is a target of the jump tables, update the jump table to branch to New...
JTEntryKind
JTEntryKind - This enum indicates how each entry of the jump table is represented and emitted.
@ EK_GPRel32BlockAddress
EK_GPRel32BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
@ EK_Inline
EK_Inline - Jump table entries are emitted inline at their point of use.
@ EK_LabelDifference32
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table.
@ EK_Custom32
EK_Custom32 - Each entry is a 32-bit value that is custom lowered by the TargetLowering::LowerCustomJ...
@ EK_LabelDifference64
EK_LabelDifference64 - Each entry is the address of the block minus the address of the jump table.
@ EK_BlockAddress
EK_BlockAddress - Each entry is a plain address of block, e.g.: .word LBB123.
@ EK_GPRel64BlockAddress
EK_GPRel64BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
unsigned getEntryAlignment(const DataLayout &TD) const
getEntryAlignment - Return the alignment of each entry in the jump table.
JTEntryKind getEntryKind() const
A description of a memory reference used in the backend.
AtomicOrdering getFailureOrdering() const
For cmpxchg atomic operations, return the atomic ordering requirements when store does not occur.
const PseudoSourceValue * getPseudoValue() const
const MDNode * getRanges() const
Return the range tag for the memory reference.
uint64_t getSize() const
Return the size in bytes of the memory reference.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID for this memory operation.
Flags
Flags values. These may be or'd together.
AtomicOrdering getSuccessOrdering() const
Return the atomic ordering requirements for this memory operation.
const MachinePointerInfo & getPointerInfo() const
Flags getFlags() const
Return the raw flags of the source value,.
AAMDNodes getAAInfo() const
Return the AA tags for the memory reference.
const Value * getValue() const
Return the base address of the memory access.
Align getBaseAlign() const
Return the minimum known alignment in bytes of the base address, without the offset.
int64_t getOffset() const
For normal values, this is a byte offset added to the base address.
This class contains meta information specific to a module.
bool hasDebugInfo() const
Returns true if valid debug info is present.
MachineOperand class - Representation of each machine instruction operand.
static unsigned getRegMaskSize(unsigned NumRegs)
Returns number of elements needed for a regmask array.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
def_instr_iterator def_instr_begin(Register RegNo) const
std::vector< std::pair< MCRegister, Register > >::const_iterator livein_iterator
bool hasOneDef(Register RegNo) const
Return true if there is exactly one operand defining the specified register.
livein_iterator livein_end() const
livein_iterator livein_begin() const
Manage lifetime of a slot tracker for printing IR.
void incorporateFunction(const Function &F)
Incorporate the given function.
Definition: AsmWriter.cpp:892
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:275
bool isNull() const
Test if the pointer held in the union is null, regardless of which type it is.
Definition: PointerUnion.h:142
Simple wrapper around std::function<void(raw_ostream&)>.
Definition: Printable.h:38
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:22
static SectionKind getMergeableConst4()
Definition: SectionKind.h:202
static SectionKind getReadOnlyWithRel()
Definition: SectionKind.h:214
static SectionKind getMergeableConst8()
Definition: SectionKind.h:203
static SectionKind getMergeableConst16()
Definition: SectionKind.h:204
static SectionKind getReadOnly()
Definition: SectionKind.h:192
static SectionKind getMergeableConst32()
Definition: SectionKind.h:205
SlotIndexes pass.
Definition: SlotIndexes.h:300
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
bool isStackRealignable() const
isStackRealignable - This method returns whether the stack can be realigned.
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
TargetInstrInfo - Interface to description of machine instruction set.
Align getPrefFunctionAlignment() const
Return the preferred function alignment.
Align getMinFunctionAlignment() const
Return the minimum function alignment.
TargetOptions Options
unsigned ForceDwarfFrameSection
Emit DWARF debug frame section.
bool contains(Register Reg) const
Return true if the specified register is included in this register class.
bool hasSubClassEq(const TargetRegisterClass *RC) const
Returns true if RC is a sub-class of or equal to this class.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetLowering * getTargetLowering() const
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
LLVM Value Representation.
Definition: Value.h:74
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:693
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
self_iterator getIterator()
Definition: ilist_node.h:109
iterator erase(iterator where)
Definition: ilist.h:204
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:642
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:672
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:456
MachineBasicBlock::instr_iterator getBundleStart(MachineBasicBlock::instr_iterator I)
Returns an iterator to the first instruction in the bundle containing I.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
bool getAlign(const Function &F, unsigned index, unsigned &align)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2042
Printable printJumpTableEntryReference(unsigned Idx)
Prints a jump table entry reference.
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:428
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
MachineBasicBlock::instr_iterator getBundleEnd(MachineBasicBlock::instr_iterator I)
Returns an iterator pointing beyond the bundle containing I.
Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
AtomicOrdering
Atomic ordering for LLVM's memory model.
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file, then cleanup.
Definition: GraphWriter.h:427
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1828
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition: Alignment.h:212
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
bool debuginfoShouldUseDebugInstrRef(const Triple &T)
#define N
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:738
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
std::string getNodeLabel(const MachineBasicBlock *Node, const MachineFunction *Graph)
static std::string getGraphName(const MachineFunction *F)
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
DefaultDOTGraphTraits - This class provides the default implementations of all of the DOTGraphTraits ...
Represent subnormal handling kind for floating point instruction inputs and outputs.
This structure is used to retain landing pad info for the current function.
SmallVector< MCSymbol *, 1 > EndLabels
MachineBasicBlock * LandingPadBlock
SmallVector< MCSymbol *, 1 > BeginLabels
std::vector< int > TypeIds
MachineJumpTableEntry - One jump table in the jump table info.
std::vector< MachineBasicBlock * > MBBs
MBBs - The vector of basic blocks from which to create the jump table.
This class contains a discriminated union of information about pointers in memory operands,...
PointerUnion< const Value *, const PseudoSourceValue * > V
This is the IR pointer value for the access, or it is null if unknown.
MachinePointerInfo getWithOffset(int64_t O) const
static void deleteNode(NodeTy *V)
Definition: ilist.h:42