#include "llvm/CodeGen/AsmPrinter.h"
#include "CodeViewDebug.h"
#include "DwarfDebug.h"
#include "DwarfException.h"
#include "PseudoProbePrinter.h"
#include "WasmException.h"
#include "WinCFGuard.h"
#include "WinException.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/EHPersonalities.h"
#include "llvm/Analysis/MemoryLocation.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/BinaryFormat/COFF.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/CodeGen/GCMetadata.h"
#include "llvm/CodeGen/GCMetadataPrinter.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBundle.h"
#include "llvm/CodeGen/MachineJumpTableInfo.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineModuleInfoImpls.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
#include "llvm/CodeGen/StackMaps.h"
#include "llvm/CodeGen/TargetFrameLowering.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetOpcodes.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/Config/config.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Comdat.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GCStrategy.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/GlobalIFunc.h"
#include "llvm/IR/GlobalObject.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Mangler.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/PseudoProbe.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDirectives.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCSectionCOFF.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCSymbolELF.h"
#include "llvm/MC/MCTargetOptions.h"
#include "llvm/MC/MCValue.h"
#include "llvm/MC/SectionKind.h"
#include "llvm/Pass.h"
#include "llvm/Remarks/RemarkStreamer.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include <algorithm>
#include <cassert>
#include <cinttypes>
#include <cstdint>
#include <iterator>
#include <memory>
#include <string>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "asm-printer"
const char DWARFGroupName[] = "dwarf";
const char DWARFGroupDescription[] = "DWARF Emission";
const char DbgTimerName[] = "emit";
const char DbgTimerDescription[] = "Debug Info Emission";
const char EHTimerName[] = "write_exception";
const char EHTimerDescription[] = "DWARF Exception Writer";
const char CFGuardName[] = "Control Flow Guard";
const char CFGuardDescription[] = "Control Flow Guard";
const char CodeViewLineTablesGroupName[] = "linetables";
const char CodeViewLineTablesGroupDescription[] = "CodeView Line Tables";
const char PPTimerName[] = "emit";
const char PPTimerDescription[] = "Pseudo Probe Emission";
const char PPGroupName[] = "pseudo probe";
const char PPGroupDescription[] = "Pseudo Probe Emission";
STATISTIC(EmittedInsts, "Number of machine instrs printed");
char AsmPrinter::ID = 0;
using gcp_map_type = DenseMap<GCStrategy *, std::unique_ptr<GCMetadataPrinter>>;
static gcp_map_type &getGCMap(void *&P) {
if (!P)
P = new gcp_map_type();
return *(gcp_map_type*)P;
}
namespace {
class AddrLabelMapCallbackPtr final : CallbackVH {
AddrLabelMap *Map = nullptr;
public:
AddrLabelMapCallbackPtr() = default;
AddrLabelMapCallbackPtr(Value *V) : CallbackVH(V) {}
void setPtr(BasicBlock *BB) {
ValueHandleBase::operator=(BB);
}
void setMap(AddrLabelMap *map) { Map = map; }
void deleted() override;
void allUsesReplacedWith(Value *V2) override;
};
}
class llvm::AddrLabelMap {
MCContext &Context;
struct AddrLabelSymEntry {
TinyPtrVector<MCSymbol *> Symbols;
Function *Fn; unsigned Index; };
DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
std::vector<AddrLabelMapCallbackPtr> BBCallbacks;
DenseMap<AssertingVH<Function>, std::vector<MCSymbol *>>
DeletedAddrLabelsNeedingEmission;
public:
AddrLabelMap(MCContext &context) : Context(context) {}
~AddrLabelMap() {
assert(DeletedAddrLabelsNeedingEmission.empty() &&
"Some labels for deleted blocks never got emitted");
}
ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
void takeDeletedSymbolsForFunction(Function *F,
std::vector<MCSymbol *> &Result);
void UpdateForDeletedBlock(BasicBlock *BB);
void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
};
ArrayRef<MCSymbol *> AddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) {
assert(BB->hasAddressTaken() &&
"Shouldn't get label for block without address taken");
AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
if (!Entry.Symbols.empty()) {
assert(BB->getParent() == Entry.Fn && "Parent changed");
return Entry.Symbols;
}
BBCallbacks.emplace_back(BB);
BBCallbacks.back().setMap(this);
Entry.Index = BBCallbacks.size() - 1;
Entry.Fn = BB->getParent();
MCSymbol *Sym = BB->hasAddressTaken() ? Context.createNamedTempSymbol()
: Context.createTempSymbol();
Entry.Symbols.push_back(Sym);
return Entry.Symbols;
}
void AddrLabelMap::takeDeletedSymbolsForFunction(
Function *F, std::vector<MCSymbol *> &Result) {
DenseMap<AssertingVH<Function>, std::vector<MCSymbol *>>::iterator I =
DeletedAddrLabelsNeedingEmission.find(F);
if (I == DeletedAddrLabelsNeedingEmission.end())
return;
std::swap(Result, I->second);
DeletedAddrLabelsNeedingEmission.erase(I);
}
ArrayRef<MCSymbol *>
AsmPrinter::getAddrLabelSymbolToEmit(const BasicBlock *BB) {
if (!AddrLabelSymbols)
AddrLabelSymbols = std::make_unique<AddrLabelMap>(OutContext);
return AddrLabelSymbols->getAddrLabelSymbolToEmit(
const_cast<BasicBlock *>(BB));
}
void AsmPrinter::takeDeletedSymbolsForFunction(
const Function *F, std::vector<MCSymbol *> &Result) {
if (!AddrLabelSymbols)
return;
return AddrLabelSymbols->takeDeletedSymbolsForFunction(
const_cast<Function *>(F), Result);
}
void AddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
AddrLabelSymbols.erase(BB);
assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
BBCallbacks[Entry.Index] = nullptr;
#if !LLVM_MEMORY_SANITIZER_BUILD
assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
"Block/parent mismatch");
#endif
for (MCSymbol *Sym : Entry.Symbols) {
if (Sym->isDefined())
return;
DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
}
}
void AddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
AddrLabelSymbols.erase(Old);
assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
if (NewEntry.Symbols.empty()) {
BBCallbacks[OldEntry.Index].setPtr(New); NewEntry = std::move(OldEntry); return;
}
BBCallbacks[OldEntry.Index] = nullptr;
llvm::append_range(NewEntry.Symbols, OldEntry.Symbols);
}
void AddrLabelMapCallbackPtr::deleted() {
Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
}
void AddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
}
Align AsmPrinter::getGVAlignment(const GlobalObject *GV, const DataLayout &DL,
Align InAlign) {
Align Alignment;
if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
Alignment = DL.getPreferredAlign(GVar);
if (InAlign > Alignment)
Alignment = InAlign;
const MaybeAlign GVAlign(GV->getAlign());
if (!GVAlign)
return Alignment;
assert(GVAlign && "GVAlign must be set");
if (*GVAlign > Alignment || GV->hasSection())
Alignment = *GVAlign;
return Alignment;
}
AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
: MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)) {
VerboseAsm = OutStreamer->isVerboseAsm();
}
AsmPrinter::~AsmPrinter() {
assert(!DD && Handlers.size() == NumUserHandlers &&
"Debug/EH info didn't get finalized");
if (GCMetadataPrinters) {
gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
delete &GCMap;
GCMetadataPrinters = nullptr;
}
}
bool AsmPrinter::isPositionIndependent() const {
return TM.isPositionIndependent();
}
unsigned AsmPrinter::getFunctionNumber() const {
return MF->getFunctionNumber();
}
const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
return *TM.getObjFileLowering();
}
const DataLayout &AsmPrinter::getDataLayout() const {
return MMI->getModule()->getDataLayout();
}
unsigned AsmPrinter::getPointerSize() const {
return TM.getPointerSize(0); }
const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
return MF->getSubtarget<MCSubtargetInfo>();
}
void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
S.emitInstruction(Inst, getSubtargetInfo());
}
void AsmPrinter::emitInitialRawDwarfLocDirective(const MachineFunction &MF) {
if (DD) {
assert(OutStreamer->hasRawTextSupport() &&
"Expected assembly output mode.");
DISubprogram *MFSP = MF.getFunction().getSubprogram();
if (!MFSP)
return;
(void)DD->emitInitialLocDirective(MF, 0);
}
}
const MCSection *AsmPrinter::getCurrentSection() const {
return OutStreamer->getCurrentSectionOnly();
}
void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
MachineFunctionPass::getAnalysisUsage(AU);
AU.addRequired<MachineOptimizationRemarkEmitterPass>();
AU.addRequired<GCModuleInfo>();
}
bool AsmPrinter::doInitialization(Module &M) {
auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>();
MMI = MMIWP ? &MMIWP->getMMI() : nullptr;
HasSplitStack = false;
HasNoSplitStack = false;
AddrLabelSymbols = nullptr;
const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
.Initialize(OutContext, TM);
const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
.getModuleMetadata(M);
OutStreamer->initSections(false, *TM.getMCSubtargetInfo());
const Triple &Target = TM.getTargetTriple();
Triple TVT(M.getDarwinTargetVariantTriple());
OutStreamer->emitVersionForTarget(
Target, M.getSDKVersion(),
M.getDarwinTargetVariantTriple().empty() ? nullptr : &TVT,
M.getDarwinTargetVariantSDKVersion());
emitStartOfAsmFile(M);
if (MAI->hasSingleParameterDotFile()) {
SmallString<128> FileName;
if (MAI->hasBasenameOnlyForFileDirective())
FileName = llvm::sys::path::filename(M.getSourceFileName());
else
FileName = M.getSourceFileName();
if (MAI->hasFourStringsDotFile()) {
#ifdef PACKAGE_VENDOR
const char VerStr[] =
PACKAGE_VENDOR " " PACKAGE_NAME " version " PACKAGE_VERSION;
#else
const char VerStr[] = PACKAGE_NAME " version " PACKAGE_VERSION;
#endif
OutStreamer->emitFileDirective(FileName, VerStr, "", "");
} else {
OutStreamer->emitFileDirective(FileName);
}
}
GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
assert(MI && "AsmPrinter didn't require GCModuleInfo?");
for (const auto &I : *MI)
if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
MP->beginAssembly(M, *MI, *this);
if (!M.getModuleInlineAsm().empty()) {
OutStreamer->AddComment("Start of file scope inline assembly");
OutStreamer->addBlankLine();
emitInlineAsm(M.getModuleInlineAsm() + "\n", *TM.getMCSubtargetInfo(),
TM.Options.MCOptions);
OutStreamer->AddComment("End of file scope inline assembly");
OutStreamer->addBlankLine();
}
if (MAI->doesSupportDebugInformation()) {
bool EmitCodeView = M.getCodeViewFlag();
if (EmitCodeView && TM.getTargetTriple().isOSWindows()) {
Handlers.emplace_back(std::make_unique<CodeViewDebug>(this),
DbgTimerName, DbgTimerDescription,
CodeViewLineTablesGroupName,
CodeViewLineTablesGroupDescription);
}
if (!EmitCodeView || M.getDwarfVersion()) {
if (MMI->hasDebugInfo()) {
DD = new DwarfDebug(this);
Handlers.emplace_back(std::unique_ptr<DwarfDebug>(DD), DbgTimerName,
DbgTimerDescription, DWARFGroupName,
DWARFGroupDescription);
}
}
}
if (M.getNamedMetadata(PseudoProbeDescMetadataName)) {
PP = new PseudoProbeHandler(this);
Handlers.emplace_back(std::unique_ptr<PseudoProbeHandler>(PP), PPTimerName,
PPTimerDescription, PPGroupName, PPGroupDescription);
}
switch (MAI->getExceptionHandlingType()) {
case ExceptionHandling::None:
LLVM_FALLTHROUGH;
case ExceptionHandling::SjLj:
case ExceptionHandling::DwarfCFI:
case ExceptionHandling::ARM:
for (auto &F : M.getFunctionList()) {
if (getFunctionCFISectionType(F) != CFISection::None)
ModuleCFISection = getFunctionCFISectionType(F);
if (ModuleCFISection == CFISection::EH)
break;
}
assert(MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI ||
ModuleCFISection != CFISection::EH);
break;
default:
break;
}
EHStreamer *ES = nullptr;
switch (MAI->getExceptionHandlingType()) {
case ExceptionHandling::None:
if (!needsCFIForDebug())
break;
LLVM_FALLTHROUGH;
case ExceptionHandling::SjLj:
case ExceptionHandling::DwarfCFI:
ES = new DwarfCFIException(this);
break;
case ExceptionHandling::ARM:
ES = new ARMException(this);
break;
case ExceptionHandling::WinEH:
switch (MAI->getWinEHEncodingType()) {
default: llvm_unreachable("unsupported unwinding information encoding");
case WinEH::EncodingType::Invalid:
break;
case WinEH::EncodingType::X86:
case WinEH::EncodingType::Itanium:
ES = new WinException(this);
break;
}
break;
case ExceptionHandling::Wasm:
ES = new WasmException(this);
break;
case ExceptionHandling::AIX:
ES = new AIXException(this);
break;
}
if (ES)
Handlers.emplace_back(std::unique_ptr<EHStreamer>(ES), EHTimerName,
EHTimerDescription, DWARFGroupName,
DWARFGroupDescription);
if (mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("cfguard")))
Handlers.emplace_back(std::make_unique<WinCFGuard>(this), CFGuardName,
CFGuardDescription, DWARFGroupName,
DWARFGroupDescription);
for (const HandlerInfo &HI : Handlers) {
NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
HI.TimerGroupDescription, TimePassesIsEnabled);
HI.Handler->beginModule(&M);
}
return false;
}
static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
if (!MAI.hasWeakDefCanBeHiddenDirective())
return false;
return GV->canBeOmittedFromSymbolTable();
}
void AsmPrinter::emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
GlobalValue::LinkageTypes Linkage = GV->getLinkage();
switch (Linkage) {
case GlobalValue::CommonLinkage:
case GlobalValue::LinkOnceAnyLinkage:
case GlobalValue::LinkOnceODRLinkage:
case GlobalValue::WeakAnyLinkage:
case GlobalValue::WeakODRLinkage:
if (MAI->hasWeakDefDirective()) {
OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
if (!canBeHidden(GV, *MAI))
OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefinition);
else
OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
} else if (MAI->avoidWeakIfComdat() && GV->hasComdat()) {
OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
} else {
OutStreamer->emitSymbolAttribute(GVSym, MCSA_Weak);
}
return;
case GlobalValue::ExternalLinkage:
OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
return;
case GlobalValue::PrivateLinkage:
case GlobalValue::InternalLinkage:
return;
case GlobalValue::ExternalWeakLinkage:
case GlobalValue::AvailableExternallyLinkage:
case GlobalValue::AppendingLinkage:
llvm_unreachable("Should never emit this");
}
llvm_unreachable("Unknown linkage type!");
}
void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
const GlobalValue *GV) const {
TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler());
}
MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
return TM.getSymbol(GV);
}
MCSymbol *AsmPrinter::getSymbolPreferLocal(const GlobalValue &GV) const {
if (TM.getTargetTriple().isOSBinFormatELF() && GV.canBenefitFromLocalAlias()) {
const Module &M = *GV.getParent();
if (TM.getRelocationModel() != Reloc::Static &&
M.getPIELevel() == PIELevel::Default && GV.isDSOLocal())
return getSymbolWithGlobalValueBase(&GV, "$local");
}
return TM.getSymbol(&GV);
}
void AsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
"No emulated TLS variables in the common section");
if (IsEmuTLSVar)
return;
if (GV->hasInitializer()) {
if (emitSpecialLLVMGlobal(GV))
return;
if (GlobalGOTEquivs.count(getSymbol(GV)))
return;
if (isVerbose()) {
GV->printAsOperand(OutStreamer->getCommentOS(),
false, GV->getParent());
OutStreamer->getCommentOS() << '\n';
}
}
MCSymbol *GVSym = getSymbol(GV);
MCSymbol *EmittedSym = GVSym;
emitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
if (!GV->hasInitializer()) return;
GVSym->redefineIfPossible();
if (GVSym->isDefined() || GVSym->isVariable())
OutContext.reportError(SMLoc(), "symbol '" + Twine(GVSym->getName()) +
"' is already defined");
if (MAI->hasDotTypeDotSizeDirective())
OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
const DataLayout &DL = GV->getParent()->getDataLayout();
uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
const Align Alignment = getGVAlignment(GV, DL);
for (const HandlerInfo &HI : Handlers) {
NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
HI.TimerGroupName, HI.TimerGroupDescription,
TimePassesIsEnabled);
HI.Handler->setSymbolSize(GVSym, Size);
}
if (GVKind.isCommon()) {
if (Size == 0) Size = 1; const bool SupportsAlignment =
getObjFileLowering().getCommDirectiveSupportsAlignment();
OutStreamer->emitCommonSymbol(GVSym, Size,
SupportsAlignment ? Alignment.value() : 0);
return;
}
MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() &&
TheSection->isVirtualSection()) {
if (Size == 0)
Size = 1; emitLinkage(GV, GVSym);
OutStreamer->emitZerofill(TheSection, GVSym, Size, Alignment.value());
return;
}
if (GVKind.isBSSLocal() &&
getObjFileLowering().getBSSSection() == TheSection) {
if (Size == 0)
Size = 1;
if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
OutStreamer->emitLocalCommonSymbol(GVSym, Size, Alignment.value());
return;
}
OutStreamer->emitSymbolAttribute(GVSym, MCSA_Local);
const bool SupportsAlignment =
getObjFileLowering().getCommDirectiveSupportsAlignment();
OutStreamer->emitCommonSymbol(GVSym, Size,
SupportsAlignment ? Alignment.value() : 0);
return;
}
if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
MCSymbol *MangSym =
OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
if (GVKind.isThreadBSS()) {
TheSection = getObjFileLowering().getTLSBSSSection();
OutStreamer->emitTBSSSymbol(TheSection, MangSym, Size, Alignment.value());
} else if (GVKind.isThreadData()) {
OutStreamer->switchSection(TheSection);
emitAlignment(Alignment, GV);
OutStreamer->emitLabel(MangSym);
emitGlobalConstant(GV->getParent()->getDataLayout(),
GV->getInitializer());
}
OutStreamer->addBlankLine();
MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
OutStreamer->switchSection(TLVSect);
emitLinkage(GV, GVSym);
OutStreamer->emitLabel(GVSym);
unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
PtrSize);
OutStreamer->emitIntValue(0, PtrSize);
OutStreamer->emitSymbolValue(MangSym, PtrSize);
OutStreamer->addBlankLine();
return;
}
MCSymbol *EmittedInitSym = GVSym;
OutStreamer->switchSection(TheSection);
emitLinkage(GV, EmittedInitSym);
emitAlignment(Alignment, GV);
OutStreamer->emitLabel(EmittedInitSym);
MCSymbol *LocalAlias = getSymbolPreferLocal(*GV);
if (LocalAlias != EmittedInitSym)
OutStreamer->emitLabel(LocalAlias);
emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
if (MAI->hasDotTypeDotSizeDirective())
OutStreamer->emitELFSize(EmittedInitSym,
MCConstantExpr::create(Size, OutContext));
OutStreamer->addBlankLine();
}
void AsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const {
OutStreamer->emitValue(Value, Size);
}
void AsmPrinter::emitFunctionHeaderComment() {}
void AsmPrinter::emitFunctionHeader() {
const Function &F = MF->getFunction();
if (isVerbose())
OutStreamer->getCommentOS()
<< "-- Begin function "
<< GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n';
emitConstantPool();
if (MF->front().isBeginSection())
MF->setSection(getObjFileLowering().getUniqueSectionForFunction(F, TM));
else
MF->setSection(getObjFileLowering().SectionForGlobal(&F, TM));
OutStreamer->switchSection(MF->getSection());
if (!MAI->hasVisibilityOnlyWithLinkage())
emitVisibility(CurrentFnSym, F.getVisibility());
if (MAI->needsFunctionDescriptors())
emitLinkage(&F, CurrentFnDescSym);
emitLinkage(&F, CurrentFnSym);
if (MAI->hasFunctionAlignment())
emitAlignment(MF->getAlignment(), &F);
if (MAI->hasDotTypeDotSizeDirective())
OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
if (F.hasFnAttribute(Attribute::Cold))
OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_Cold);
if (isVerbose()) {
F.printAsOperand(OutStreamer->getCommentOS(),
false, F.getParent());
emitFunctionHeaderComment();
OutStreamer->getCommentOS() << '\n';
}
if (F.hasPrefixData()) {
if (MAI->hasSubsectionsViaSymbols()) {
MCSymbol *PrefixSym = OutContext.createLinkerPrivateTempSymbol();
OutStreamer->emitLabel(PrefixSym);
emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_AltEntry);
} else {
emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
}
}
unsigned PatchableFunctionPrefix = 0;
unsigned PatchableFunctionEntry = 0;
(void)F.getFnAttribute("patchable-function-prefix")
.getValueAsString()
.getAsInteger(10, PatchableFunctionPrefix);
(void)F.getFnAttribute("patchable-function-entry")
.getValueAsString()
.getAsInteger(10, PatchableFunctionEntry);
if (PatchableFunctionPrefix) {
CurrentPatchableFunctionEntrySym =
OutContext.createLinkerPrivateTempSymbol();
OutStreamer->emitLabel(CurrentPatchableFunctionEntrySym);
emitNops(PatchableFunctionPrefix);
} else if (PatchableFunctionEntry) {
CurrentPatchableFunctionEntrySym = CurrentFnBegin;
}
if (MAI->needsFunctionDescriptors())
emitFunctionDescriptor();
emitFunctionEntryLabel();
std::vector<MCSymbol*> DeadBlockSyms;
takeDeletedSymbolsForFunction(&F, DeadBlockSyms);
for (MCSymbol *DeadBlockSym : DeadBlockSyms) {
OutStreamer->AddComment("Address taken block that was later removed");
OutStreamer->emitLabel(DeadBlockSym);
}
if (CurrentFnBegin) {
if (MAI->useAssignmentForEHBegin()) {
MCSymbol *CurPos = OutContext.createTempSymbol();
OutStreamer->emitLabel(CurPos);
OutStreamer->emitAssignment(CurrentFnBegin,
MCSymbolRefExpr::create(CurPos, OutContext));
} else {
OutStreamer->emitLabel(CurrentFnBegin);
}
}
for (const HandlerInfo &HI : Handlers) {
NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
HI.TimerGroupDescription, TimePassesIsEnabled);
HI.Handler->beginFunction(MF);
}
if (F.hasPrologueData())
emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrologueData());
if (const MDNode *MD = F.getMetadata(LLVMContext::MD_func_sanitize)) {
assert(TM.getTargetTriple().getArch() == Triple::x86 ||
TM.getTargetTriple().getArch() == Triple::x86_64);
assert(MD->getNumOperands() == 2);
auto *PrologueSig = mdconst::extract<Constant>(MD->getOperand(0));
auto *FTRTTIProxy = mdconst::extract<Constant>(MD->getOperand(1));
assert(PrologueSig && FTRTTIProxy);
emitGlobalConstant(F.getParent()->getDataLayout(), PrologueSig);
const MCExpr *Proxy = lowerConstant(FTRTTIProxy);
const MCExpr *FnExp = MCSymbolRefExpr::create(CurrentFnSym, OutContext);
const MCExpr *PCRel = MCBinaryExpr::createSub(Proxy, FnExp, OutContext);
OutStreamer->emitValue(PCRel, 4u);
}
}
void AsmPrinter::emitFunctionEntryLabel() {
CurrentFnSym->redefineIfPossible();
if (CurrentFnSym->isVariable())
report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
"' is a protected alias");
OutStreamer->emitLabel(CurrentFnSym);
if (TM.getTargetTriple().isOSBinFormatELF()) {
MCSymbol *Sym = getSymbolPreferLocal(MF->getFunction());
if (Sym != CurrentFnSym)
OutStreamer->emitLabel(Sym);
}
}
static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
const MachineFunction *MF = MI.getMF();
const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
Optional<unsigned> Size;
if ((Size = MI.getRestoreSize(TII))) {
CommentOS << *Size << "-byte Reload\n";
} else if ((Size = MI.getFoldedRestoreSize(TII))) {
if (*Size) {
if (*Size == unsigned(MemoryLocation::UnknownSize))
CommentOS << "Unknown-size Folded Reload\n";
else
CommentOS << *Size << "-byte Folded Reload\n";
}
} else if ((Size = MI.getSpillSize(TII))) {
CommentOS << *Size << "-byte Spill\n";
} else if ((Size = MI.getFoldedSpillSize(TII))) {
if (*Size) {
if (*Size == unsigned(MemoryLocation::UnknownSize))
CommentOS << "Unknown-size Folded Spill\n";
else
CommentOS << *Size << "-byte Folded Spill\n";
}
}
if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
CommentOS << " Reload Reuse\n";
}
void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
Register RegNo = MI->getOperand(0).getReg();
SmallString<128> Str;
raw_svector_ostream OS(Str);
OS << "implicit-def: "
<< printReg(RegNo, MF->getSubtarget().getRegisterInfo());
OutStreamer->AddComment(OS.str());
OutStreamer->addBlankLine();
}
static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
std::string Str;
raw_string_ostream OS(Str);
OS << "kill:";
for (const MachineOperand &Op : MI->operands()) {
assert(Op.isReg() && "KILL instruction must have only register operands");
OS << ' ' << (Op.isDef() ? "def " : "killed ")
<< printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
}
AP.OutStreamer->AddComment(OS.str());
AP.OutStreamer->addBlankLine();
}
static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
if (MI->isNonListDebugValue() && MI->getNumOperands() != 4)
return false;
SmallString<128> Str;
raw_svector_ostream OS(Str);
OS << "DEBUG_VALUE: ";
const DILocalVariable *V = MI->getDebugVariable();
if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
StringRef Name = SP->getName();
if (!Name.empty())
OS << Name << ":";
}
OS << V->getName();
OS << " <- ";
const DIExpression *Expr = MI->getDebugExpression();
if (Expr->getNumElements()) {
OS << '[';
ListSeparator LS;
for (auto Op : Expr->expr_ops()) {
OS << LS << dwarf::OperationEncodingString(Op.getOp());
for (unsigned I = 0; I < Op.getNumArgs(); ++I)
OS << ' ' << Op.getArg(I);
}
OS << "] ";
}
for (const MachineOperand &Op : MI->debug_operands()) {
if (&Op != MI->debug_operands().begin())
OS << ", ";
switch (Op.getType()) {
case MachineOperand::MO_FPImmediate: {
APFloat APF = APFloat(Op.getFPImm()->getValueAPF());
Type *ImmTy = Op.getFPImm()->getType();
if (ImmTy->isBFloatTy() || ImmTy->isHalfTy() || ImmTy->isFloatTy() ||
ImmTy->isDoubleTy()) {
OS << APF.convertToDouble();
} else {
bool ignored;
APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
&ignored);
OS << "(long double) " << APF.convertToDouble();
}
break;
}
case MachineOperand::MO_Immediate: {
OS << Op.getImm();
break;
}
case MachineOperand::MO_CImmediate: {
Op.getCImm()->getValue().print(OS, false );
break;
}
case MachineOperand::MO_TargetIndex: {
OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")";
AP.OutStreamer->emitRawComment(OS.str());
break;
}
case MachineOperand::MO_Register:
case MachineOperand::MO_FrameIndex: {
Register Reg;
Optional<StackOffset> Offset;
if (Op.isReg()) {
Reg = Op.getReg();
} else {
const TargetFrameLowering *TFI =
AP.MF->getSubtarget().getFrameLowering();
Offset = TFI->getFrameIndexReference(*AP.MF, Op.getIndex(), Reg);
}
if (!Reg) {
OS << "undef";
break;
}
if (MI->isIndirectDebugValue())
Offset = StackOffset::getFixed(MI->getDebugOffset().getImm());
if (Offset)
OS << '[';
OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
if (Offset)
OS << '+' << Offset->getFixed() << ']';
break;
}
default:
llvm_unreachable("Unknown operand type");
}
}
AP.OutStreamer->emitRawComment(OS.str());
return true;
}
static bool emitDebugLabelComment(const MachineInstr *MI, AsmPrinter &AP) {
if (MI->getNumOperands() != 1)
return false;
SmallString<128> Str;
raw_svector_ostream OS(Str);
OS << "DEBUG_LABEL: ";
const DILabel *V = MI->getDebugLabel();
if (auto *SP = dyn_cast<DISubprogram>(
V->getScope()->getNonLexicalBlockFileScope())) {
StringRef Name = SP->getName();
if (!Name.empty())
OS << Name << ":";
}
OS << V->getName();
AP.OutStreamer->emitRawComment(OS.str());
return true;
}
AsmPrinter::CFISection
AsmPrinter::getFunctionCFISectionType(const Function &F) const {
if (F.isDeclarationForLinker())
return CFISection::None;
if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
F.needsUnwindTableEntry())
return CFISection::EH;
if (MMI->hasDebugInfo() || TM.Options.ForceDwarfFrameSection)
return CFISection::Debug;
return CFISection::None;
}
AsmPrinter::CFISection
AsmPrinter::getFunctionCFISectionType(const MachineFunction &MF) const {
return getFunctionCFISectionType(MF.getFunction());
}
bool AsmPrinter::needsSEHMoves() {
return MAI->usesWindowsCFI() && MF->getFunction().needsUnwindTableEntry();
}
bool AsmPrinter::needsCFIForDebug() const {
return MAI->getExceptionHandlingType() == ExceptionHandling::None &&
MAI->doesUseCFIForDebug() && ModuleCFISection == CFISection::Debug;
}
void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
if (!needsCFIForDebug() &&
ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
ExceptionHandlingType != ExceptionHandling::ARM)
return;
if (getFunctionCFISectionType(*MF) == CFISection::None)
return;
auto *MBB = MI.getParent();
auto I = std::next(MI.getIterator());
while (I != MBB->end() && I->isTransient())
++I;
if (I == MBB->instr_end() &&
MBB->getReverseIterator() == MBB->getParent()->rbegin())
return;
const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
const MCCFIInstruction &CFI = Instrs[CFIIndex];
emitCFIInstruction(CFI);
}
void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
int FrameOffset = MI.getOperand(1).getImm();
OutStreamer->emitAssignment(FrameAllocSym,
MCConstantExpr::create(FrameOffset, OutContext));
}
static unsigned getBBAddrMapMetadata(const MachineBasicBlock &MBB) {
const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
return ((unsigned)MBB.isReturnBlock()) |
((!MBB.empty() && TII->isTailCall(MBB.back())) << 1) |
(MBB.isEHPad() << 2) |
(const_cast<MachineBasicBlock &>(MBB).canFallThrough() << 3);
}
void AsmPrinter::emitBBAddrMapSection(const MachineFunction &MF) {
MCSection *BBAddrMapSection =
getObjFileLowering().getBBAddrMapSection(*MF.getSection());
assert(BBAddrMapSection && ".llvm_bb_addr_map section is not initialized.");
const MCSymbol *FunctionSymbol = getFunctionBegin();
OutStreamer->pushSection();
OutStreamer->switchSection(BBAddrMapSection);
OutStreamer->AddComment("version");
OutStreamer->emitInt8(OutStreamer->getContext().getBBAddrMapVersion());
OutStreamer->AddComment("feature");
OutStreamer->emitInt8(0);
OutStreamer->AddComment("function address");
OutStreamer->emitSymbolValue(FunctionSymbol, getPointerSize());
OutStreamer->AddComment("number of basic blocks");
OutStreamer->emitULEB128IntValue(MF.size());
const MCSymbol *PrevMBBEndSymbol = FunctionSymbol;
for (const MachineBasicBlock &MBB : MF) {
const MCSymbol *MBBSymbol =
MBB.isEntryBlock() ? FunctionSymbol : MBB.getSymbol();
emitLabelDifferenceAsULEB128(MBBSymbol, PrevMBBEndSymbol);
emitLabelDifferenceAsULEB128(MBB.getEndSymbol(), MBBSymbol);
OutStreamer->emitULEB128IntValue(getBBAddrMapMetadata(MBB));
PrevMBBEndSymbol = MBB.getEndSymbol();
}
OutStreamer->popSection();
}
void AsmPrinter::emitPseudoProbe(const MachineInstr &MI) {
if (PP) {
auto GUID = MI.getOperand(0).getImm();
auto Index = MI.getOperand(1).getImm();
auto Type = MI.getOperand(2).getImm();
auto Attr = MI.getOperand(3).getImm();
DILocation *DebugLoc = MI.getDebugLoc();
PP->emitPseudoProbe(GUID, Index, Type, Attr, DebugLoc);
}
}
void AsmPrinter::emitStackSizeSection(const MachineFunction &MF) {
if (!MF.getTarget().Options.EmitStackSizeSection)
return;
MCSection *StackSizeSection =
getObjFileLowering().getStackSizesSection(*getCurrentSection());
if (!StackSizeSection)
return;
const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
if (FrameInfo.hasVarSizedObjects())
return;
OutStreamer->pushSection();
OutStreamer->switchSection(StackSizeSection);
const MCSymbol *FunctionSymbol = getFunctionBegin();
uint64_t StackSize =
FrameInfo.getStackSize() + FrameInfo.getUnsafeStackSize();
OutStreamer->emitSymbolValue(FunctionSymbol, TM.getProgramPointerSize());
OutStreamer->emitULEB128IntValue(StackSize);
OutStreamer->popSection();
}
void AsmPrinter::emitStackUsage(const MachineFunction &MF) {
const std::string &OutputFilename = MF.getTarget().Options.StackUsageOutput;
if (OutputFilename.empty())
return;
const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
uint64_t StackSize =
FrameInfo.getStackSize() + FrameInfo.getUnsafeStackSize();
if (StackUsageStream == nullptr) {
std::error_code EC;
StackUsageStream =
std::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::OF_Text);
if (EC) {
errs() << "Could not open file: " << EC.message();
return;
}
}
*StackUsageStream << MF.getFunction().getParent()->getName();
if (const DISubprogram *DSP = MF.getFunction().getSubprogram())
*StackUsageStream << ':' << DSP->getLine();
*StackUsageStream << ':' << MF.getName() << '\t' << StackSize << '\t';
if (FrameInfo.hasVarSizedObjects())
*StackUsageStream << "dynamic\n";
else
*StackUsageStream << "static\n";
}
static bool needFuncLabelsForEHOrDebugInfo(const MachineFunction &MF) {
MachineModuleInfo &MMI = MF.getMMI();
if (!MF.getLandingPads().empty() || MF.hasEHFunclets() || MMI.hasDebugInfo())
return true;
if (!MF.getFunction().hasPersonalityFn())
return false;
return !isNoOpWithoutInvoke(
classifyEHPersonality(MF.getFunction().getPersonalityFn()));
}
void AsmPrinter::emitFunctionBody() {
emitFunctionHeader();
emitFunctionBodyStart();
if (isVerbose()) {
MDT = getAnalysisIfAvailable<MachineDominatorTree>();
if (!MDT) {
OwnedMDT = std::make_unique<MachineDominatorTree>();
OwnedMDT->getBase().recalculate(*MF);
MDT = OwnedMDT.get();
}
MLI = getAnalysisIfAvailable<MachineLoopInfo>();
if (!MLI) {
OwnedMLI = std::make_unique<MachineLoopInfo>();
OwnedMLI->getBase().analyze(MDT->getBase());
MLI = OwnedMLI.get();
}
}
bool HasAnyRealCode = false;
int NumInstsInFunction = 0;
bool CanDoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
for (auto &MBB : *MF) {
emitBasicBlockStart(MBB);
DenseMap<StringRef, unsigned> MnemonicCounts;
for (auto &MI : MBB) {
if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
!MI.isDebugInstr()) {
HasAnyRealCode = true;
++NumInstsInFunction;
}
if (MCSymbol *S = MI.getPreInstrSymbol())
OutStreamer->emitLabel(S);
for (const HandlerInfo &HI : Handlers) {
NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
HI.TimerGroupDescription, TimePassesIsEnabled);
HI.Handler->beginInstruction(&MI);
}
if (isVerbose())
emitComments(MI, OutStreamer->getCommentOS());
switch (MI.getOpcode()) {
case TargetOpcode::CFI_INSTRUCTION:
emitCFIInstruction(MI);
break;
case TargetOpcode::LOCAL_ESCAPE:
emitFrameAlloc(MI);
break;
case TargetOpcode::ANNOTATION_LABEL:
case TargetOpcode::EH_LABEL:
case TargetOpcode::GC_LABEL:
OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
break;
case TargetOpcode::INLINEASM:
case TargetOpcode::INLINEASM_BR:
emitInlineAsm(&MI);
break;
case TargetOpcode::DBG_VALUE:
case TargetOpcode::DBG_VALUE_LIST:
if (isVerbose()) {
if (!emitDebugValueComment(&MI, *this))
emitInstruction(&MI);
}
break;
case TargetOpcode::DBG_INSTR_REF:
break;
case TargetOpcode::DBG_PHI:
break;
case TargetOpcode::DBG_LABEL:
if (isVerbose()) {
if (!emitDebugLabelComment(&MI, *this))
emitInstruction(&MI);
}
break;
case TargetOpcode::IMPLICIT_DEF:
if (isVerbose()) emitImplicitDef(&MI);
break;
case TargetOpcode::KILL:
if (isVerbose()) emitKill(&MI, *this);
break;
case TargetOpcode::PSEUDO_PROBE:
emitPseudoProbe(MI);
break;
case TargetOpcode::ARITH_FENCE:
if (isVerbose())
OutStreamer->emitRawComment("ARITH_FENCE");
break;
default:
emitInstruction(&MI);
if (CanDoExtraAnalysis) {
MCInst MCI;
MCI.setOpcode(MI.getOpcode());
auto Name = OutStreamer->getMnemonic(MCI);
auto I = MnemonicCounts.insert({Name, 0u});
I.first->second++;
}
break;
}
if (MCSymbol *S = MI.getPostInstrSymbol())
OutStreamer->emitLabel(S);
for (const HandlerInfo &HI : Handlers) {
NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
HI.TimerGroupDescription, TimePassesIsEnabled);
HI.Handler->endInstruction();
}
}
if (MF->hasBBLabels() ||
(MAI->hasDotTypeDotSizeDirective() && MBB.isEndSection()))
OutStreamer->emitLabel(MBB.getEndSymbol());
if (MBB.isEndSection()) {
if (!MBB.sameSection(&MF->front())) {
if (MAI->hasDotTypeDotSizeDirective()) {
const MCExpr *SizeExp = MCBinaryExpr::createSub(
MCSymbolRefExpr::create(MBB.getEndSymbol(), OutContext),
MCSymbolRefExpr::create(CurrentSectionBeginSym, OutContext),
OutContext);
OutStreamer->emitELFSize(CurrentSectionBeginSym, SizeExp);
}
MBBSectionRanges[MBB.getSectionIDNum()] =
MBBSectionRange{CurrentSectionBeginSym, MBB.getEndSymbol()};
}
}
emitBasicBlockEnd(MBB);
if (CanDoExtraAnalysis) {
if (MBB.empty())
continue;
MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionMix",
MBB.begin()->getDebugLoc(), &MBB);
SmallVector<std::pair<StringRef, unsigned>, 128> MnemonicVec;
for (auto &KV : MnemonicCounts)
MnemonicVec.emplace_back(KV.first, KV.second);
sort(MnemonicVec, [](const std::pair<StringRef, unsigned> &A,
const std::pair<StringRef, unsigned> &B) {
if (A.second > B.second)
return true;
if (A.second == B.second)
return StringRef(A.first) < StringRef(B.first);
return false;
});
R << "BasicBlock: " << ore::NV("BasicBlock", MBB.getName()) << "\n";
for (auto &KV : MnemonicVec) {
auto Name = (Twine("INST_") + getToken(KV.first.trim()).first).str();
R << KV.first << ": " << ore::NV(Name, KV.second) << "\n";
}
ORE->emit(R);
}
}
EmittedInsts += NumInstsInFunction;
MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
MF->getFunction().getSubprogram(),
&MF->front());
R << ore::NV("NumInstructions", NumInstsInFunction)
<< " instructions in function";
ORE->emit(R);
const Triple &TT = TM.getTargetTriple();
if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
(TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
MCInst Noop = MF->getSubtarget().getInstrInfo()->getNop();
if (Noop.getOpcode()) {
OutStreamer->AddComment("avoids zero-length function");
emitNops(1);
}
}
OutStreamer->switchSection(MF->getSection());
const Function &F = MF->getFunction();
for (const auto &BB : F) {
if (!BB.hasAddressTaken())
continue;
MCSymbol *Sym = GetBlockAddressSymbol(&BB);
if (Sym->isDefined())
continue;
OutStreamer->AddComment("Address of block that was removed by CodeGen");
OutStreamer->emitLabel(Sym);
}
emitFunctionBodyEnd();
if (needFuncLabelsForEHOrDebugInfo(*MF) ||
MAI->hasDotTypeDotSizeDirective()) {
CurrentFnEnd = createTempSymbol("func_end");
OutStreamer->emitLabel(CurrentFnEnd);
}
if (MAI->hasDotTypeDotSizeDirective()) {
const MCExpr *SizeExp = MCBinaryExpr::createSub(
MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext);
OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
}
for (const HandlerInfo &HI : Handlers) {
NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
HI.TimerGroupDescription, TimePassesIsEnabled);
HI.Handler->markFunctionEnd();
}
MBBSectionRanges[MF->front().getSectionIDNum()] =
MBBSectionRange{CurrentFnBegin, CurrentFnEnd};
emitJumpTableInfo();
for (const HandlerInfo &HI : Handlers) {
NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
HI.TimerGroupDescription, TimePassesIsEnabled);
HI.Handler->endFunction(MF);
}
if (MF->hasBBLabels() && HasAnyRealCode)
emitBBAddrMapSection(*MF);
emitStackSizeSection(*MF);
emitStackUsage(*MF);
emitPatchableFunctionEntries();
if (isVerbose())
OutStreamer->getCommentOS() << "-- End function\n";
OutStreamer->addBlankLine();
}
static unsigned getNumGlobalVariableUses(const Constant *C) {
if (!C)
return 0;
if (isa<GlobalVariable>(C))
return 1;
unsigned NumUses = 0;
for (const auto *CU : C->users())
NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
return NumUses;
}
static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
unsigned &NumGOTEquivUsers) {
if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
!GV->isConstant() || !GV->isDiscardableIfUnused() ||
!isa<GlobalValue>(GV->getOperand(0)))
return false;
for (const auto *U : GV->users())
NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
return NumGOTEquivUsers > 0;
}
void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
return;
for (const auto &G : M.globals()) {
unsigned NumGOTEquivUsers = 0;
if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
continue;
const MCSymbol *GOTEquivSym = getSymbol(&G);
GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
}
}
void AsmPrinter::emitGlobalGOTEquivs() {
if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
return;
SmallVector<const GlobalVariable *, 8> FailedCandidates;
for (auto &I : GlobalGOTEquivs) {
const GlobalVariable *GV = I.second.first;
unsigned Cnt = I.second.second;
if (Cnt)
FailedCandidates.push_back(GV);
}
GlobalGOTEquivs.clear();
for (const auto *GV : FailedCandidates)
emitGlobalVariable(GV);
}
void AsmPrinter::emitGlobalAlias(Module &M, const GlobalAlias &GA) {
MCSymbol *Name = getSymbol(&GA);
bool IsFunction = GA.getValueType()->isFunctionTy();
if (!IsFunction)
IsFunction = isa<Function>(GA.getAliasee()->stripPointerCasts());
if (TM.getTargetTriple().isOSBinFormatXCOFF()) {
assert(MAI->hasVisibilityOnlyWithLinkage() &&
"Visibility should be handled with emitLinkage() on AIX.");
if (isa<GlobalVariable>(GA.getAliaseeObject()))
return;
emitLinkage(&GA, Name);
if (IsFunction)
emitLinkage(&GA,
getObjFileLowering().getFunctionEntryPointSymbol(&GA, TM));
return;
}
if (GA.hasExternalLinkage() || !MAI->getWeakRefDirective())
OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
else if (GA.hasWeakLinkage() || GA.hasLinkOnceLinkage())
OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
else
assert(GA.hasLocalLinkage() && "Invalid alias linkage");
if (IsFunction) {
OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
if (TM.getTargetTriple().isOSBinFormatCOFF()) {
OutStreamer->beginCOFFSymbolDef(Name);
OutStreamer->emitCOFFSymbolStorageClass(
GA.hasLocalLinkage() ? COFF::IMAGE_SYM_CLASS_STATIC
: COFF::IMAGE_SYM_CLASS_EXTERNAL);
OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
<< COFF::SCT_COMPLEX_TYPE_SHIFT);
OutStreamer->endCOFFSymbolDef();
}
}
emitVisibility(Name, GA.getVisibility());
const MCExpr *Expr = lowerConstant(GA.getAliasee());
if (MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr))
OutStreamer->emitSymbolAttribute(Name, MCSA_AltEntry);
OutStreamer->emitAssignment(Name, Expr);
MCSymbol *LocalAlias = getSymbolPreferLocal(GA);
if (LocalAlias != Name)
OutStreamer->emitAssignment(LocalAlias, Expr);
const GlobalObject *BaseObject = GA.getAliaseeObject();
if (MAI->hasDotTypeDotSizeDirective() && GA.getValueType()->isSized() &&
(!BaseObject || BaseObject->hasPrivateLinkage())) {
const DataLayout &DL = M.getDataLayout();
uint64_t Size = DL.getTypeAllocSize(GA.getValueType());
OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
}
}
void AsmPrinter::emitGlobalIFunc(Module &M, const GlobalIFunc &GI) {
assert(!TM.getTargetTriple().isOSBinFormatXCOFF() &&
"IFunc is not supported on AIX.");
MCSymbol *Name = getSymbol(&GI);
if (GI.hasExternalLinkage() || !MAI->getWeakRefDirective())
OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
else if (GI.hasWeakLinkage() || GI.hasLinkOnceLinkage())
OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
else
assert(GI.hasLocalLinkage() && "Invalid ifunc linkage");
OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction);
emitVisibility(Name, GI.getVisibility());
const MCExpr *Expr = lowerConstant(GI.getResolver());
OutStreamer->emitAssignment(Name, Expr);
MCSymbol *LocalAlias = getSymbolPreferLocal(GI);
if (LocalAlias != Name)
OutStreamer->emitAssignment(LocalAlias, Expr);
}
void AsmPrinter::emitRemarksSection(remarks::RemarkStreamer &RS) {
if (!RS.needsSection())
return;
remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
Optional<SmallString<128>> Filename;
if (Optional<StringRef> FilenameRef = RS.getFilename()) {
Filename = *FilenameRef;
sys::fs::make_absolute(*Filename);
assert(!Filename->empty() && "The filename can't be empty.");
}
std::string Buf;
raw_string_ostream OS(Buf);
std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
Filename ? RemarkSerializer.metaSerializer(OS, Filename->str())
: RemarkSerializer.metaSerializer(OS);
MetaSerializer->emit();
MCSection *RemarksSection =
OutContext.getObjectFileInfo()->getRemarksSection();
OutStreamer->switchSection(RemarksSection);
OutStreamer->emitBinaryData(OS.str());
}
bool AsmPrinter::doFinalization(Module &M) {
MF = nullptr;
computeGlobalGOTEquivs(M);
for (const auto &G : M.globals())
emitGlobalVariable(&G);
emitGlobalGOTEquivs();
const TargetLoweringObjectFile &TLOF = getObjFileLowering();
for (const Function &F : M) {
if (!F.isDeclarationForLinker())
continue;
MCSymbol *Name = getSymbol(&F);
if (!TM.getTargetTriple().isOSBinFormatXCOFF()) {
GlobalValue::VisibilityTypes V = F.getVisibility();
if (V == GlobalValue::DefaultVisibility)
continue;
emitVisibility(Name, V, false);
continue;
}
if (F.isIntrinsic())
continue;
MCSymbol *FnEntryPointSym = TLOF.getFunctionEntryPointSymbol(&F, TM);
emitLinkage(&F, FnEntryPointSym);
emitLinkage(&F, Name);
}
if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer())
emitRemarksSection(*RS);
TLOF.emitModuleMetadata(*OutStreamer, M);
if (TM.getTargetTriple().isOSBinFormatELF()) {
MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
if (!Stubs.empty()) {
OutStreamer->switchSection(TLOF.getDataSection());
const DataLayout &DL = M.getDataLayout();
emitAlignment(Align(DL.getPointerSize()));
for (const auto &Stub : Stubs) {
OutStreamer->emitLabel(Stub.first);
OutStreamer->emitSymbolValue(Stub.second.getPointer(),
DL.getPointerSize());
}
}
}
if (TM.getTargetTriple().isOSBinFormatCOFF()) {
MachineModuleInfoCOFF &MMICOFF =
MMI->getObjFileInfo<MachineModuleInfoCOFF>();
MachineModuleInfoCOFF::SymbolListTy Stubs = MMICOFF.GetGVStubList();
if (!Stubs.empty()) {
const DataLayout &DL = M.getDataLayout();
for (const auto &Stub : Stubs) {
SmallString<256> SectionName = StringRef(".rdata$");
SectionName += Stub.first->getName();
OutStreamer->switchSection(OutContext.getCOFFSection(
SectionName,
COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ |
COFF::IMAGE_SCN_LNK_COMDAT,
SectionKind::getReadOnly(), Stub.first->getName(),
COFF::IMAGE_COMDAT_SELECT_ANY));
emitAlignment(Align(DL.getPointerSize()));
OutStreamer->emitSymbolAttribute(Stub.first, MCSA_Global);
OutStreamer->emitLabel(Stub.first);
OutStreamer->emitSymbolValue(Stub.second.getPointer(),
DL.getPointerSize());
}
}
}
if (auto *TS = OutStreamer->getTargetStreamer())
TS->emitConstantPools();
for (const HandlerInfo &HI : Handlers) {
NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
HI.TimerGroupDescription, TimePassesIsEnabled);
HI.Handler->endModule();
}
Handlers.erase(Handlers.begin() + NumUserHandlers, Handlers.end());
DD = nullptr;
if (MAI->getWeakRefDirective()) {
for (const auto &GO : M.global_objects()) {
if (!GO.hasExternalWeakLinkage())
continue;
OutStreamer->emitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
}
if (shouldEmitWeakSwiftAsyncExtendedFramePointerFlags()) {
auto SymbolName = "swift_async_extendedFramePointerFlags";
auto Global = M.getGlobalVariable(SymbolName);
if (!Global) {
auto Int8PtrTy = Type::getInt8PtrTy(M.getContext());
Global = new GlobalVariable(M, Int8PtrTy, false,
GlobalValue::ExternalWeakLinkage, nullptr,
SymbolName);
OutStreamer->emitSymbolAttribute(getSymbol(Global), MCSA_WeakReference);
}
}
}
SmallVector<const GlobalAlias *, 16> AliasStack;
SmallPtrSet<const GlobalAlias *, 16> AliasVisited;
for (const auto &Alias : M.aliases()) {
for (const GlobalAlias *Cur = &Alias; Cur;
Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
if (!AliasVisited.insert(Cur).second)
break;
AliasStack.push_back(Cur);
}
for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
emitGlobalAlias(M, *AncestorAlias);
AliasStack.clear();
}
for (const auto &IFunc : M.ifuncs())
emitGlobalIFunc(M, IFunc);
GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
assert(MI && "AsmPrinter didn't require GCModuleInfo?");
for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
MP->finishAssembly(M, *MI, *this);
emitModuleIdents(M);
emitModuleCommandLines(M);
if (TM.getTargetTriple().isOSBinFormatELF() && HasSplitStack) {
OutStreamer->switchSection(OutContext.getELFSection(".note.GNU-split-stack",
ELF::SHT_PROGBITS, 0));
if (HasNoSplitStack)
OutStreamer->switchSection(OutContext.getELFSection(
".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
}
Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
OutStreamer->switchSection(S);
if (TM.Options.EmitAddrsig) {
OutStreamer->emitAddrsig();
for (const GlobalValue &GV : M.global_values()) {
if (!GV.use_empty() && !GV.isTransitiveUsedByMetadataOnly() &&
!GV.isThreadLocal() && !GV.hasDLLImportStorageClass() &&
!GV.getName().startswith("llvm.") && !GV.hasAtLeastLocalUnnamedAddr())
OutStreamer->emitAddrsigSym(getSymbol(&GV));
}
}
if (TM.getTargetTriple().isOSBinFormatELF()) {
unsigned UniqueID = 0;
for (const GlobalValue &GV : M.global_values()) {
if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
GV.getVisibility() != GlobalValue::DefaultVisibility)
continue;
OutStreamer->switchSection(
OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0,
"", false, ++UniqueID, nullptr));
OutStreamer->emitBytes(GV.getPartition());
OutStreamer->emitZeros(1);
OutStreamer->emitValue(
MCSymbolRefExpr::create(getSymbol(&GV), OutContext),
MAI->getCodePointerSize());
}
}
emitEndOfAsmFile(M);
MMI = nullptr;
AddrLabelSymbols = nullptr;
OutStreamer->finish();
OutStreamer->reset();
OwnedMLI.reset();
OwnedMDT.reset();
return false;
}
MCSymbol *AsmPrinter::getMBBExceptionSym(const MachineBasicBlock &MBB) {
auto Res = MBBSectionExceptionSyms.try_emplace(MBB.getSectionIDNum());
if (Res.second)
Res.first->second = createTempSymbol("exception");
return Res.first->second;
}
void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
this->MF = &MF;
const Function &F = MF.getFunction();
if (MF.shouldSplitStack()) {
HasSplitStack = true;
if (!MF.getFrameInfo().needsSplitStackProlog())
HasNoSplitStack = true;
} else
HasNoSplitStack = true;
if (!MAI->needsFunctionDescriptors()) {
CurrentFnSym = getSymbol(&MF.getFunction());
} else {
assert(TM.getTargetTriple().isOSAIX() &&
"Only AIX uses the function descriptor hooks.");
assert(CurrentFnDescSym && "The function descriptor symbol needs to be"
" initalized first.");
CurrentFnSym = getObjFileLowering().getFunctionEntryPointSymbol(&F, TM);
}
CurrentFnSymForSize = CurrentFnSym;
CurrentFnBegin = nullptr;
CurrentSectionBeginSym = nullptr;
MBBSectionRanges.clear();
MBBSectionExceptionSyms.clear();
bool NeedsLocalForSize = MAI->needsLocalForSize();
if (F.hasFnAttribute("patchable-function-entry") ||
F.hasFnAttribute("function-instrument") ||
F.hasFnAttribute("xray-instruction-threshold") ||
needFuncLabelsForEHOrDebugInfo(MF) || NeedsLocalForSize ||
MF.getTarget().Options.EmitStackSizeSection || MF.hasBBLabels()) {
CurrentFnBegin = createTempSymbol("func_begin");
if (NeedsLocalForSize)
CurrentFnSymForSize = CurrentFnBegin;
}
ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
}
namespace {
struct SectionCPs {
MCSection *S;
Align Alignment;
SmallVector<unsigned, 4> CPEs;
SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {}
};
}
void AsmPrinter::emitConstantPool() {
const MachineConstantPool *MCP = MF->getConstantPool();
const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
if (CP.empty()) return;
SmallVector<SectionCPs, 4> CPSections;
for (unsigned i = 0, e = CP.size(); i != e; ++i) {
const MachineConstantPoolEntry &CPE = CP[i];
Align Alignment = CPE.getAlign();
SectionKind Kind = CPE.getSectionKind(&getDataLayout());
const Constant *C = nullptr;
if (!CPE.isMachineConstantPoolEntry())
C = CPE.Val.ConstVal;
MCSection *S = getObjFileLowering().getSectionForConstant(
getDataLayout(), Kind, C, Alignment);
bool Found = false;
unsigned SecIdx = CPSections.size();
while (SecIdx != 0) {
if (CPSections[--SecIdx].S == S) {
Found = true;
break;
}
}
if (!Found) {
SecIdx = CPSections.size();
CPSections.push_back(SectionCPs(S, Alignment));
}
if (Alignment > CPSections[SecIdx].Alignment)
CPSections[SecIdx].Alignment = Alignment;
CPSections[SecIdx].CPEs.push_back(i);
}
const MCSection *CurSection = nullptr;
unsigned Offset = 0;
for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
unsigned CPI = CPSections[i].CPEs[j];
MCSymbol *Sym = GetCPISymbol(CPI);
if (!Sym->isUndefined())
continue;
if (CurSection != CPSections[i].S) {
OutStreamer->switchSection(CPSections[i].S);
emitAlignment(Align(CPSections[i].Alignment));
CurSection = CPSections[i].S;
Offset = 0;
}
MachineConstantPoolEntry CPE = CP[CPI];
unsigned NewOffset = alignTo(Offset, CPE.getAlign());
OutStreamer->emitZeros(NewOffset - Offset);
Offset = NewOffset + CPE.getSizeInBytes(getDataLayout());
OutStreamer->emitLabel(Sym);
if (CPE.isMachineConstantPoolEntry())
emitMachineConstantPoolValue(CPE.Val.MachineCPVal);
else
emitGlobalConstant(getDataLayout(), CPE.Val.ConstVal);
}
}
}
void AsmPrinter::emitJumpTableInfo() {
const DataLayout &DL = MF->getDataLayout();
const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
if (!MJTI) return;
if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
if (JT.empty()) return;
const Function &F = MF->getFunction();
const TargetLoweringObjectFile &TLOF = getObjFileLowering();
bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
F);
if (JTInDiffSection) {
MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
OutStreamer->switchSection(ReadOnlySection);
}
emitAlignment(Align(MJTI->getEntryAlignment(DL)));
if (!JTInDiffSection)
OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
if (JTBBs.empty()) continue;
if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
MAI->doesSetDirectiveSuppressReloc()) {
SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
for (const MachineBasicBlock *MBB : JTBBs) {
if (!EmittedSets.insert(MBB).second)
continue;
const MCExpr *LHS =
MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
OutStreamer->emitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
MCBinaryExpr::createSub(LHS, Base,
OutContext));
}
}
if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
OutStreamer->emitLabel(GetJTISymbol(JTI, true));
MCSymbol* JTISymbol = GetJTISymbol(JTI);
OutStreamer->emitLabel(JTISymbol);
for (const MachineBasicBlock *MBB : JTBBs)
emitJumpTableEntry(MJTI, MBB, JTI);
}
if (!JTInDiffSection)
OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
}
void AsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo *MJTI,
const MachineBasicBlock *MBB,
unsigned UID) const {
assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
const MCExpr *Value = nullptr;
switch (MJTI->getEntryKind()) {
case MachineJumpTableInfo::EK_Inline:
llvm_unreachable("Cannot emit EK_Inline jump table entry");
case MachineJumpTableInfo::EK_Custom32:
Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
MJTI, MBB, UID, OutContext);
break;
case MachineJumpTableInfo::EK_BlockAddress:
Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
break;
case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
MCSymbol *MBBSym = MBB->getSymbol();
OutStreamer->emitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
return;
}
case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
MCSymbol *MBBSym = MBB->getSymbol();
OutStreamer->emitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
return;
}
case MachineJumpTableInfo::EK_LabelDifference32: {
if (MAI->doesSetDirectiveSuppressReloc()) {
Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
OutContext);
break;
}
Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
Value = MCBinaryExpr::createSub(Value, Base, OutContext);
break;
}
}
assert(Value && "Unknown entry kind!");
unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
OutStreamer->emitValue(Value, EntrySize);
}
bool AsmPrinter::emitSpecialLLVMGlobal(const GlobalVariable *GV) {
if (GV->getName() == "llvm.used") {
if (MAI->hasNoDeadStrip()) emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
return true;
}
if (GV->getSection() == "llvm.metadata" ||
GV->hasAvailableExternallyLinkage())
return true;
if (!GV->hasAppendingLinkage()) return false;
assert(GV->hasInitializer() && "Not a special LLVM global!");
if (GV->getName() == "llvm.global_ctors") {
emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
true);
return true;
}
if (GV->getName() == "llvm.global_dtors") {
emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
false);
return true;
}
report_fatal_error("unknown special variable");
}
void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) {
for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
const GlobalValue *GV =
dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
if (GV)
OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
}
}
void AsmPrinter::preprocessXXStructorList(const DataLayout &DL,
const Constant *List,
SmallVector<Structor, 8> &Structors) {
if (!isa<ConstantArray>(List))
return;
for (Value *O : cast<ConstantArray>(List)->operands()) {
auto *CS = cast<ConstantStruct>(O);
if (CS->getOperand(1)->isNullValue())
break; ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
if (!Priority)
continue; Structors.push_back(Structor());
Structor &S = Structors.back();
S.Priority = Priority->getLimitedValue(65535);
S.Func = CS->getOperand(1);
if (!CS->getOperand(2)->isNullValue()) {
if (TM.getTargetTriple().isOSAIX())
llvm::report_fatal_error(
"associated data of XXStructor list is not yet supported on AIX");
S.ComdatKey =
dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
}
}
llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
return L.Priority < R.Priority;
});
}
void AsmPrinter::emitXXStructorList(const DataLayout &DL, const Constant *List,
bool IsCtor) {
SmallVector<Structor, 8> Structors;
preprocessXXStructorList(DL, List, Structors);
if (Structors.empty())
return;
if (!TM.Options.UseInitArray)
std::reverse(Structors.begin(), Structors.end());
const Align Align = DL.getPointerPrefAlignment();
for (Structor &S : Structors) {
const TargetLoweringObjectFile &Obj = getObjFileLowering();
const MCSymbol *KeySym = nullptr;
if (GlobalValue *GV = S.ComdatKey) {
if (GV->isDeclarationForLinker())
continue;
KeySym = getSymbol(GV);
}
MCSection *OutputSection =
(IsCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
: Obj.getStaticDtorSection(S.Priority, KeySym));
OutStreamer->switchSection(OutputSection);
if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
emitAlignment(Align);
emitXXStructor(DL, S.Func);
}
}
void AsmPrinter::emitModuleIdents(Module &M) {
if (!MAI->hasIdentDirective())
return;
if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
const MDNode *N = NMD->getOperand(i);
assert(N->getNumOperands() == 1 &&
"llvm.ident metadata entry can have only one operand");
const MDString *S = cast<MDString>(N->getOperand(0));
OutStreamer->emitIdent(S->getString());
}
}
}
void AsmPrinter::emitModuleCommandLines(Module &M) {
MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines();
if (!CommandLine)
return;
const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
if (!NMD || !NMD->getNumOperands())
return;
OutStreamer->pushSection();
OutStreamer->switchSection(CommandLine);
OutStreamer->emitZeros(1);
for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
const MDNode *N = NMD->getOperand(i);
assert(N->getNumOperands() == 1 &&
"llvm.commandline metadata entry can have only one operand");
const MDString *S = cast<MDString>(N->getOperand(0));
OutStreamer->emitBytes(S->getString());
OutStreamer->emitZeros(1);
}
OutStreamer->popSection();
}
void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
void AsmPrinter::emitInt64(uint64_t Value) const {
OutStreamer->emitInt64(Value);
}
void AsmPrinter::emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
unsigned Size) const {
OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
}
void AsmPrinter::emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
unsigned Size,
bool IsSectionRelative) const {
if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
OutStreamer->emitCOFFSecRel32(Label, Offset);
if (Size > 4)
OutStreamer->emitZeros(Size - 4);
return;
}
const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
if (Offset)
Expr = MCBinaryExpr::createAdd(
Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
OutStreamer->emitValue(Expr, Size);
}
void AsmPrinter::emitAlignment(Align Alignment, const GlobalObject *GV,
unsigned MaxBytesToEmit) const {
if (GV)
Alignment = getGVAlignment(GV, GV->getParent()->getDataLayout(), Alignment);
if (Alignment == Align(1))
return;
if (getCurrentSection()->getKind().isText()) {
const MCSubtargetInfo *STI = nullptr;
if (this->MF)
STI = &getSubtargetInfo();
else
STI = TM.getMCSubtargetInfo();
OutStreamer->emitCodeAlignment(Alignment.value(), STI, MaxBytesToEmit);
} else
OutStreamer->emitValueToAlignment(Alignment.value(), 0, 1, MaxBytesToEmit);
}
const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
MCContext &Ctx = OutContext;
if (CV->isNullValue() || isa<UndefValue>(CV))
return MCConstantExpr::create(0, Ctx);
if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
return MCConstantExpr::create(CI->getZExtValue(), Ctx);
if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV))
return getObjFileLowering().lowerDSOLocalEquivalent(Equiv, TM);
if (const NoCFIValue *NC = dyn_cast<NoCFIValue>(CV))
return MCSymbolRefExpr::create(getSymbol(NC->getGlobalValue()), Ctx);
const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
if (!CE) {
llvm_unreachable("Unknown constant value to lower!");
}
switch (CE->getOpcode()) {
default:
break; case Instruction::AddrSpaceCast: {
const Constant *Op = CE->getOperand(0);
unsigned DstAS = CE->getType()->getPointerAddressSpace();
unsigned SrcAS = Op->getType()->getPointerAddressSpace();
if (TM.isNoopAddrSpaceCast(SrcAS, DstAS))
return lowerConstant(Op);
break; }
case Instruction::GetElementPtr: {
APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
const MCExpr *Base = lowerConstant(CE->getOperand(0));
if (!OffsetAI)
return Base;
int64_t Offset = OffsetAI.getSExtValue();
return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
Ctx);
}
case Instruction::Trunc:
LLVM_FALLTHROUGH;
case Instruction::BitCast:
return lowerConstant(CE->getOperand(0));
case Instruction::IntToPtr: {
const DataLayout &DL = getDataLayout();
Constant *Op = CE->getOperand(0);
Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
false);
return lowerConstant(Op);
}
case Instruction::PtrToInt: {
const DataLayout &DL = getDataLayout();
Constant *Op = CE->getOperand(0);
Type *Ty = CE->getType();
const MCExpr *OpExpr = lowerConstant(Op);
if (DL.getTypeAllocSize(Ty).getFixedSize() <=
DL.getTypeAllocSize(Op->getType()).getFixedSize())
return OpExpr;
break; }
case Instruction::Sub: {
GlobalValue *LHSGV;
APInt LHSOffset;
DSOLocalEquivalent *DSOEquiv;
if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
getDataLayout(), &DSOEquiv)) {
GlobalValue *RHSGV;
APInt RHSOffset;
if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
getDataLayout())) {
const MCExpr *RelocExpr =
getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
if (!RelocExpr) {
const MCExpr *LHSExpr =
MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx);
if (DSOEquiv &&
getObjFileLowering().supportDSOLocalEquivalentLowering())
LHSExpr =
getObjFileLowering().lowerDSOLocalEquivalent(DSOEquiv, TM);
RelocExpr = MCBinaryExpr::createSub(
LHSExpr, MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
}
int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
if (Addend != 0)
RelocExpr = MCBinaryExpr::createAdd(
RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
return RelocExpr;
}
}
const MCExpr *LHS = lowerConstant(CE->getOperand(0));
const MCExpr *RHS = lowerConstant(CE->getOperand(1));
return MCBinaryExpr::createSub(LHS, RHS, Ctx);
break;
}
case Instruction::Add: {
const MCExpr *LHS = lowerConstant(CE->getOperand(0));
const MCExpr *RHS = lowerConstant(CE->getOperand(1));
return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
}
}
Constant *C = ConstantFoldConstant(CE, getDataLayout());
if (C != CE)
return lowerConstant(C);
std::string S;
raw_string_ostream OS(S);
OS << "Unsupported expression in static initializer: ";
CE->printAsOperand(OS, false,
!MF ? nullptr : MF->getFunction().getParent());
report_fatal_error(Twine(OS.str()));
}
static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
AsmPrinter &AP,
const Constant *BaseCV = nullptr,
uint64_t Offset = 0,
AsmPrinter::AliasMapTy *AliasList = nullptr);
static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
static int isRepeatedByteSequence(const ConstantDataSequential *V) {
StringRef Data = V->getRawDataValues();
assert(!Data.empty() && "Empty aggregates should be CAZ node");
char C = Data[0];
for (unsigned i = 1, e = Data.size(); i != e; ++i)
if (Data[i] != C) return -1;
return static_cast<uint8_t>(C); }
static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
assert(Size % 8 == 0);
APInt Value = CI->getValue().zext(Size);
if (!Value.isSplat(8))
return -1;
return Value.zextOrTrunc(8).getZExtValue();
}
if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
assert(CA->getNumOperands() != 0 && "Should be a CAZ");
Constant *Op0 = CA->getOperand(0);
int Byte = isRepeatedByteSequence(Op0, DL);
if (Byte == -1)
return -1;
for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
if (CA->getOperand(i) != Op0)
return -1;
return Byte;
}
if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
return isRepeatedByteSequence(CDS);
return -1;
}
static void emitGlobalAliasInline(AsmPrinter &AP, uint64_t Offset,
AsmPrinter::AliasMapTy *AliasList) {
if (AliasList) {
auto AliasIt = AliasList->find(Offset);
if (AliasIt != AliasList->end()) {
for (const GlobalAlias *GA : AliasIt->second)
AP.OutStreamer->emitLabel(AP.getSymbol(GA));
AliasList->erase(Offset);
}
}
}
static void emitGlobalConstantDataSequential(
const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP,
AsmPrinter::AliasMapTy *AliasList) {
int Value = isRepeatedByteSequence(CDS, DL);
if (Value != -1) {
uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
if (Bytes > 1)
return AP.OutStreamer->emitFill(Bytes, Value);
}
if (CDS->isString())
return AP.OutStreamer->emitBytes(CDS->getAsString());
unsigned ElementByteSize = CDS->getElementByteSize();
if (isa<IntegerType>(CDS->getElementType())) {
for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) {
emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
if (AP.isVerbose())
AP.OutStreamer->getCommentOS()
<< format("0x%" PRIx64 "\n", CDS->getElementAsInteger(I));
AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(I),
ElementByteSize);
}
} else {
Type *ET = CDS->getElementType();
for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) {
emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
emitGlobalConstantFP(CDS->getElementAsAPFloat(I), ET, AP);
}
}
unsigned Size = DL.getTypeAllocSize(CDS->getType());
unsigned EmittedSize =
DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements();
assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
if (unsigned Padding = Size - EmittedSize)
AP.OutStreamer->emitZeros(Padding);
}
static void emitGlobalConstantArray(const DataLayout &DL,
const ConstantArray *CA, AsmPrinter &AP,
const Constant *BaseCV, uint64_t Offset,
AsmPrinter::AliasMapTy *AliasList) {
int Value = isRepeatedByteSequence(CA, DL);
if (Value != -1) {
uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
AP.OutStreamer->emitFill(Bytes, Value);
} else {
for (unsigned I = 0, E = CA->getNumOperands(); I != E; ++I) {
emitGlobalConstantImpl(DL, CA->getOperand(I), AP, BaseCV, Offset,
AliasList);
Offset += DL.getTypeAllocSize(CA->getOperand(I)->getType());
}
}
}
static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP);
static void emitGlobalConstantVector(const DataLayout &DL,
const ConstantVector *CV, AsmPrinter &AP,
AsmPrinter::AliasMapTy *AliasList) {
Type *ElementType = CV->getType()->getElementType();
uint64_t ElementSizeInBits = DL.getTypeSizeInBits(ElementType);
uint64_t ElementAllocSizeInBits = DL.getTypeAllocSizeInBits(ElementType);
uint64_t EmittedSize;
if (ElementSizeInBits != ElementAllocSizeInBits) {
Type *IntT =
IntegerType::get(CV->getContext(), DL.getTypeSizeInBits(CV->getType()));
ConstantInt *CI = dyn_cast_or_null<ConstantInt>(ConstantFoldConstant(
ConstantExpr::getBitCast(const_cast<ConstantVector *>(CV), IntT), DL));
if (!CI) {
report_fatal_error(
"Cannot lower vector global with unusual element type");
}
emitGlobalAliasInline(AP, 0, AliasList);
emitGlobalConstantLargeInt(CI, AP);
EmittedSize = DL.getTypeStoreSize(CV->getType());
} else {
for (unsigned I = 0, E = CV->getType()->getNumElements(); I != E; ++I) {
emitGlobalAliasInline(AP, DL.getTypeAllocSize(CV->getType()) * I, AliasList);
emitGlobalConstantImpl(DL, CV->getOperand(I), AP);
}
EmittedSize =
DL.getTypeAllocSize(ElementType) * CV->getType()->getNumElements();
}
unsigned Size = DL.getTypeAllocSize(CV->getType());
if (unsigned Padding = Size - EmittedSize)
AP.OutStreamer->emitZeros(Padding);
}
static void emitGlobalConstantStruct(const DataLayout &DL,
const ConstantStruct *CS, AsmPrinter &AP,
const Constant *BaseCV, uint64_t Offset,
AsmPrinter::AliasMapTy *AliasList) {
unsigned Size = DL.getTypeAllocSize(CS->getType());
const StructLayout *Layout = DL.getStructLayout(CS->getType());
uint64_t SizeSoFar = 0;
for (unsigned I = 0, E = CS->getNumOperands(); I != E; ++I) {
const Constant *Field = CS->getOperand(I);
emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar,
AliasList);
uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
uint64_t PadSize = ((I == E - 1 ? Size : Layout->getElementOffset(I + 1)) -
Layout->getElementOffset(I)) -
FieldSize;
SizeSoFar += FieldSize + PadSize;
AP.OutStreamer->emitZeros(PadSize);
}
assert(SizeSoFar == Layout->getSizeInBytes() &&
"Layout of constant struct may be incorrect!");
}
static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
assert(ET && "Unknown float type");
APInt API = APF.bitcastToAPInt();
if (AP.isVerbose()) {
SmallString<8> StrVal;
APF.toString(StrVal);
ET->print(AP.OutStreamer->getCommentOS());
AP.OutStreamer->getCommentOS() << ' ' << StrVal << '\n';
}
unsigned NumBytes = API.getBitWidth() / 8;
unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
const uint64_t *p = API.getRawData();
if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
int Chunk = API.getNumWords() - 1;
if (TrailingBytes)
AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
for (; Chunk >= 0; --Chunk)
AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
} else {
unsigned Chunk;
for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
if (TrailingBytes)
AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
}
const DataLayout &DL = AP.getDataLayout();
AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
}
static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
}
static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
const DataLayout &DL = AP.getDataLayout();
unsigned BitWidth = CI->getBitWidth();
APInt Realigned(CI->getValue());
uint64_t ExtraBits = 0;
unsigned ExtraBitsSize = BitWidth & 63;
if (ExtraBitsSize) {
if (DL.isBigEndian()) {
ExtraBitsSize = alignTo(ExtraBitsSize, 8);
ExtraBits = Realigned.getRawData()[0] &
(((uint64_t)-1) >> (64 - ExtraBitsSize));
Realigned.lshrInPlace(ExtraBitsSize);
} else
ExtraBits = Realigned.getRawData()[BitWidth / 64];
}
const uint64_t *RawData = Realigned.getRawData();
for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
AP.OutStreamer->emitIntValue(Val, 8);
}
if (ExtraBitsSize) {
uint64_t Size = AP.getDataLayout().getTypeStoreSize(CI->getType());
Size -= (BitWidth / 64) * 8;
assert(Size && Size * 8 >= ExtraBitsSize &&
(ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
== ExtraBits && "Directive too small for extra bits.");
AP.OutStreamer->emitIntValue(ExtraBits, Size);
}
}
static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
const Constant *BaseCst,
uint64_t Offset) {
MCValue MV;
if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
return;
const MCSymbolRefExpr *SymA = MV.getSymA();
if (!SymA)
return;
const MCSymbol *GOTEquivSym = &SymA->getSymbol();
if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
return;
const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
if (!BaseGV)
return;
const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
const MCSymbolRefExpr *SymB = MV.getSymB();
if (!SymB || BaseSym != &SymB->getSymbol())
return;
int64_t GOTPCRelCst = Offset + MV.getConstant();
if (GOTPCRelCst < 0)
return;
if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
return;
AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
const GlobalVariable *GV = Result.first;
int NumUses = (int)Result.second;
const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
*ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
--NumUses;
if (NumUses >= 0)
AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
}
static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
AsmPrinter &AP, const Constant *BaseCV,
uint64_t Offset,
AsmPrinter::AliasMapTy *AliasList) {
emitGlobalAliasInline(AP, Offset, AliasList);
uint64_t Size = DL.getTypeAllocSize(CV->getType());
if (!BaseCV && CV->hasOneUse())
BaseCV = dyn_cast<Constant>(CV->user_back());
if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
return AP.OutStreamer->emitZeros(Size);
if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
if (StoreSize <= 8) {
if (AP.isVerbose())
AP.OutStreamer->getCommentOS()
<< format("0x%" PRIx64 "\n", CI->getZExtValue());
AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize);
} else {
emitGlobalConstantLargeInt(CI, AP);
}
if (Size != StoreSize)
AP.OutStreamer->emitZeros(Size - StoreSize);
return;
}
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
return emitGlobalConstantFP(CFP, AP);
if (isa<ConstantPointerNull>(CV)) {
AP.OutStreamer->emitIntValue(0, Size);
return;
}
if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
return emitGlobalConstantDataSequential(DL, CDS, AP, AliasList);
if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset, AliasList);
if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset, AliasList);
if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
if (CE->getOpcode() == Instruction::BitCast)
return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
if (Size > 8) {
Constant *New = ConstantFoldConstant(CE, DL);
if (New != CE)
return emitGlobalConstantImpl(DL, New, AP);
}
}
if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
return emitGlobalConstantVector(DL, V, AP, AliasList);
const MCExpr *ME = AP.lowerConstant(CV);
if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
AP.OutStreamer->emitValue(ME, Size);
}
void AsmPrinter::emitGlobalConstant(const DataLayout &DL, const Constant *CV,
AliasMapTy *AliasList) {
uint64_t Size = DL.getTypeAllocSize(CV->getType());
if (Size)
emitGlobalConstantImpl(DL, CV, *this, nullptr, 0, AliasList);
else if (MAI->hasSubsectionsViaSymbols()) {
OutStreamer->emitIntValue(0, 1);
}
if (!AliasList)
return;
for (auto &AliasPair : *AliasList) {
for (const GlobalAlias *GA : AliasPair.second)
OutStreamer->emitLabel(getSymbol(GA));
}
}
void AsmPrinter::emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
}
void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
if (Offset > 0)
OS << '+' << Offset;
else if (Offset < 0)
OS << Offset;
}
void AsmPrinter::emitNops(unsigned N) {
MCInst Nop = MF->getSubtarget().getInstrInfo()->getNop();
for (; N; --N)
EmitToStreamer(*OutStreamer, Nop);
}
MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
return OutContext.createTempSymbol(Name, true);
}
MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(
BA->getBasicBlock());
}
MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(BB);
}
MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) {
const MachineConstantPoolEntry &CPE =
MF->getConstantPool()->getConstants()[CPID];
if (!CPE.isMachineConstantPoolEntry()) {
const DataLayout &DL = MF->getDataLayout();
SectionKind Kind = CPE.getSectionKind(&DL);
const Constant *C = CPE.Val.ConstVal;
Align Alignment = CPE.Alignment;
if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
getObjFileLowering().getSectionForConstant(DL, Kind, C,
Alignment))) {
if (MCSymbol *Sym = S->getCOMDATSymbol()) {
if (Sym->isUndefined())
OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
return Sym;
}
}
}
}
const DataLayout &DL = getDataLayout();
return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
"CPI" + Twine(getFunctionNumber()) + "_" +
Twine(CPID));
}
MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
}
MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
const DataLayout &DL = getDataLayout();
return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
Twine(getFunctionNumber()) + "_" +
Twine(UID) + "_set_" + Twine(MBBID));
}
MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
StringRef Suffix) const {
return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
}
MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
SmallString<60> NameStr;
Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
return OutContext.getOrCreateSymbol(NameStr);
}
static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
unsigned FunctionNumber) {
if (!Loop) return;
PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
OS.indent(Loop->getLoopDepth()*2)
<< "Parent Loop BB" << FunctionNumber << "_"
<< Loop->getHeader()->getNumber()
<< " Depth=" << Loop->getLoopDepth() << '\n';
}
static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
unsigned FunctionNumber) {
for (const MachineLoop *CL : *Loop) {
OS.indent(CL->getLoopDepth()*2)
<< "Child Loop BB" << FunctionNumber << "_"
<< CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
<< '\n';
PrintChildLoopComment(OS, CL, FunctionNumber);
}
}
static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
const MachineLoopInfo *LI,
const AsmPrinter &AP) {
const MachineLoop *Loop = LI->getLoopFor(&MBB);
if (!Loop) return;
MachineBasicBlock *Header = Loop->getHeader();
assert(Header && "No header for loop");
if (Header != &MBB) {
AP.OutStreamer->AddComment(" in Loop: Header=BB" +
Twine(AP.getFunctionNumber())+"_" +
Twine(Loop->getHeader()->getNumber())+
" Depth="+Twine(Loop->getLoopDepth()));
return;
}
raw_ostream &OS = AP.OutStreamer->getCommentOS();
PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
OS << "=>";
OS.indent(Loop->getLoopDepth()*2-2);
OS << "This ";
if (Loop->isInnermost())
OS << "Inner ";
OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
}
void AsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) {
if (MBB.isEHFuncletEntry()) {
for (const HandlerInfo &HI : Handlers) {
HI.Handler->endFunclet();
HI.Handler->beginFunclet(MBB);
}
}
const Align Alignment = MBB.getAlignment();
if (Alignment != Align(1))
emitAlignment(Alignment, nullptr, MBB.getMaxBytesForAlignment());
if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
OutStreamer->switchSection(
getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(),
MBB, TM));
CurrentSectionBeginSym = MBB.getSymbol();
}
const BasicBlock *BB = MBB.getBasicBlock();
if (MBB.hasAddressTaken()) {
if (isVerbose())
OutStreamer->AddComment("Block address taken");
if (BB && BB->hasAddressTaken())
for (MCSymbol *Sym : getAddrLabelSymbolToEmit(BB))
OutStreamer->emitLabel(Sym);
}
if (isVerbose()) {
if (BB) {
if (BB->hasName()) {
BB->printAsOperand(OutStreamer->getCommentOS(),
false, BB->getModule());
OutStreamer->getCommentOS() << '\n';
}
}
assert(MLI != nullptr && "MachineLoopInfo should has been computed");
emitBasicBlockLoopComments(MBB, MLI, *this);
}
if (shouldEmitLabelForBasicBlock(MBB)) {
if (isVerbose() && MBB.hasLabelMustBeEmitted())
OutStreamer->AddComment("Label of block must be emitted");
OutStreamer->emitLabel(MBB.getSymbol());
} else {
if (isVerbose()) {
OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
false);
}
}
if (MBB.isEHCatchretTarget() &&
MAI->getExceptionHandlingType() == ExceptionHandling::WinEH) {
OutStreamer->emitLabel(MBB.getEHCatchretSymbol());
}
if (MBB.isBeginSection() && !MBB.isEntryBlock())
for (const HandlerInfo &HI : Handlers)
HI.Handler->beginBasicBlock(MBB);
}
void AsmPrinter::emitBasicBlockEnd(const MachineBasicBlock &MBB) {
if (MBB.isEndSection())
for (const HandlerInfo &HI : Handlers)
HI.Handler->endBasicBlock(MBB);
}
void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
bool IsDefinition) const {
MCSymbolAttr Attr = MCSA_Invalid;
switch (Visibility) {
default: break;
case GlobalValue::HiddenVisibility:
if (IsDefinition)
Attr = MAI->getHiddenVisibilityAttr();
else
Attr = MAI->getHiddenDeclarationVisibilityAttr();
break;
case GlobalValue::ProtectedVisibility:
Attr = MAI->getProtectedVisibilityAttr();
break;
}
if (Attr != MCSA_Invalid)
OutStreamer->emitSymbolAttribute(Sym, Attr);
}
bool AsmPrinter::shouldEmitLabelForBasicBlock(
const MachineBasicBlock &MBB) const {
if ((MF->hasBBLabels() || MBB.isBeginSection()) && !MBB.isEntryBlock())
return true;
return !MBB.pred_empty() &&
(!isBlockOnlyReachableByFallthrough(&MBB) || MBB.isEHFuncletEntry() ||
MBB.hasLabelMustBeEmitted());
}
bool AsmPrinter::
isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
if (MBB->isEHPad() || MBB->pred_empty())
return false;
if (MBB->pred_size() > 1)
return false;
MachineBasicBlock *Pred = *MBB->pred_begin();
if (!Pred->isLayoutSuccessor(MBB))
return false;
if (Pred->empty())
return true;
for (const auto &MI : Pred->terminators()) {
if (!MI.isBranch() || MI.isIndirectBranch())
return false;
for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
if (OP->isJTI())
return false;
if (OP->isMBB() && OP->getMBB() == MBB)
return false;
}
}
return true;
}
GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
if (!S.usesMetadata())
return nullptr;
gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
gcp_map_type::iterator GCPI = GCMap.find(&S);
if (GCPI != GCMap.end())
return GCPI->second.get();
auto Name = S.getName();
for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter :
GCMetadataPrinterRegistry::entries())
if (Name == GCMetaPrinter.getName()) {
std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
GMP->S = &S;
auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
return IterBool.first->second.get();
}
report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
}
void AsmPrinter::emitStackMaps(StackMaps &SM) {
GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
assert(MI && "AsmPrinter didn't require GCModuleInfo?");
bool NeedsDefault = false;
if (MI->begin() == MI->end())
NeedsDefault = true;
else
for (const auto &I : *MI) {
if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
if (MP->emitStackMaps(SM, *this))
continue;
NeedsDefault = true;
}
if (NeedsDefault)
SM.serializeToStackMapSection();
}
AsmPrinterHandler::~AsmPrinterHandler() = default;
void AsmPrinterHandler::markFunctionEnd() {}
void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out) const {
auto Kind8 = static_cast<uint8_t>(Kind);
Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
Out->emitBinaryData(
StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
Out->emitZeros(Padding);
}
void AsmPrinter::emitXRayTable() {
if (Sleds.empty())
return;
auto PrevSection = OutStreamer->getCurrentSectionOnly();
const Function &F = MF->getFunction();
MCSection *InstMap = nullptr;
MCSection *FnSledIndex = nullptr;
const Triple &TT = TM.getTargetTriple();
if (TT.isOSBinFormatELF()) {
auto LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
StringRef GroupName;
if (F.hasComdat()) {
Flags |= ELF::SHF_GROUP;
GroupName = F.getComdat()->getName();
}
InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
Flags, 0, GroupName, F.hasComdat(),
MCSection::NonUniqueID, LinkedToSym);
if (!TM.Options.XRayOmitFunctionIndex)
FnSledIndex = OutContext.getELFSection(
"xray_fn_idx", ELF::SHT_PROGBITS, Flags | ELF::SHF_WRITE, 0,
GroupName, F.hasComdat(), MCSection::NonUniqueID, LinkedToSym);
} else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
SectionKind::getReadOnlyWithRel());
if (!TM.Options.XRayOmitFunctionIndex)
FnSledIndex = OutContext.getMachOSection(
"__DATA", "xray_fn_idx", 0, SectionKind::getReadOnlyWithRel());
} else {
llvm_unreachable("Unsupported target");
}
auto WordSizeBytes = MAI->getCodePointerSize();
auto &Ctx = OutContext;
MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true);
OutStreamer->switchSection(InstMap);
OutStreamer->emitLabel(SledsStart);
for (const auto &Sled : Sleds) {
MCSymbol *Dot = Ctx.createTempSymbol();
OutStreamer->emitLabel(Dot);
OutStreamer->emitValueImpl(
MCBinaryExpr::createSub(MCSymbolRefExpr::create(Sled.Sled, Ctx),
MCSymbolRefExpr::create(Dot, Ctx), Ctx),
WordSizeBytes);
OutStreamer->emitValueImpl(
MCBinaryExpr::createSub(
MCSymbolRefExpr::create(CurrentFnBegin, Ctx),
MCBinaryExpr::createAdd(MCSymbolRefExpr::create(Dot, Ctx),
MCConstantExpr::create(WordSizeBytes, Ctx),
Ctx),
Ctx),
WordSizeBytes);
Sled.emit(WordSizeBytes, OutStreamer.get());
}
MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
OutStreamer->emitLabel(SledsEnd);
if (FnSledIndex) {
OutStreamer->switchSection(FnSledIndex);
OutStreamer->emitCodeAlignment(2 * WordSizeBytes, &getSubtargetInfo());
OutStreamer->emitSymbolValue(SledsStart, WordSizeBytes, false);
OutStreamer->emitSymbolValue(SledsEnd, WordSizeBytes, false);
OutStreamer->switchSection(PrevSection);
}
Sleds.clear();
}
void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI,
SledKind Kind, uint8_t Version) {
const Function &F = MI.getMF()->getFunction();
auto Attr = F.getFnAttribute("function-instrument");
bool LogArgs = F.hasFnAttribute("xray-log-args");
bool AlwaysInstrument =
Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
Kind = SledKind::LOG_ARGS_ENTER;
Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
AlwaysInstrument, &F, Version});
}
void AsmPrinter::emitPatchableFunctionEntries() {
const Function &F = MF->getFunction();
unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0;
(void)F.getFnAttribute("patchable-function-prefix")
.getValueAsString()
.getAsInteger(10, PatchableFunctionPrefix);
(void)F.getFnAttribute("patchable-function-entry")
.getValueAsString()
.getAsInteger(10, PatchableFunctionEntry);
if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
return;
const unsigned PointerSize = getPointerSize();
if (TM.getTargetTriple().isOSBinFormatELF()) {
auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
const MCSymbolELF *LinkedToSym = nullptr;
StringRef GroupName;
if (MAI->useIntegratedAssembler() || MAI->binutilsIsAtLeast(2, 36)) {
Flags |= ELF::SHF_LINK_ORDER;
if (F.hasComdat()) {
Flags |= ELF::SHF_GROUP;
GroupName = F.getComdat()->getName();
}
LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
}
OutStreamer->switchSection(OutContext.getELFSection(
"__patchable_function_entries", ELF::SHT_PROGBITS, Flags, 0, GroupName,
F.hasComdat(), MCSection::NonUniqueID, LinkedToSym));
emitAlignment(Align(PointerSize));
OutStreamer->emitSymbolValue(CurrentPatchableFunctionEntrySym, PointerSize);
}
}
uint16_t AsmPrinter::getDwarfVersion() const {
return OutStreamer->getContext().getDwarfVersion();
}
void AsmPrinter::setDwarfVersion(uint16_t Version) {
OutStreamer->getContext().setDwarfVersion(Version);
}
bool AsmPrinter::isDwarf64() const {
return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64;
}
unsigned int AsmPrinter::getDwarfOffsetByteSize() const {
return dwarf::getDwarfOffsetByteSize(
OutStreamer->getContext().getDwarfFormat());
}
dwarf::FormParams AsmPrinter::getDwarfFormParams() const {
return {getDwarfVersion(), uint8_t(getPointerSize()),
OutStreamer->getContext().getDwarfFormat(),
MAI->doesDwarfUseRelocationsAcrossSections()};
}
unsigned int AsmPrinter::getUnitLengthFieldByteSize() const {
return dwarf::getUnitLengthFieldByteSize(
OutStreamer->getContext().getDwarfFormat());
}