Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/LLVMBuild.txt | ;===- ./lib/MC/LLVMBuild.txt -----------------------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[common]
subdirectories = MCDisassembler MCParser
[component_0]
type = Library
name = MC
parent = Libraries
required_libraries = Support
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/MCLinkerOptimizationHint.cpp | //===-- llvm/MC/MCLinkerOptimizationHint.cpp ----- LOH handling -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCLinkerOptimizationHint.h"
#include "llvm/MC/MCAsmLayout.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/Support/LEB128.h"
using namespace llvm;
// Each LOH is composed by, in this order (each field is encoded using ULEB128):
// - Its kind.
// - Its number of arguments (let say N).
// - Its arg1.
// - ...
// - Its argN.
// <arg1> to <argN> are absolute addresses in the object file, i.e.,
// relative addresses from the beginning of the object file.
void MCLOHDirective::emit_impl(raw_ostream &OutStream,
const MachObjectWriter &ObjWriter,
const MCAsmLayout &Layout) const {
encodeULEB128(Kind, OutStream);
encodeULEB128(Args.size(), OutStream);
for (LOHArgs::const_iterator It = Args.begin(), EndIt = Args.end();
It != EndIt; ++It)
encodeULEB128(ObjWriter.getSymbolAddress(**It, Layout), OutStream);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/MCAsmInfo.cpp | //===-- MCAsmInfo.cpp - Asm Info -------------------------------------------==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines target asm properties related what form asm statements
// should take.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/Dwarf.h"
#include <cctype>
#include <cstring>
using namespace llvm;
MCAsmInfo::MCAsmInfo() {
PointerSize = 4;
CalleeSaveStackSlotSize = 4;
IsLittleEndian = true;
StackGrowsUp = false;
HasSubsectionsViaSymbols = false;
HasMachoZeroFillDirective = false;
HasMachoTBSSDirective = false;
HasStaticCtorDtorReferenceInStaticMode = false;
MaxInstLength = 4;
MinInstAlignment = 1;
DollarIsPC = false;
SeparatorString = ";";
CommentString = "#";
LabelSuffix = ":";
UseAssignmentForEHBegin = false;
NeedsLocalForSize = false;
PrivateGlobalPrefix = "L";
PrivateLabelPrefix = PrivateGlobalPrefix;
LinkerPrivateGlobalPrefix = "";
InlineAsmStart = "APP";
InlineAsmEnd = "NO_APP";
Code16Directive = ".code16";
Code32Directive = ".code32";
Code64Directive = ".code64";
AssemblerDialect = 0;
AllowAtInName = false;
SupportsQuotedNames = true;
UseDataRegionDirectives = false;
ZeroDirective = "\t.zero\t";
AsciiDirective = "\t.ascii\t";
AscizDirective = "\t.asciz\t";
Data8bitsDirective = "\t.byte\t";
Data16bitsDirective = "\t.short\t";
Data32bitsDirective = "\t.long\t";
Data64bitsDirective = "\t.quad\t";
SunStyleELFSectionSwitchSyntax = false;
UsesELFSectionDirectiveForBSS = false;
AlignmentIsInBytes = true;
TextAlignFillValue = 0;
GPRel64Directive = nullptr;
GPRel32Directive = nullptr;
GlobalDirective = "\t.globl\t";
SetDirectiveSuppressesReloc = false;
HasAggressiveSymbolFolding = true;
COMMDirectiveAlignmentIsInBytes = true;
LCOMMDirectiveAlignmentType = LCOMM::NoAlignment;
HasFunctionAlignment = true;
HasDotTypeDotSizeDirective = true;
HasSingleParameterDotFile = true;
HasIdentDirective = false;
HasNoDeadStrip = false;
WeakDirective = "\t.weak\t";
WeakRefDirective = nullptr;
HasWeakDefDirective = false;
HasWeakDefCanBeHiddenDirective = false;
HasLinkOnceDirective = false;
HiddenVisibilityAttr = MCSA_Hidden;
HiddenDeclarationVisibilityAttr = MCSA_Hidden;
ProtectedVisibilityAttr = MCSA_Protected;
SupportsDebugInformation = false;
ExceptionsType = ExceptionHandling::None;
WinEHEncodingType = WinEH::EncodingType::Invalid;
DwarfUsesRelocationsAcrossSections = true;
DwarfFDESymbolsUseAbsDiff = false;
DwarfRegNumForCFI = false;
NeedsDwarfSectionOffsetDirective = false;
UseParensForSymbolVariant = false;
UseLogicalShr = true;
// FIXME: Clang's logic should be synced with the logic used to initialize
// this member and the two implementations should be merged.
// For reference:
// - Solaris always enables the integrated assembler by default
// - SparcELFMCAsmInfo and X86ELFMCAsmInfo are handling this case
// - Windows always enables the integrated assembler by default
// - MCAsmInfoCOFF is handling this case, should it be MCAsmInfoMicrosoft?
// - MachO targets always enables the integrated assembler by default
// - MCAsmInfoDarwin is handling this case
// - Generic_GCC toolchains enable the integrated assembler on a per
// architecture basis.
// - The target subclasses for AArch64, ARM, and X86 handle these cases
UseIntegratedAssembler = false;
CompressDebugSections = false;
}
MCAsmInfo::~MCAsmInfo() {
}
bool MCAsmInfo::isSectionAtomizableBySymbols(const MCSection &Section) const {
return false;
}
const MCExpr *
MCAsmInfo::getExprForPersonalitySymbol(const MCSymbol *Sym,
unsigned Encoding,
MCStreamer &Streamer) const {
return getExprForFDESymbol(Sym, Encoding, Streamer);
}
const MCExpr *
MCAsmInfo::getExprForFDESymbol(const MCSymbol *Sym,
unsigned Encoding,
MCStreamer &Streamer) const {
if (!(Encoding & dwarf::DW_EH_PE_pcrel))
return MCSymbolRefExpr::create(Sym, Streamer.getContext());
MCContext &Context = Streamer.getContext();
const MCExpr *Res = MCSymbolRefExpr::create(Sym, Context);
MCSymbol *PCSym = Context.createTempSymbol();
Streamer.EmitLabel(PCSym);
const MCExpr *PC = MCSymbolRefExpr::create(PCSym, Context);
return MCBinaryExpr::createSub(Res, PC, Context);
}
static bool isAcceptableChar(char C) {
return (C >= 'a' && C <= 'z') || (C >= 'A' && C <= 'Z') ||
(C >= '0' && C <= '9') || C == '_' || C == '$' || C == '.' || C == '@';
}
bool MCAsmInfo::isValidUnquotedName(StringRef Name) const {
if (Name.empty())
return false;
// If any of the characters in the string is an unacceptable character, force
// quotes.
for (char C : Name) {
if (!isAcceptableChar(C))
return false;
}
return true;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/ConstantPools.cpp | //===- ConstantPools.cpp - ConstantPool class --*- C++ -*---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the ConstantPool and AssemblerConstantPools classes.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/MapVector.h"
#include "llvm/MC/ConstantPools.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCStreamer.h"
// //
///////////////////////////////////////////////////////////////////////////////
using namespace llvm;
//
// ConstantPool implementation
//
// Emit the contents of the constant pool using the provided streamer.
void ConstantPool::emitEntries(MCStreamer &Streamer) {
if (Entries.empty())
return;
Streamer.EmitDataRegion(MCDR_DataRegion);
for (EntryVecTy::const_iterator I = Entries.begin(), E = Entries.end();
I != E; ++I) {
Streamer.EmitCodeAlignment(I->Size); // align naturally
Streamer.EmitLabel(I->Label);
Streamer.EmitValue(I->Value, I->Size);
}
Streamer.EmitDataRegion(MCDR_DataRegionEnd);
Entries.clear();
}
const MCExpr *ConstantPool::addEntry(const MCExpr *Value, MCContext &Context,
unsigned Size) {
MCSymbol *CPEntryLabel = Context.createTempSymbol();
Entries.push_back(ConstantPoolEntry(CPEntryLabel, Value, Size));
return MCSymbolRefExpr::create(CPEntryLabel, Context);
}
bool ConstantPool::empty() { return Entries.empty(); }
//
// AssemblerConstantPools implementation
//
ConstantPool *AssemblerConstantPools::getConstantPool(MCSection *Section) {
ConstantPoolMapTy::iterator CP = ConstantPools.find(Section);
if (CP == ConstantPools.end())
return nullptr;
return &CP->second;
}
ConstantPool &
AssemblerConstantPools::getOrCreateConstantPool(MCSection *Section) {
return ConstantPools[Section];
}
static void emitConstantPool(MCStreamer &Streamer, MCSection *Section,
ConstantPool &CP) {
if (!CP.empty()) {
Streamer.SwitchSection(Section);
CP.emitEntries(Streamer);
}
}
void AssemblerConstantPools::emitAll(MCStreamer &Streamer) {
// Dump contents of assembler constant pools.
for (ConstantPoolMapTy::iterator CPI = ConstantPools.begin(),
CPE = ConstantPools.end();
CPI != CPE; ++CPI) {
MCSection *Section = CPI->first;
ConstantPool &CP = CPI->second;
emitConstantPool(Streamer, Section, CP);
}
}
void AssemblerConstantPools::emitForCurrentSection(MCStreamer &Streamer) {
MCSection *Section = Streamer.getCurrentSection().first;
if (ConstantPool *CP = getConstantPool(Section)) {
emitConstantPool(Streamer, Section, *CP);
}
}
const MCExpr *AssemblerConstantPools::addEntry(MCStreamer &Streamer,
const MCExpr *Expr,
unsigned Size) {
MCSection *Section = Streamer.getCurrentSection().first;
return getOrCreateConstantPool(Section).addEntry(Expr, Streamer.getContext(),
Size);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/MCInst.cpp | //===- lib/MC/MCInst.cpp - MCInst implementation --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
void MCOperand::print(raw_ostream &OS) const {
OS << "<MCOperand ";
if (!isValid())
OS << "INVALID";
else if (isReg())
OS << "Reg:" << getReg();
else if (isImm())
OS << "Imm:" << getImm();
else if (isExpr()) {
OS << "Expr:(" << *getExpr() << ")";
} else if (isInst()) {
OS << "Inst:(" << *getInst() << ")";
} else
OS << "UNDEFINED";
OS << ">";
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
void MCOperand::dump() const {
print(dbgs());
dbgs() << "\n";
}
#endif
void MCInst::print(raw_ostream &OS) const {
OS << "<MCInst " << getOpcode();
for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
OS << " ";
getOperand(i).print(OS);
}
OS << ">";
}
void MCInst::dump_pretty(raw_ostream &OS, const MCInstPrinter *Printer,
StringRef Separator) const {
OS << "<MCInst #" << getOpcode();
// Show the instruction opcode name if we have access to a printer.
if (Printer)
OS << ' ' << Printer->getOpcodeName(getOpcode());
for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
OS << Separator;
getOperand(i).print(OS);
}
OS << ">";
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
void MCInst::dump() const {
print(dbgs());
dbgs() << "\n";
}
#endif
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/MCStreamer.cpp | //===- lib/MC/MCStreamer.cpp - Streaming Machine Code Output --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCStreamer.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCWin64EH.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdlib>
using namespace llvm;
// Pin the vtables to this file.
MCTargetStreamer::~MCTargetStreamer() {}
MCTargetStreamer::MCTargetStreamer(MCStreamer &S) : Streamer(S) {
S.setTargetStreamer(this);
}
void MCTargetStreamer::emitLabel(MCSymbol *Symbol) {}
void MCTargetStreamer::finish() {}
void MCTargetStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {}
MCStreamer::MCStreamer(MCContext &Ctx)
: Context(Ctx), CurrentWinFrameInfo(nullptr) {
SectionStack.push_back(std::pair<MCSectionSubPair, MCSectionSubPair>());
}
MCStreamer::~MCStreamer() {
for (unsigned i = 0; i < getNumWinFrameInfos(); ++i)
delete WinFrameInfos[i];
}
void MCStreamer::reset() {
DwarfFrameInfos.clear();
for (unsigned i = 0; i < getNumWinFrameInfos(); ++i)
delete WinFrameInfos[i];
WinFrameInfos.clear();
CurrentWinFrameInfo = nullptr;
SymbolOrdering.clear();
SectionStack.clear();
SectionStack.push_back(std::pair<MCSectionSubPair, MCSectionSubPair>());
}
raw_ostream &MCStreamer::GetCommentOS() {
// By default, discard comments.
return nulls();
}
void MCStreamer::emitRawComment(const Twine &T, bool TabPrefix) {}
void MCStreamer::generateCompactUnwindEncodings(MCAsmBackend *MAB) {
for (auto &FI : DwarfFrameInfos)
FI.CompactUnwindEncoding =
(MAB ? MAB->generateCompactUnwindEncoding(FI.Instructions) : 0);
}
/// EmitIntValue - Special case of EmitValue that avoids the client having to
/// pass in a MCExpr for constant integers.
void MCStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
assert(1 <= Size && Size <= 8 && "Invalid size");
assert((isUIntN(8 * Size, Value) || isIntN(8 * Size, Value)) &&
"Invalid size");
char buf[8];
const bool isLittleEndian = Context.getAsmInfo()->isLittleEndian();
for (unsigned i = 0; i != Size; ++i) {
unsigned index = isLittleEndian ? i : (Size - i - 1);
buf[i] = uint8_t(Value >> (index * 8));
}
EmitBytes(StringRef(buf, Size));
}
/// EmitULEB128Value - Special case of EmitULEB128Value that avoids the
/// client having to pass in a MCExpr for constant integers.
void MCStreamer::EmitULEB128IntValue(uint64_t Value, unsigned Padding) {
SmallString<128> Tmp;
raw_svector_ostream OSE(Tmp);
encodeULEB128(Value, OSE, Padding);
EmitBytes(OSE.str());
}
/// EmitSLEB128Value - Special case of EmitSLEB128Value that avoids the
/// client having to pass in a MCExpr for constant integers.
void MCStreamer::EmitSLEB128IntValue(int64_t Value) {
SmallString<128> Tmp;
raw_svector_ostream OSE(Tmp);
encodeSLEB128(Value, OSE);
EmitBytes(OSE.str());
}
void MCStreamer::EmitValue(const MCExpr *Value, unsigned Size,
const SMLoc &Loc) {
EmitValueImpl(Value, Size, Loc);
}
void MCStreamer::EmitSymbolValue(const MCSymbol *Sym, unsigned Size,
bool IsSectionRelative) {
assert((!IsSectionRelative || Size == 4) &&
"SectionRelative value requires 4-bytes");
if (!IsSectionRelative)
EmitValueImpl(MCSymbolRefExpr::create(Sym, getContext()), Size);
else
EmitCOFFSecRel32(Sym);
}
void MCStreamer::EmitGPRel64Value(const MCExpr *Value) {
report_fatal_error("unsupported directive in streamer");
}
void MCStreamer::EmitGPRel32Value(const MCExpr *Value) {
report_fatal_error("unsupported directive in streamer");
}
/// EmitFill - Emit NumBytes bytes worth of the value specified by
/// FillValue. This implements directives such as '.space'.
void MCStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
const MCExpr *E = MCConstantExpr::create(FillValue, getContext());
for (uint64_t i = 0, e = NumBytes; i != e; ++i)
EmitValue(E, 1);
}
/// The implementation in this class just redirects to EmitFill.
void MCStreamer::EmitZeros(uint64_t NumBytes) {
EmitFill(NumBytes, 0);
}
unsigned MCStreamer::EmitDwarfFileDirective(unsigned FileNo,
StringRef Directory,
StringRef Filename, unsigned CUID) {
return getContext().getDwarfFile(Directory, Filename, FileNo, CUID);
}
void MCStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
unsigned Column, unsigned Flags,
unsigned Isa,
unsigned Discriminator,
StringRef FileName) {
getContext().setCurrentDwarfLoc(FileNo, Line, Column, Flags, Isa,
Discriminator);
}
MCSymbol *MCStreamer::getDwarfLineTableSymbol(unsigned CUID) {
MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
if (!Table.getLabel()) {
StringRef Prefix = Context.getAsmInfo()->getPrivateGlobalPrefix();
Table.setLabel(
Context.getOrCreateSymbol(Prefix + "line_table_start" + Twine(CUID)));
}
return Table.getLabel();
}
MCDwarfFrameInfo *MCStreamer::getCurrentDwarfFrameInfo() {
if (DwarfFrameInfos.empty())
return nullptr;
return &DwarfFrameInfos.back();
}
void MCStreamer::EnsureValidDwarfFrame() {
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
if (!CurFrame || CurFrame->End)
report_fatal_error("No open frame");
}
void MCStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
MCSymbol *EHSymbol) {
}
void MCStreamer::InitSections(bool NoExecStack) {
SwitchSection(getContext().getObjectFileInfo()->getTextSection());
}
void MCStreamer::AssignSection(MCSymbol *Symbol, MCSection *Section) {
if (Section)
Symbol->setSection(*Section);
else
Symbol->setUndefined();
// As we emit symbols into a section, track the order so that they can
// be sorted upon later. Zero is reserved to mean 'unemitted'.
SymbolOrdering[Symbol] = 1 + SymbolOrdering.size();
}
void MCStreamer::EmitLabel(MCSymbol *Symbol) {
assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
assert(getCurrentSection().first && "Cannot emit before setting section!");
AssignSection(Symbol, getCurrentSection().first);
MCTargetStreamer *TS = getTargetStreamer();
if (TS)
TS->emitLabel(Symbol);
}
void MCStreamer::EmitCFISections(bool EH, bool Debug) {
assert(EH || Debug);
}
void MCStreamer::EmitCFIStartProc(bool IsSimple) {
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
if (CurFrame && !CurFrame->End)
report_fatal_error("Starting a frame before finishing the previous one!");
MCDwarfFrameInfo Frame;
Frame.IsSimple = IsSimple;
EmitCFIStartProcImpl(Frame);
const MCAsmInfo* MAI = Context.getAsmInfo();
if (MAI) {
for (const MCCFIInstruction& Inst : MAI->getInitialFrameState()) {
if (Inst.getOperation() == MCCFIInstruction::OpDefCfa ||
Inst.getOperation() == MCCFIInstruction::OpDefCfaRegister) {
Frame.CurrentCfaRegister = Inst.getRegister();
}
}
}
DwarfFrameInfos.push_back(Frame);
}
void MCStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
}
void MCStreamer::EmitCFIEndProc() {
EnsureValidDwarfFrame();
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
EmitCFIEndProcImpl(*CurFrame);
}
void MCStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
// Put a dummy non-null value in Frame.End to mark that this frame has been
// closed.
Frame.End = (MCSymbol *) 1;
}
MCSymbol *MCStreamer::EmitCFICommon() {
EnsureValidDwarfFrame();
MCSymbol *Label = getContext().createTempSymbol();
EmitLabel(Label);
return Label;
}
void MCStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
MCSymbol *Label = EmitCFICommon();
MCCFIInstruction Instruction =
MCCFIInstruction::createDefCfa(Label, Register, Offset);
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->Instructions.push_back(Instruction);
CurFrame->CurrentCfaRegister = static_cast<unsigned>(Register);
}
void MCStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
MCSymbol *Label = EmitCFICommon();
MCCFIInstruction Instruction =
MCCFIInstruction::createDefCfaOffset(Label, Offset);
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->Instructions.push_back(Instruction);
}
void MCStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
MCSymbol *Label = EmitCFICommon();
MCCFIInstruction Instruction =
MCCFIInstruction::createAdjustCfaOffset(Label, Adjustment);
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->Instructions.push_back(Instruction);
}
void MCStreamer::EmitCFIDefCfaRegister(int64_t Register) {
MCSymbol *Label = EmitCFICommon();
MCCFIInstruction Instruction =
MCCFIInstruction::createDefCfaRegister(Label, Register);
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->Instructions.push_back(Instruction);
CurFrame->CurrentCfaRegister = static_cast<unsigned>(Register);
}
void MCStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
MCSymbol *Label = EmitCFICommon();
MCCFIInstruction Instruction =
MCCFIInstruction::createOffset(Label, Register, Offset);
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->Instructions.push_back(Instruction);
}
void MCStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
MCSymbol *Label = EmitCFICommon();
MCCFIInstruction Instruction =
MCCFIInstruction::createRelOffset(Label, Register, Offset);
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->Instructions.push_back(Instruction);
}
void MCStreamer::EmitCFIPersonality(const MCSymbol *Sym,
unsigned Encoding) {
EnsureValidDwarfFrame();
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->Personality = Sym;
CurFrame->PersonalityEncoding = Encoding;
}
void MCStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
EnsureValidDwarfFrame();
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->Lsda = Sym;
CurFrame->LsdaEncoding = Encoding;
}
void MCStreamer::EmitCFIRememberState() {
MCSymbol *Label = EmitCFICommon();
MCCFIInstruction Instruction = MCCFIInstruction::createRememberState(Label);
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->Instructions.push_back(Instruction);
}
void MCStreamer::EmitCFIRestoreState() {
// FIXME: Error if there is no matching cfi_remember_state.
MCSymbol *Label = EmitCFICommon();
MCCFIInstruction Instruction = MCCFIInstruction::createRestoreState(Label);
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->Instructions.push_back(Instruction);
}
void MCStreamer::EmitCFISameValue(int64_t Register) {
MCSymbol *Label = EmitCFICommon();
MCCFIInstruction Instruction =
MCCFIInstruction::createSameValue(Label, Register);
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->Instructions.push_back(Instruction);
}
void MCStreamer::EmitCFIRestore(int64_t Register) {
MCSymbol *Label = EmitCFICommon();
MCCFIInstruction Instruction =
MCCFIInstruction::createRestore(Label, Register);
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->Instructions.push_back(Instruction);
}
void MCStreamer::EmitCFIEscape(StringRef Values) {
MCSymbol *Label = EmitCFICommon();
MCCFIInstruction Instruction = MCCFIInstruction::createEscape(Label, Values);
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->Instructions.push_back(Instruction);
}
void MCStreamer::EmitCFISignalFrame() {
EnsureValidDwarfFrame();
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->IsSignalFrame = true;
}
void MCStreamer::EmitCFIUndefined(int64_t Register) {
MCSymbol *Label = EmitCFICommon();
MCCFIInstruction Instruction =
MCCFIInstruction::createUndefined(Label, Register);
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->Instructions.push_back(Instruction);
}
void MCStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
MCSymbol *Label = EmitCFICommon();
MCCFIInstruction Instruction =
MCCFIInstruction::createRegister(Label, Register1, Register2);
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->Instructions.push_back(Instruction);
}
void MCStreamer::EmitCFIWindowSave() {
MCSymbol *Label = EmitCFICommon();
MCCFIInstruction Instruction =
MCCFIInstruction::createWindowSave(Label);
MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
CurFrame->Instructions.push_back(Instruction);
}
void MCStreamer::EnsureValidWinFrameInfo() {
const MCAsmInfo *MAI = Context.getAsmInfo();
if (!MAI->usesWindowsCFI())
report_fatal_error(".seh_* directives are not supported on this target");
if (!CurrentWinFrameInfo || CurrentWinFrameInfo->End)
report_fatal_error("No open Win64 EH frame function!");
}
void MCStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol) {
const MCAsmInfo *MAI = Context.getAsmInfo();
if (!MAI->usesWindowsCFI())
report_fatal_error(".seh_* directives are not supported on this target");
if (CurrentWinFrameInfo && !CurrentWinFrameInfo->End)
report_fatal_error("Starting a function before ending the previous one!");
MCSymbol *StartProc = getContext().createTempSymbol();
EmitLabel(StartProc);
WinFrameInfos.push_back(new WinEH::FrameInfo(Symbol, StartProc));
CurrentWinFrameInfo = WinFrameInfos.back();
}
void MCStreamer::EmitWinCFIEndProc() {
EnsureValidWinFrameInfo();
if (CurrentWinFrameInfo->ChainedParent)
report_fatal_error("Not all chained regions terminated!");
MCSymbol *Label = getContext().createTempSymbol();
EmitLabel(Label);
CurrentWinFrameInfo->End = Label;
}
void MCStreamer::EmitWinCFIStartChained() {
EnsureValidWinFrameInfo();
MCSymbol *StartProc = getContext().createTempSymbol();
EmitLabel(StartProc);
WinFrameInfos.push_back(new WinEH::FrameInfo(CurrentWinFrameInfo->Function,
StartProc, CurrentWinFrameInfo));
CurrentWinFrameInfo = WinFrameInfos.back();
}
void MCStreamer::EmitWinCFIEndChained() {
EnsureValidWinFrameInfo();
if (!CurrentWinFrameInfo->ChainedParent)
report_fatal_error("End of a chained region outside a chained region!");
MCSymbol *Label = getContext().createTempSymbol();
EmitLabel(Label);
CurrentWinFrameInfo->End = Label;
CurrentWinFrameInfo =
const_cast<WinEH::FrameInfo *>(CurrentWinFrameInfo->ChainedParent);
}
void MCStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind,
bool Except) {
EnsureValidWinFrameInfo();
if (CurrentWinFrameInfo->ChainedParent)
report_fatal_error("Chained unwind areas can't have handlers!");
CurrentWinFrameInfo->ExceptionHandler = Sym;
if (!Except && !Unwind)
report_fatal_error("Don't know what kind of handler this is!");
if (Unwind)
CurrentWinFrameInfo->HandlesUnwind = true;
if (Except)
CurrentWinFrameInfo->HandlesExceptions = true;
}
void MCStreamer::EmitWinEHHandlerData() {
EnsureValidWinFrameInfo();
if (CurrentWinFrameInfo->ChainedParent)
report_fatal_error("Chained unwind areas can't have handlers!");
}
void MCStreamer::EmitWinCFIPushReg(unsigned Register) {
EnsureValidWinFrameInfo();
MCSymbol *Label = getContext().createTempSymbol();
EmitLabel(Label);
WinEH::Instruction Inst = Win64EH::Instruction::PushNonVol(Label, Register);
CurrentWinFrameInfo->Instructions.push_back(Inst);
}
void MCStreamer::EmitWinCFISetFrame(unsigned Register, unsigned Offset) {
EnsureValidWinFrameInfo();
if (CurrentWinFrameInfo->LastFrameInst >= 0)
report_fatal_error("Frame register and offset already specified!");
if (Offset & 0x0F)
report_fatal_error("Misaligned frame pointer offset!");
if (Offset > 240)
report_fatal_error("Frame offset must be less than or equal to 240!");
MCSymbol *Label = getContext().createTempSymbol();
EmitLabel(Label);
WinEH::Instruction Inst =
Win64EH::Instruction::SetFPReg(Label, Register, Offset);
CurrentWinFrameInfo->LastFrameInst = CurrentWinFrameInfo->Instructions.size();
CurrentWinFrameInfo->Instructions.push_back(Inst);
}
void MCStreamer::EmitWinCFIAllocStack(unsigned Size) {
EnsureValidWinFrameInfo();
if (Size == 0)
report_fatal_error("Allocation size must be non-zero!");
if (Size & 7)
report_fatal_error("Misaligned stack allocation!");
MCSymbol *Label = getContext().createTempSymbol();
EmitLabel(Label);
WinEH::Instruction Inst = Win64EH::Instruction::Alloc(Label, Size);
CurrentWinFrameInfo->Instructions.push_back(Inst);
}
void MCStreamer::EmitWinCFISaveReg(unsigned Register, unsigned Offset) {
EnsureValidWinFrameInfo();
if (Offset & 7)
report_fatal_error("Misaligned saved register offset!");
MCSymbol *Label = getContext().createTempSymbol();
EmitLabel(Label);
WinEH::Instruction Inst =
Win64EH::Instruction::SaveNonVol(Label, Register, Offset);
CurrentWinFrameInfo->Instructions.push_back(Inst);
}
void MCStreamer::EmitWinCFISaveXMM(unsigned Register, unsigned Offset) {
EnsureValidWinFrameInfo();
if (Offset & 0x0F)
report_fatal_error("Misaligned saved vector register offset!");
MCSymbol *Label = getContext().createTempSymbol();
EmitLabel(Label);
WinEH::Instruction Inst =
Win64EH::Instruction::SaveXMM(Label, Register, Offset);
CurrentWinFrameInfo->Instructions.push_back(Inst);
}
void MCStreamer::EmitWinCFIPushFrame(bool Code) {
EnsureValidWinFrameInfo();
if (CurrentWinFrameInfo->Instructions.size() > 0)
report_fatal_error("If present, PushMachFrame must be the first UOP");
MCSymbol *Label = getContext().createTempSymbol();
EmitLabel(Label);
WinEH::Instruction Inst = Win64EH::Instruction::PushMachFrame(Label, Code);
CurrentWinFrameInfo->Instructions.push_back(Inst);
}
void MCStreamer::EmitWinCFIEndProlog() {
EnsureValidWinFrameInfo();
MCSymbol *Label = getContext().createTempSymbol();
EmitLabel(Label);
CurrentWinFrameInfo->PrologEnd = Label;
}
void MCStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
}
void MCStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
}
void MCStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) {
}
/// EmitRawText - If this file is backed by an assembly streamer, this dumps
/// the specified string in the output .s file. This capability is
/// indicated by the hasRawTextSupport() predicate.
void MCStreamer::EmitRawTextImpl(StringRef String) {
errs() << "EmitRawText called on an MCStreamer that doesn't support it, "
" something must not be fully mc'ized\n";
abort();
}
void MCStreamer::EmitRawText(const Twine &T) {
SmallString<128> Str;
EmitRawTextImpl(T.toStringRef(Str));
}
void MCStreamer::EmitWindowsUnwindTables() {
}
void MCStreamer::Finish() {
if (!DwarfFrameInfos.empty() && !DwarfFrameInfos.back().End)
report_fatal_error("Unfinished frame!");
MCTargetStreamer *TS = getTargetStreamer();
if (TS)
TS->finish();
FinishImpl();
}
void MCStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
visitUsedExpr(*Value);
Symbol->setVariableValue(Value);
MCTargetStreamer *TS = getTargetStreamer();
if (TS)
TS->emitAssignment(Symbol, Value);
}
void MCTargetStreamer::prettyPrintAsm(MCInstPrinter &InstPrinter, raw_ostream &OS,
const MCInst &Inst, const MCSubtargetInfo &STI) {
InstPrinter.printInst(&Inst, OS, "", STI);
}
void MCStreamer::visitUsedSymbol(const MCSymbol &Sym) {
}
void MCStreamer::visitUsedExpr(const MCExpr &Expr) {
switch (Expr.getKind()) {
case MCExpr::Target:
cast<MCTargetExpr>(Expr).visitUsedExpr(*this);
break;
case MCExpr::Constant:
break;
case MCExpr::Binary: {
const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
visitUsedExpr(*BE.getLHS());
visitUsedExpr(*BE.getRHS());
break;
}
case MCExpr::SymbolRef:
visitUsedSymbol(cast<MCSymbolRefExpr>(Expr).getSymbol());
break;
case MCExpr::Unary:
visitUsedExpr(*cast<MCUnaryExpr>(Expr).getSubExpr());
break;
}
}
void MCStreamer::EmitInstruction(const MCInst &Inst,
const MCSubtargetInfo &STI) {
// Scan for values.
for (unsigned i = Inst.getNumOperands(); i--;)
if (Inst.getOperand(i).isExpr())
visitUsedExpr(*Inst.getOperand(i).getExpr());
}
void MCStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo,
unsigned Size) {
// Get the Hi-Lo expression.
const MCExpr *Diff =
MCBinaryExpr::createSub(MCSymbolRefExpr::create(Hi, Context),
MCSymbolRefExpr::create(Lo, Context), Context);
const MCAsmInfo *MAI = Context.getAsmInfo();
if (!MAI->doesSetDirectiveSuppressesReloc()) {
EmitValue(Diff, Size);
return;
}
// Otherwise, emit with .set (aka assignment).
MCSymbol *SetLabel = Context.createTempSymbol("set", true);
EmitAssignment(SetLabel, Diff);
EmitSymbolValue(SetLabel, Size);
}
void MCStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {}
void MCStreamer::EmitThumbFunc(MCSymbol *Func) {}
void MCStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
void MCStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
void MCStreamer::EndCOFFSymbolDef() {}
void MCStreamer::EmitFileDirective(StringRef Filename) {}
void MCStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {}
void MCStreamer::EmitCOFFSymbolType(int Type) {}
void MCStreamer::emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value) {}
void MCStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
unsigned ByteAlignment) {}
void MCStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
uint64_t Size, unsigned ByteAlignment) {}
void MCStreamer::ChangeSection(MCSection *, const MCExpr *) {}
void MCStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
void MCStreamer::EmitBytes(StringRef Data) {}
void MCStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
const SMLoc &Loc) {
visitUsedExpr(*Value);
}
void MCStreamer::EmitULEB128Value(const MCExpr *Value) {}
void MCStreamer::EmitSLEB128Value(const MCExpr *Value) {}
void MCStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
unsigned ValueSize,
unsigned MaxBytesToEmit) {}
void MCStreamer::EmitCodeAlignment(unsigned ByteAlignment,
unsigned MaxBytesToEmit) {}
bool MCStreamer::EmitValueToOffset(const MCExpr *Offset, unsigned char Value) {
return false;
}
void MCStreamer::EmitBundleAlignMode(unsigned AlignPow2) {}
void MCStreamer::EmitBundleLock(bool AlignToEnd) {}
void MCStreamer::FinishImpl() {}
void MCStreamer::EmitBundleUnlock() {}
void MCStreamer::SwitchSection(MCSection *Section, const MCExpr *Subsection) {
assert(Section && "Cannot switch to a null section!");
MCSectionSubPair curSection = SectionStack.back().first;
SectionStack.back().second = curSection;
if (MCSectionSubPair(Section, Subsection) != curSection) {
ChangeSection(Section, Subsection);
SectionStack.back().first = MCSectionSubPair(Section, Subsection);
assert(!Section->hasEnded() && "Section already ended");
MCSymbol *Sym = Section->getBeginSymbol();
if (Sym && !Sym->isInSection())
EmitLabel(Sym);
}
}
MCSymbol *MCStreamer::endSection(MCSection *Section) {
// TODO: keep track of the last subsection so that this symbol appears in the
// correct place.
MCSymbol *Sym = Section->getEndSymbol(Context);
if (Sym->isInSection())
return Sym;
SwitchSection(Section);
EmitLabel(Sym);
return Sym;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/MCSectionELF.cpp | //===- lib/MC/MCSectionELF.cpp - ELF Code Section Representation ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
MCSectionELF::~MCSectionELF() {} // anchor.
// Decides whether a '.section' directive
// should be printed before the section name.
bool MCSectionELF::ShouldOmitSectionDirective(StringRef Name,
const MCAsmInfo &MAI) const {
if (isUnique())
return false;
// FIXME: Does .section .bss/.data/.text work everywhere??
if (Name == ".text" || Name == ".data" ||
(Name == ".bss" && !MAI.usesELFSectionDirectiveForBSS()))
return true;
return false;
}
static void printName(raw_ostream &OS, StringRef Name) {
if (Name.find_first_not_of("0123456789_."
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ") == Name.npos) {
OS << Name;
return;
}
OS << '"';
for (const char *B = Name.begin(), *E = Name.end(); B < E; ++B) {
if (*B == '"') // Unquoted "
OS << "\\\"";
else if (*B != '\\') // Neither " or backslash
OS << *B;
else if (B + 1 == E) // Trailing backslash
OS << "\\\\";
else {
OS << B[0] << B[1]; // Quoted character
++B;
}
}
OS << '"';
}
void MCSectionELF::PrintSwitchToSection(const MCAsmInfo &MAI,
raw_ostream &OS,
const MCExpr *Subsection) const {
if (ShouldOmitSectionDirective(SectionName, MAI)) {
OS << '\t' << getSectionName();
if (Subsection) {
OS << '\t';
Subsection->print(OS, &MAI);
}
OS << '\n';
return;
}
OS << "\t.section\t";
printName(OS, getSectionName());
// Handle the weird solaris syntax if desired.
if (MAI.usesSunStyleELFSectionSwitchSyntax() &&
!(Flags & ELF::SHF_MERGE)) {
if (Flags & ELF::SHF_ALLOC)
OS << ",#alloc";
if (Flags & ELF::SHF_EXECINSTR)
OS << ",#execinstr";
if (Flags & ELF::SHF_WRITE)
OS << ",#write";
if (Flags & ELF::SHF_EXCLUDE)
OS << ",#exclude";
if (Flags & ELF::SHF_TLS)
OS << ",#tls";
OS << '\n';
return;
}
OS << ",\"";
if (Flags & ELF::SHF_ALLOC)
OS << 'a';
if (Flags & ELF::SHF_EXCLUDE)
OS << 'e';
if (Flags & ELF::SHF_EXECINSTR)
OS << 'x';
if (Flags & ELF::SHF_GROUP)
OS << 'G';
if (Flags & ELF::SHF_WRITE)
OS << 'w';
if (Flags & ELF::SHF_MERGE)
OS << 'M';
if (Flags & ELF::SHF_STRINGS)
OS << 'S';
if (Flags & ELF::SHF_TLS)
OS << 'T';
// If there are target-specific flags, print them.
if (Flags & ELF::XCORE_SHF_CP_SECTION)
OS << 'c';
if (Flags & ELF::XCORE_SHF_DP_SECTION)
OS << 'd';
OS << '"';
OS << ',';
// If comment string is '@', e.g. as on ARM - use '%' instead
if (MAI.getCommentString()[0] == '@')
OS << '%';
else
OS << '@';
if (Type == ELF::SHT_INIT_ARRAY)
OS << "init_array";
else if (Type == ELF::SHT_FINI_ARRAY)
OS << "fini_array";
else if (Type == ELF::SHT_PREINIT_ARRAY)
OS << "preinit_array";
else if (Type == ELF::SHT_NOBITS)
OS << "nobits";
else if (Type == ELF::SHT_NOTE)
OS << "note";
else if (Type == ELF::SHT_PROGBITS)
OS << "progbits";
if (EntrySize) {
assert(Flags & ELF::SHF_MERGE);
OS << "," << EntrySize;
}
if (Flags & ELF::SHF_GROUP) {
OS << ",";
printName(OS, Group->getName());
OS << ",comdat";
}
if (isUnique())
OS << ",unique," << UniqueID;
OS << '\n';
if (Subsection) {
OS << "\t.subsection\t";
Subsection->print(OS, &MAI);
OS << '\n';
}
}
bool MCSectionELF::UseCodeAlign() const {
return getFlags() & ELF::SHF_EXECINSTR;
}
bool MCSectionELF::isVirtualSection() const {
return getType() == ELF::SHT_NOBITS;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/MCSection.cpp | //===- lib/MC/MCSection.cpp - Machine Code Section Representation ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// MCSection
//===----------------------------------------------------------------------===//
MCSection::MCSection(SectionVariant V, SectionKind K, MCSymbol *Begin)
: Begin(Begin), BundleGroupBeforeFirstInst(false), HasInstructions(false),
IsRegistered(false), Variant(V), Kind(K) {}
MCSymbol *MCSection::getEndSymbol(MCContext &Ctx) {
if (!End)
End = Ctx.createTempSymbol("sec_end", true);
return End;
}
bool MCSection::hasEnded() const { return End && End->isInSection(); }
MCSection::~MCSection() {
}
void MCSection::setBundleLockState(BundleLockStateType NewState) {
if (NewState == NotBundleLocked) {
if (BundleLockNestingDepth == 0) {
report_fatal_error("Mismatched bundle_lock/unlock directives");
}
if (--BundleLockNestingDepth == 0) {
BundleLockState = NotBundleLocked;
}
return;
}
// If any of the directives is an align_to_end directive, the whole nested
// group is align_to_end. So don't downgrade from align_to_end to just locked.
if (BundleLockState != BundleLockedAlignToEnd) {
BundleLockState = NewState;
}
++BundleLockNestingDepth;
}
MCSection::iterator
MCSection::getSubsectionInsertionPoint(unsigned Subsection) {
if (Subsection == 0 && SubsectionFragmentMap.empty())
return end();
SmallVectorImpl<std::pair<unsigned, MCFragment *>>::iterator MI =
std::lower_bound(SubsectionFragmentMap.begin(),
SubsectionFragmentMap.end(),
std::make_pair(Subsection, (MCFragment *)nullptr));
bool ExactMatch = false;
if (MI != SubsectionFragmentMap.end()) {
ExactMatch = MI->first == Subsection;
if (ExactMatch)
++MI;
}
iterator IP;
if (MI == SubsectionFragmentMap.end())
IP = end();
else
IP = MI->second;
if (!ExactMatch && Subsection != 0) {
// The GNU as documentation claims that subsections have an alignment of 4,
// although this appears not to be the case.
MCFragment *F = new MCDataFragment();
SubsectionFragmentMap.insert(MI, std::make_pair(Subsection, F));
getFragmentList().insert(IP, F);
F->setParent(this);
}
return IP;
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
void MCSection::dump() {
raw_ostream &OS = llvm::errs();
OS << "<MCSection";
OS << " Fragments:[\n ";
for (auto it = begin(), ie = end(); it != ie; ++it) {
if (it != begin())
OS << ",\n ";
it->dump();
}
OS << "]>";
}
#endif
MCSection::iterator MCSection::begin() { return Fragments.begin(); }
MCSection::iterator MCSection::end() { return Fragments.end(); }
MCSection::reverse_iterator MCSection::rbegin() { return Fragments.rbegin(); }
MCSection::reverse_iterator MCSection::rend() { return Fragments.rend(); }
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/MCSubtargetInfo.cpp | //===-- MCSubtargetInfo.cpp - Subtarget Information -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Triple.h"
#include "llvm/MC/MCInstrItineraries.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace llvm;
static FeatureBitset getFeatures(StringRef CPU, StringRef FS,
ArrayRef<SubtargetFeatureKV> ProcDesc,
ArrayRef<SubtargetFeatureKV> ProcFeatures) {
SubtargetFeatures Features(FS);
return Features.getFeatureBits(CPU, ProcDesc, ProcFeatures);
}
void MCSubtargetInfo::InitMCProcessorInfo(StringRef CPU, StringRef FS) {
FeatureBits = getFeatures(CPU, FS, ProcDesc, ProcFeatures);
if (!CPU.empty())
CPUSchedModel = &getSchedModelForCPU(CPU);
else
CPUSchedModel = &MCSchedModel::GetDefaultSchedModel();
}
void MCSubtargetInfo::setDefaultFeatures(StringRef CPU) {
FeatureBits = getFeatures(CPU, "", ProcDesc, ProcFeatures);
}
MCSubtargetInfo::MCSubtargetInfo(
const Triple &TT, StringRef C, StringRef FS,
ArrayRef<SubtargetFeatureKV> PF, ArrayRef<SubtargetFeatureKV> PD,
const SubtargetInfoKV *ProcSched, const MCWriteProcResEntry *WPR,
const MCWriteLatencyEntry *WL, const MCReadAdvanceEntry *RA,
const InstrStage *IS, const unsigned *OC, const unsigned *FP)
: TargetTriple(TT), CPU(C), ProcFeatures(PF), ProcDesc(PD),
ProcSchedModels(ProcSched), WriteProcResTable(WPR), WriteLatencyTable(WL),
ReadAdvanceTable(RA), Stages(IS), OperandCycles(OC), ForwardingPaths(FP) {
InitMCProcessorInfo(CPU, FS);
}
/// ToggleFeature - Toggle a feature and returns the re-computed feature
/// bits. This version does not change the implied bits.
FeatureBitset MCSubtargetInfo::ToggleFeature(uint64_t FB) {
FeatureBits.flip(FB);
return FeatureBits;
}
FeatureBitset MCSubtargetInfo::ToggleFeature(const FeatureBitset &FB) {
FeatureBits ^= FB;
return FeatureBits;
}
/// ToggleFeature - Toggle a feature and returns the re-computed feature
/// bits. This version will also change all implied bits.
FeatureBitset MCSubtargetInfo::ToggleFeature(StringRef FS) {
SubtargetFeatures Features;
FeatureBits = Features.ToggleFeature(FeatureBits, FS, ProcFeatures);
return FeatureBits;
}
FeatureBitset MCSubtargetInfo::ApplyFeatureFlag(StringRef FS) {
SubtargetFeatures Features;
FeatureBits = Features.ApplyFeatureFlag(FeatureBits, FS, ProcFeatures);
return FeatureBits;
}
const MCSchedModel &MCSubtargetInfo::getSchedModelForCPU(StringRef CPU) const {
assert(ProcSchedModels && "Processor machine model not available!");
unsigned NumProcs = ProcDesc.size();
#ifndef NDEBUG
for (size_t i = 1; i < NumProcs; i++) {
assert(strcmp(ProcSchedModels[i - 1].Key, ProcSchedModels[i].Key) < 0 &&
"Processor machine model table is not sorted");
}
#endif
// Find entry
const SubtargetInfoKV *Found =
std::lower_bound(ProcSchedModels, ProcSchedModels+NumProcs, CPU);
if (Found == ProcSchedModels+NumProcs || StringRef(Found->Key) != CPU) {
if (CPU != "help") // Don't error if the user asked for help.
errs() << "'" << CPU
<< "' is not a recognized processor for this target"
<< " (ignoring processor)\n";
return MCSchedModel::GetDefaultSchedModel();
}
assert(Found->Value && "Missing processor SchedModel value");
return *(const MCSchedModel *)Found->Value;
}
InstrItineraryData
MCSubtargetInfo::getInstrItineraryForCPU(StringRef CPU) const {
const MCSchedModel SchedModel = getSchedModelForCPU(CPU);
return InstrItineraryData(SchedModel, Stages, OperandCycles, ForwardingPaths);
}
/// Initialize an InstrItineraryData instance.
void MCSubtargetInfo::initInstrItins(InstrItineraryData &InstrItins) const {
InstrItins = InstrItineraryData(getSchedModel(), Stages, OperandCycles,
ForwardingPaths);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/MCRegisterInfo.cpp | //=== MC/MCRegisterInfo.cpp - Target Register Description -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements MCRegisterInfo functions.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCRegisterInfo.h"
using namespace llvm;
unsigned MCRegisterInfo::getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
const MCRegisterClass *RC) const {
for (MCSuperRegIterator Supers(Reg, this); Supers.isValid(); ++Supers)
if (RC->contains(*Supers) && Reg == getSubReg(*Supers, SubIdx))
return *Supers;
return 0;
}
unsigned MCRegisterInfo::getSubReg(unsigned Reg, unsigned Idx) const {
assert(Idx && Idx < getNumSubRegIndices() &&
"This is not a subregister index");
// Get a pointer to the corresponding SubRegIndices list. This list has the
// name of each sub-register in the same order as MCSubRegIterator.
const uint16_t *SRI = SubRegIndices + get(Reg).SubRegIndices;
for (MCSubRegIterator Subs(Reg, this); Subs.isValid(); ++Subs, ++SRI)
if (*SRI == Idx)
return *Subs;
return 0;
}
unsigned MCRegisterInfo::getSubRegIndex(unsigned Reg, unsigned SubReg) const {
assert(SubReg && SubReg < getNumRegs() && "This is not a register");
// Get a pointer to the corresponding SubRegIndices list. This list has the
// name of each sub-register in the same order as MCSubRegIterator.
const uint16_t *SRI = SubRegIndices + get(Reg).SubRegIndices;
for (MCSubRegIterator Subs(Reg, this); Subs.isValid(); ++Subs, ++SRI)
if (*Subs == SubReg)
return *SRI;
return 0;
}
unsigned MCRegisterInfo::getSubRegIdxSize(unsigned Idx) const {
assert(Idx && Idx < getNumSubRegIndices() &&
"This is not a subregister index");
return SubRegIdxRanges[Idx].Size;
}
unsigned MCRegisterInfo::getSubRegIdxOffset(unsigned Idx) const {
assert(Idx && Idx < getNumSubRegIndices() &&
"This is not a subregister index");
return SubRegIdxRanges[Idx].Offset;
}
int MCRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
const DwarfLLVMRegPair *M = isEH ? EHL2DwarfRegs : L2DwarfRegs;
unsigned Size = isEH ? EHL2DwarfRegsSize : L2DwarfRegsSize;
DwarfLLVMRegPair Key = { RegNum, 0 };
const DwarfLLVMRegPair *I = std::lower_bound(M, M+Size, Key);
if (I == M+Size || I->FromReg != RegNum)
return -1;
return I->ToReg;
}
int MCRegisterInfo::getLLVMRegNum(unsigned RegNum, bool isEH) const {
const DwarfLLVMRegPair *M = isEH ? EHDwarf2LRegs : Dwarf2LRegs;
unsigned Size = isEH ? EHDwarf2LRegsSize : Dwarf2LRegsSize;
DwarfLLVMRegPair Key = { RegNum, 0 };
const DwarfLLVMRegPair *I = std::lower_bound(M, M+Size, Key);
assert(I != M+Size && I->FromReg == RegNum && "Invalid RegNum");
return I->ToReg;
}
int MCRegisterInfo::getSEHRegNum(unsigned RegNum) const {
const DenseMap<unsigned, int>::const_iterator I = L2SEHRegs.find(RegNum);
if (I == L2SEHRegs.end()) return (int)RegNum;
return I->second;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/ELFObjectWriter.cpp | //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements ELF object file writer information.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCELFObjectWriter.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCAsmLayout.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCFixupKindInfo.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCSymbolELF.h"
#include "llvm/MC/MCValue.h"
#include "llvm/MC/StringTableBuilder.h"
#include "llvm/Support/Compression.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorHandling.h"
#include <vector>
using namespace llvm;
#undef DEBUG_TYPE
#define DEBUG_TYPE "reloc-info"
namespace {
typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
class ELFObjectWriter;
class SymbolTableWriter {
ELFObjectWriter &EWriter;
bool Is64Bit;
// indexes we are going to write to .symtab_shndx.
std::vector<uint32_t> ShndxIndexes;
// The numbel of symbols written so far.
unsigned NumWritten;
void createSymtabShndx();
template <typename T> void write(T Value);
public:
SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit);
void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
uint8_t other, uint32_t shndx, bool Reserved);
ArrayRef<uint32_t> getShndxIndexes() const { return ShndxIndexes; }
};
class ELFObjectWriter : public MCObjectWriter {
static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
static uint64_t SymbolValue(const MCSymbol &Sym, const MCAsmLayout &Layout);
static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
bool Used, bool Renamed);
/// Helper struct for containing some precomputed information on symbols.
struct ELFSymbolData {
const MCSymbolELF *Symbol;
uint32_t SectionIndex;
StringRef Name;
// Support lexicographic sorting.
bool operator<(const ELFSymbolData &RHS) const {
unsigned LHSType = Symbol->getType();
unsigned RHSType = RHS.Symbol->getType();
if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
return false;
if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
return true;
if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
return SectionIndex < RHS.SectionIndex;
return Name < RHS.Name;
}
};
/// The target specific ELF writer instance.
std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
DenseMap<const MCSymbolELF *, const MCSymbolELF *> Renames;
llvm::DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>>
Relocations;
/// @}
/// @name Symbol Table Data
/// @{
StringTableBuilder StrTabBuilder;
/// @}
// This holds the symbol table index of the last local symbol.
unsigned LastLocalSymbolIndex;
// This holds the .strtab section index.
unsigned StringTableIndex;
// This holds the .symtab section index.
unsigned SymbolTableIndex;
// Sections in the order they are to be output in the section table.
std::vector<const MCSectionELF *> SectionTable;
unsigned addToSectionTable(const MCSectionELF *Sec);
// TargetObjectWriter wrappers.
bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
bool hasRelocationAddend() const {
return TargetObjectWriter->hasRelocationAddend();
}
unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
bool IsPCRel) const {
return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
}
void align(unsigned Alignment);
public:
ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
bool IsLittleEndian)
: MCObjectWriter(OS, IsLittleEndian), TargetObjectWriter(MOTW) {}
void reset() override {
Renames.clear();
Relocations.clear();
StrTabBuilder.clear();
SectionTable.clear();
MCObjectWriter::reset();
}
~ELFObjectWriter() override;
void WriteWord(uint64_t W) {
if (is64Bit())
write64(W);
else
write32(W);
}
template <typename T> void write(T Val) {
if (IsLittleEndian)
support::endian::Writer<support::little>(OS).write(Val);
else
support::endian::Writer<support::big>(OS).write(Val);
}
void writeHeader(const MCAssembler &Asm);
void writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
ELFSymbolData &MSD, const MCAsmLayout &Layout);
// Start and end offset of each section
typedef std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>>
SectionOffsetsTy;
bool shouldRelocateWithSymbol(const MCAssembler &Asm,
const MCSymbolRefExpr *RefA,
const MCSymbol *Sym, uint64_t C,
unsigned Type) const;
void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
const MCFragment *Fragment, const MCFixup &Fixup,
MCValue Target, bool &IsPCRel,
uint64_t &FixedValue) override;
// Map from a signature symbol to the group section index
typedef DenseMap<const MCSymbol *, unsigned> RevGroupMapTy;
/// Compute the symbol table data
///
/// \param Asm - The assembler.
/// \param SectionIndexMap - Maps a section to its index.
/// \param RevGroupMap - Maps a signature symbol to the group section.
void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
const SectionIndexMapTy &SectionIndexMap,
const RevGroupMapTy &RevGroupMap,
SectionOffsetsTy &SectionOffsets);
MCSectionELF *createRelocationSection(MCContext &Ctx,
const MCSectionELF &Sec);
const MCSectionELF *createStringTable(MCContext &Ctx);
void executePostLayoutBinding(MCAssembler &Asm,
const MCAsmLayout &Layout) override;
void writeSectionHeader(const MCAsmLayout &Layout,
const SectionIndexMapTy &SectionIndexMap,
const SectionOffsetsTy &SectionOffsets);
void writeSectionData(const MCAssembler &Asm, MCSection &Sec,
const MCAsmLayout &Layout);
void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
uint64_t Address, uint64_t Offset, uint64_t Size,
uint32_t Link, uint32_t Info, uint64_t Alignment,
uint64_t EntrySize);
void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec);
bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
const MCSymbol &SymA,
const MCFragment &FB,
bool InSet,
bool IsPCRel) const override;
bool isWeak(const MCSymbol &Sym) const override;
void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
void writeSection(const SectionIndexMapTy &SectionIndexMap,
uint32_t GroupSymbolIndex, uint64_t Offset, uint64_t Size,
const MCSectionELF &Section);
};
}
void ELFObjectWriter::align(unsigned Alignment) {
uint64_t Padding = OffsetToAlignment(OS.tell(), Alignment);
WriteZeros(Padding);
}
unsigned ELFObjectWriter::addToSectionTable(const MCSectionELF *Sec) {
SectionTable.push_back(Sec);
StrTabBuilder.add(Sec->getSectionName());
return SectionTable.size();
}
void SymbolTableWriter::createSymtabShndx() {
if (!ShndxIndexes.empty())
return;
ShndxIndexes.resize(NumWritten);
}
template <typename T> void SymbolTableWriter::write(T Value) {
EWriter.write(Value);
}
SymbolTableWriter::SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit)
: EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
uint64_t size, uint8_t other,
uint32_t shndx, bool Reserved) {
bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
if (LargeIndex)
createSymtabShndx();
if (!ShndxIndexes.empty()) {
if (LargeIndex)
ShndxIndexes.push_back(shndx);
else
ShndxIndexes.push_back(0);
}
uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
if (Is64Bit) {
write(name); // st_name
write(info); // st_info
write(other); // st_other
write(Index); // st_shndx
write(value); // st_value
write(size); // st_size
} else {
write(name); // st_name
write(uint32_t(value)); // st_value
write(uint32_t(size)); // st_size
write(info); // st_info
write(other); // st_other
write(Index); // st_shndx
}
++NumWritten;
}
bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
const MCFixupKindInfo &FKI =
Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
}
ELFObjectWriter::~ELFObjectWriter()
{}
// Emit the ELF header.
void ELFObjectWriter::writeHeader(const MCAssembler &Asm) {
// ELF Header
// ----------
//
// Note
// ----
// emitWord method behaves differently for ELF32 and ELF64, writing
// 4 bytes in the former and 8 in the latter.
writeBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
// e_ident[EI_DATA]
write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
// e_ident[EI_OSABI]
write8(TargetObjectWriter->getOSABI());
write8(0); // e_ident[EI_ABIVERSION]
WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
write16(ELF::ET_REL); // e_type
write16(TargetObjectWriter->getEMachine()); // e_machine = target
write32(ELF::EV_CURRENT); // e_version
WriteWord(0); // e_entry, no entry point in .o file
WriteWord(0); // e_phoff, no program header for .o
WriteWord(0); // e_shoff = sec hdr table off in bytes
// e_flags = whatever the target wants
write32(Asm.getELFHeaderEFlags());
// e_ehsize = ELF header size
write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
write16(0); // e_phentsize = prog header entry size
write16(0); // e_phnum = # prog header entries = 0
// e_shentsize = Section header entry size
write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
// e_shnum = # of section header ents
write16(0);
// e_shstrndx = Section # of '.shstrtab'
assert(StringTableIndex < ELF::SHN_LORESERVE);
write16(StringTableIndex);
}
uint64_t ELFObjectWriter::SymbolValue(const MCSymbol &Sym,
const MCAsmLayout &Layout) {
if (Sym.isCommon() && Sym.isExternal())
return Sym.getCommonAlignment();
uint64_t Res;
if (!Layout.getSymbolOffset(Sym, Res))
return 0;
if (Layout.getAssembler().isThumbFunc(&Sym))
Res |= 1;
return Res;
}
void ELFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
const MCAsmLayout &Layout) {
// The presence of symbol versions causes undefined symbols and
// versions declared with @@@ to be renamed.
for (const MCSymbol &A : Asm.symbols()) {
const auto &Alias = cast<MCSymbolELF>(A);
// Not an alias.
if (!Alias.isVariable())
continue;
auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
if (!Ref)
continue;
const auto &Symbol = cast<MCSymbolELF>(Ref->getSymbol());
StringRef AliasName = Alias.getName();
size_t Pos = AliasName.find('@');
if (Pos == StringRef::npos)
continue;
// Aliases defined with .symvar copy the binding from the symbol they alias.
// This is the first place we are able to copy this information.
Alias.setExternal(Symbol.isExternal());
Alias.setBinding(Symbol.getBinding());
StringRef Rest = AliasName.substr(Pos);
if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
continue;
// FIXME: produce a better error message.
if (Symbol.isUndefined() && Rest.startswith("@@") &&
!Rest.startswith("@@@"))
report_fatal_error("A @@ version cannot be undefined");
Renames.insert(std::make_pair(&Symbol, &Alias));
}
}
static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
uint8_t Type = newType;
// Propagation rules:
// IFUNC > FUNC > OBJECT > NOTYPE
// TLS_OBJECT > OBJECT > NOTYPE
//
// dont let the new type degrade the old type
switch (origType) {
default:
break;
case ELF::STT_GNU_IFUNC:
if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
Type = ELF::STT_GNU_IFUNC;
break;
case ELF::STT_FUNC:
if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
Type == ELF::STT_TLS)
Type = ELF::STT_FUNC;
break;
case ELF::STT_OBJECT:
if (Type == ELF::STT_NOTYPE)
Type = ELF::STT_OBJECT;
break;
case ELF::STT_TLS:
if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
Type = ELF::STT_TLS;
break;
}
return Type;
}
void ELFObjectWriter::writeSymbol(SymbolTableWriter &Writer,
uint32_t StringIndex, ELFSymbolData &MSD,
const MCAsmLayout &Layout) {
const auto &Symbol = cast<MCSymbolELF>(*MSD.Symbol);
assert((!Symbol.getFragment() ||
(Symbol.getFragment()->getParent() == &Symbol.getSection())) &&
"The symbol's section doesn't match the fragment's symbol");
const MCSymbolELF *Base =
cast_or_null<MCSymbolELF>(Layout.getBaseSymbol(Symbol));
// This has to be in sync with when computeSymbolTable uses SHN_ABS or
// SHN_COMMON.
bool IsReserved = !Base || Symbol.isCommon();
// Binding and Type share the same byte as upper and lower nibbles
uint8_t Binding = Symbol.getBinding();
uint8_t Type = Symbol.getType();
if (Base) {
Type = mergeTypeForSet(Type, Base->getType());
}
uint8_t Info = (Binding << 4) | Type;
// Other and Visibility share the same byte with Visibility using the lower
// 2 bits
uint8_t Visibility = Symbol.getVisibility();
uint8_t Other = Symbol.getOther() | Visibility;
uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
uint64_t Size = 0;
const MCExpr *ESize = MSD.Symbol->getSize();
if (!ESize && Base)
ESize = Base->getSize();
if (ESize) {
int64_t Res;
if (!ESize->evaluateKnownAbsolute(Res, Layout))
report_fatal_error("Size expression must be absolute.");
Size = Res;
}
// Write out the symbol table entry
Writer.writeSymbol(StringIndex, Info, Value, Size, Other, MSD.SectionIndex,
IsReserved);
}
// It is always valid to create a relocation with a symbol. It is preferable
// to use a relocation with a section if that is possible. Using the section
// allows us to omit some local symbols from the symbol table.
bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
const MCSymbolRefExpr *RefA,
const MCSymbol *S, uint64_t C,
unsigned Type) const {
const auto *Sym = cast_or_null<MCSymbolELF>(S);
// A PCRel relocation to an absolute value has no symbol (or section). We
// represent that with a relocation to a null section.
if (!RefA)
return false;
MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
switch (Kind) {
default:
break;
// The .odp creation emits a relocation against the symbol ".TOC." which
// create a R_PPC64_TOC relocation. However the relocation symbol name
// in final object creation should be NULL, since the symbol does not
// really exist, it is just the reference to TOC base for the current
// object file. Since the symbol is undefined, returning false results
// in a relocation with a null section which is the desired result.
case MCSymbolRefExpr::VK_PPC_TOCBASE:
return false;
// These VariantKind cause the relocation to refer to something other than
// the symbol itself, like a linker generated table. Since the address of
// symbol is not relevant, we cannot replace the symbol with the
// section and patch the difference in the addend.
case MCSymbolRefExpr::VK_GOT:
case MCSymbolRefExpr::VK_PLT:
case MCSymbolRefExpr::VK_GOTPCREL:
case MCSymbolRefExpr::VK_Mips_GOT:
case MCSymbolRefExpr::VK_PPC_GOT_LO:
case MCSymbolRefExpr::VK_PPC_GOT_HI:
case MCSymbolRefExpr::VK_PPC_GOT_HA:
return true;
}
// An undefined symbol is not in any section, so the relocation has to point
// to the symbol itself.
assert(Sym && "Expected a symbol");
if (Sym->isUndefined())
return true;
unsigned Binding = Sym->getBinding();
switch(Binding) {
default:
llvm_unreachable("Invalid Binding");
case ELF::STB_LOCAL:
break;
case ELF::STB_WEAK:
// If the symbol is weak, it might be overridden by a symbol in another
// file. The relocation has to point to the symbol so that the linker
// can update it.
return true;
case ELF::STB_GLOBAL:
// Global ELF symbols can be preempted by the dynamic linker. The relocation
// has to point to the symbol for a reason analogous to the STB_WEAK case.
return true;
}
// If a relocation points to a mergeable section, we have to be careful.
// If the offset is zero, a relocation with the section will encode the
// same information. With a non-zero offset, the situation is different.
// For example, a relocation can point 42 bytes past the end of a string.
// If we change such a relocation to use the section, the linker would think
// that it pointed to another string and subtracting 42 at runtime will
// produce the wrong value.
auto &Sec = cast<MCSectionELF>(Sym->getSection());
unsigned Flags = Sec.getFlags();
if (Flags & ELF::SHF_MERGE) {
if (C != 0)
return true;
// It looks like gold has a bug (http://sourceware.org/PR16794) and can
// only handle section relocations to mergeable sections if using RELA.
if (!hasRelocationAddend())
return true;
}
// Most TLS relocations use a got, so they need the symbol. Even those that
// are just an offset (@tpoff), require a symbol in gold versions before
// 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
// http://sourceware.org/PR16773.
if (Flags & ELF::SHF_TLS)
return true;
// If the symbol is a thumb function the final relocation must set the lowest
// bit. With a symbol that is done by just having the symbol have that bit
// set, so we would lose the bit if we relocated with the section.
// FIXME: We could use the section but add the bit to the relocation value.
if (Asm.isThumbFunc(Sym))
return true;
if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
return true;
return false;
}
// True if the assembler knows nothing about the final value of the symbol.
// This doesn't cover the comdat issues, since in those cases the assembler
// can at least know that all symbols in the section will move together.
static bool isWeak(const MCSymbolELF &Sym) {
if (Sym.getType() == ELF::STT_GNU_IFUNC)
return true;
switch (Sym.getBinding()) {
default:
llvm_unreachable("Unknown binding");
case ELF::STB_LOCAL:
return false;
case ELF::STB_GLOBAL:
return false;
case ELF::STB_WEAK:
case ELF::STB_GNU_UNIQUE:
return true;
}
}
void ELFObjectWriter::recordRelocation(MCAssembler &Asm,
const MCAsmLayout &Layout,
const MCFragment *Fragment,
const MCFixup &Fixup, MCValue Target,
bool &IsPCRel, uint64_t &FixedValue) {
const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
uint64_t C = Target.getConstant();
uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
"Should not have constructed this");
// Let A, B and C being the components of Target and R be the location of
// the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
// If it is pcrel, we want to compute (A - B + C - R).
// In general, ELF has no relocations for -B. It can only represent (A + C)
// or (A + C - R). If B = R + K and the relocation is not pcrel, we can
// replace B to implement it: (A - R - K + C)
if (IsPCRel)
Asm.getContext().reportFatalError(
Fixup.getLoc(),
"No relocation available to represent this relative expression");
const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol());
if (SymB.isUndefined())
Asm.getContext().reportFatalError(
Fixup.getLoc(),
Twine("symbol '") + SymB.getName() +
"' can not be undefined in a subtraction expression");
assert(!SymB.isAbsolute() && "Should have been folded");
const MCSection &SecB = SymB.getSection();
if (&SecB != &FixupSection)
Asm.getContext().reportFatalError(
Fixup.getLoc(), "Cannot represent a difference across sections");
if (::isWeak(SymB))
Asm.getContext().reportFatalError(
Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
uint64_t K = SymBOffset - FixupOffset;
IsPCRel = true;
C -= K;
}
// We either rejected the fixup or folded B into C at this point.
const MCSymbolRefExpr *RefA = Target.getSymA();
const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr;
bool ViaWeakRef = false;
if (SymA && SymA->isVariable()) {
const MCExpr *Expr = SymA->getVariableValue();
if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
SymA = cast<MCSymbolELF>(&Inner->getSymbol());
ViaWeakRef = true;
}
}
}
unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
C += Layout.getSymbolOffset(*SymA);
uint64_t Addend = 0;
if (hasRelocationAddend()) {
Addend = C;
C = 0;
}
FixedValue = C;
if (!RelocateWithSymbol) {
const MCSection *SecA =
(SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
const auto *SectionSymbol =
ELFSec ? cast<MCSymbolELF>(ELFSec->getBeginSymbol()) : nullptr;
if (SectionSymbol)
SectionSymbol->setUsedInReloc();
ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
Relocations[&FixupSection].push_back(Rec);
return;
}
if (SymA) {
if (const MCSymbolELF *R = Renames.lookup(SymA))
SymA = R;
if (ViaWeakRef)
SymA->setIsWeakrefUsedInReloc();
else
SymA->setUsedInReloc();
}
ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
Relocations[&FixupSection].push_back(Rec);
return;
}
bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
const MCSymbolELF &Symbol, bool Used,
bool Renamed) {
if (Symbol.isVariable()) {
const MCExpr *Expr = Symbol.getVariableValue();
if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
return false;
}
}
if (Used)
return true;
if (Renamed)
return false;
if (Symbol.isVariable() && Symbol.isUndefined()) {
// FIXME: this is here just to diagnose the case of a var = commmon_sym.
Layout.getBaseSymbol(Symbol);
return false;
}
if (Symbol.isUndefined() && !Symbol.isBindingSet())
return false;
if (Symbol.isTemporary())
return false;
if (Symbol.getType() == ELF::STT_SECTION)
return false;
return true;
}
void ELFObjectWriter::computeSymbolTable(
MCAssembler &Asm, const MCAsmLayout &Layout,
const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
SectionOffsetsTy &SectionOffsets) {
MCContext &Ctx = Asm.getContext();
SymbolTableWriter Writer(*this, is64Bit());
// Symbol table
unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
MCSectionELF *SymtabSection =
Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
SymtabSection->setAlignment(is64Bit() ? 8 : 4);
SymbolTableIndex = addToSectionTable(SymtabSection);
align(SymtabSection->getAlignment());
uint64_t SecStart = OS.tell();
// The first entry is the undefined symbol entry.
Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
std::vector<ELFSymbolData> LocalSymbolData;
std::vector<ELFSymbolData> ExternalSymbolData;
// Add the data for the symbols.
bool HasLargeSectionIndex = false;
for (const MCSymbol &S : Asm.symbols()) {
const auto &Symbol = cast<MCSymbolELF>(S);
bool Used = Symbol.isUsedInReloc();
bool WeakrefUsed = Symbol.isWeakrefUsedInReloc();
bool isSignature = Symbol.isSignature();
if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
Renames.count(&Symbol)))
continue;
if (Symbol.isTemporary() && Symbol.isUndefined())
Ctx.reportFatalError(SMLoc(), "Undefined temporary");
ELFSymbolData MSD;
MSD.Symbol = cast<MCSymbolELF>(&Symbol);
bool Local = Symbol.getBinding() == ELF::STB_LOCAL;
assert(Local || !Symbol.isTemporary());
if (Symbol.isAbsolute()) {
MSD.SectionIndex = ELF::SHN_ABS;
} else if (Symbol.isCommon()) {
assert(!Local);
MSD.SectionIndex = ELF::SHN_COMMON;
} else if (Symbol.isUndefined()) {
if (isSignature && !Used) {
MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
HasLargeSectionIndex = true;
} else {
MSD.SectionIndex = ELF::SHN_UNDEF;
}
} else {
const MCSectionELF &Section =
static_cast<const MCSectionELF &>(Symbol.getSection());
MSD.SectionIndex = SectionIndexMap.lookup(&Section);
assert(MSD.SectionIndex && "Invalid section index!");
if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
HasLargeSectionIndex = true;
}
// The @@@ in symbol version is replaced with @ in undefined symbols and @@
// in defined ones.
//
// FIXME: All name handling should be done before we get to the writer,
// including dealing with GNU-style version suffixes. Fixing this isn't
// trivial.
//
// We thus have to be careful to not perform the symbol version replacement
// blindly:
//
// The ELF format is used on Windows by the MCJIT engine. Thus, on
// Windows, the ELFObjectWriter can encounter symbols mangled using the MS
// Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
// C++ name mangling can legally have "@@@" as a sub-string. In that case,
// the EFLObjectWriter should not interpret the "@@@" sub-string as
// specifying GNU-style symbol versioning. The ELFObjectWriter therefore
// checks for the MSVC C++ name mangling prefix which is either "?", "@?",
// "__imp_?" or "__imp_@?".
//
// It would have been interesting to perform the MS mangling prefix check
// only when the target triple is of the form *-pc-windows-elf. But, it
// seems that this information is not easily accessible from the
// ELFObjectWriter.
StringRef Name = Symbol.getName();
SmallString<32> Buf;
if (!Name.startswith("?") && !Name.startswith("@?") &&
!Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
// This symbol isn't following the MSVC C++ name mangling convention. We
// can thus safely interpret the @@@ in symbol names as specifying symbol
// versioning.
size_t Pos = Name.find("@@@");
if (Pos != StringRef::npos) {
Buf += Name.substr(0, Pos);
unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
Buf += Name.substr(Pos + Skip);
Name = Buf;
}
}
// Sections have their own string table
if (Symbol.getType() != ELF::STT_SECTION)
MSD.Name = StrTabBuilder.add(Name);
if (Local)
LocalSymbolData.push_back(MSD);
else
ExternalSymbolData.push_back(MSD);
}
// This holds the .symtab_shndx section index.
unsigned SymtabShndxSectionIndex = 0;
if (HasLargeSectionIndex) {
MCSectionELF *SymtabShndxSection =
Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
SymtabShndxSection->setAlignment(4);
}
ArrayRef<std::string> FileNames = Asm.getFileNames();
for (const std::string &Name : FileNames)
StrTabBuilder.add(Name);
StrTabBuilder.finalize(StringTableBuilder::ELF);
for (const std::string &Name : FileNames)
Writer.writeSymbol(StrTabBuilder.getOffset(Name),
ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
ELF::SHN_ABS, true);
// Symbols are required to be in lexicographic order.
array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
// Set the symbol indices. Local symbols must come before all other
// symbols with non-local bindings.
unsigned Index = FileNames.size() + 1;
for (ELFSymbolData &MSD : LocalSymbolData) {
unsigned StringIndex = MSD.Symbol->getType() == ELF::STT_SECTION
? 0
: StrTabBuilder.getOffset(MSD.Name);
MSD.Symbol->setIndex(Index++);
writeSymbol(Writer, StringIndex, MSD, Layout);
}
// Write the symbol table entries.
LastLocalSymbolIndex = Index;
for (ELFSymbolData &MSD : ExternalSymbolData) {
unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
MSD.Symbol->setIndex(Index++);
writeSymbol(Writer, StringIndex, MSD, Layout);
assert(MSD.Symbol->getBinding() != ELF::STB_LOCAL);
}
uint64_t SecEnd = OS.tell();
SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
if (ShndxIndexes.empty()) {
assert(SymtabShndxSectionIndex == 0);
return;
}
assert(SymtabShndxSectionIndex != 0);
SecStart = OS.tell();
const MCSectionELF *SymtabShndxSection =
SectionTable[SymtabShndxSectionIndex - 1];
for (uint32_t Index : ShndxIndexes)
write(Index);
SecEnd = OS.tell();
SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
}
MCSectionELF *
ELFObjectWriter::createRelocationSection(MCContext &Ctx,
const MCSectionELF &Sec) {
if (Relocations[&Sec].empty())
return nullptr;
const StringRef SectionName = Sec.getSectionName();
std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
RelaSectionName += SectionName;
unsigned EntrySize;
if (hasRelocationAddend())
EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
else
EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
unsigned Flags = 0;
if (Sec.getFlags() & ELF::SHF_GROUP)
Flags = ELF::SHF_GROUP;
MCSectionELF *RelaSection = Ctx.createELFRelSection(
RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
Flags, EntrySize, Sec.getGroup(), &Sec);
RelaSection->setAlignment(is64Bit() ? 8 : 4);
return RelaSection;
}
static SmallVector<char, 128>
getUncompressedData(const MCAsmLayout &Layout,
const MCSection::FragmentListType &Fragments) {
SmallVector<char, 128> UncompressedData;
for (const MCFragment &F : Fragments) {
const SmallVectorImpl<char> *Contents;
switch (F.getKind()) {
case MCFragment::FT_Data:
Contents = &cast<MCDataFragment>(F).getContents();
break;
case MCFragment::FT_Dwarf:
Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
break;
case MCFragment::FT_DwarfFrame:
Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
break;
default:
llvm_unreachable(
"Not expecting any other fragment types in a debug_* section");
}
UncompressedData.append(Contents->begin(), Contents->end());
}
return UncompressedData;
}
// Include the debug info compression header:
// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
// useful for consumers to preallocate a buffer to decompress into.
static bool
prependCompressionHeader(uint64_t Size,
SmallVectorImpl<char> &CompressedContents) {
const StringRef Magic = "ZLIB";
if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
return false;
if (sys::IsLittleEndianHost)
sys::swapByteOrder(Size);
CompressedContents.insert(CompressedContents.begin(),
Magic.size() + sizeof(Size), 0);
std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
std::copy(reinterpret_cast<char *>(&Size),
reinterpret_cast<char *>(&Size + 1),
CompressedContents.begin() + Magic.size());
return true;
}
void ELFObjectWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
const MCAsmLayout &Layout) {
MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
StringRef SectionName = Section.getSectionName();
// Compressing debug_frame requires handling alignment fragments which is
// more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
// for writing to arbitrary buffers) for little benefit.
if (!Asm.getContext().getAsmInfo()->compressDebugSections() ||
!SectionName.startswith(".debug_") || SectionName == ".debug_frame") {
Asm.writeSectionData(&Section, Layout);
return;
}
// Gather the uncompressed data from all the fragments.
const MCSection::FragmentListType &Fragments = Section.getFragmentList();
SmallVector<char, 128> UncompressedData =
getUncompressedData(Layout, Fragments);
SmallVector<char, 128> CompressedContents;
zlib::Status Success = zlib::compress(
StringRef(UncompressedData.data(), UncompressedData.size()),
CompressedContents);
if (Success != zlib::StatusOK) {
Asm.writeSectionData(&Section, Layout);
return;
}
if (!prependCompressionHeader(UncompressedData.size(), CompressedContents)) {
Asm.writeSectionData(&Section, Layout);
return;
}
Asm.getContext().renameELFSection(&Section,
(".z" + SectionName.drop_front(1)).str());
OS << CompressedContents;
}
void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
uint64_t Flags, uint64_t Address,
uint64_t Offset, uint64_t Size,
uint32_t Link, uint32_t Info,
uint64_t Alignment,
uint64_t EntrySize) {
write32(Name); // sh_name: index into string table
write32(Type); // sh_type
WriteWord(Flags); // sh_flags
WriteWord(Address); // sh_addr
WriteWord(Offset); // sh_offset
WriteWord(Size); // sh_size
write32(Link); // sh_link
write32(Info); // sh_info
WriteWord(Alignment); // sh_addralign
WriteWord(EntrySize); // sh_entsize
}
void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
const MCSectionELF &Sec) {
std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
// Sort the relocation entries. Most targets just sort by Offset, but some
// (e.g., MIPS) have additional constraints.
TargetObjectWriter->sortRelocs(Asm, Relocs);
for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
const ELFRelocationEntry &Entry = Relocs[e - i - 1];
unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
if (is64Bit()) {
write(Entry.Offset);
if (TargetObjectWriter->isN64()) {
write(uint32_t(Index));
write(TargetObjectWriter->getRSsym(Entry.Type));
write(TargetObjectWriter->getRType3(Entry.Type));
write(TargetObjectWriter->getRType2(Entry.Type));
write(TargetObjectWriter->getRType(Entry.Type));
} else {
struct ELF::Elf64_Rela ERE64;
ERE64.setSymbolAndType(Index, Entry.Type);
write(ERE64.r_info);
}
if (hasRelocationAddend())
write(Entry.Addend);
} else {
write(uint32_t(Entry.Offset));
struct ELF::Elf32_Rela ERE32;
ERE32.setSymbolAndType(Index, Entry.Type);
write(ERE32.r_info);
if (hasRelocationAddend())
write(uint32_t(Entry.Addend));
}
}
}
const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) {
const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
OS << StrTabBuilder.data();
return StrtabSection;
}
void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
uint32_t GroupSymbolIndex, uint64_t Offset,
uint64_t Size, const MCSectionELF &Section) {
uint64_t sh_link = 0;
uint64_t sh_info = 0;
switch(Section.getType()) {
default:
// Nothing to do.
break;
case ELF::SHT_DYNAMIC:
llvm_unreachable("SHT_DYNAMIC in a relocatable object");
case ELF::SHT_REL:
case ELF::SHT_RELA: {
sh_link = SymbolTableIndex;
assert(sh_link && ".symtab not found");
const MCSectionELF *InfoSection = Section.getAssociatedSection();
sh_info = SectionIndexMap.lookup(InfoSection);
break;
}
case ELF::SHT_SYMTAB:
case ELF::SHT_DYNSYM:
sh_link = StringTableIndex;
sh_info = LastLocalSymbolIndex;
break;
case ELF::SHT_SYMTAB_SHNDX:
sh_link = SymbolTableIndex;
break;
case ELF::SHT_GROUP:
sh_link = SymbolTableIndex;
sh_info = GroupSymbolIndex;
break;
}
if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
Section.getType() == ELF::SHT_ARM_EXIDX)
sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
Section.getType(), Section.getFlags(), 0, Offset, Size,
sh_link, sh_info, Section.getAlignment(),
Section.getEntrySize());
}
void ELFObjectWriter::writeSectionHeader(
const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
const SectionOffsetsTy &SectionOffsets) {
const unsigned NumSections = SectionTable.size();
// Null section first.
uint64_t FirstSectionSize =
(NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
for (const MCSectionELF *Section : SectionTable) {
uint32_t GroupSymbolIndex;
unsigned Type = Section->getType();
if (Type != ELF::SHT_GROUP)
GroupSymbolIndex = 0;
else
GroupSymbolIndex = Section->getGroup()->getIndex();
const std::pair<uint64_t, uint64_t> &Offsets =
SectionOffsets.find(Section)->second;
uint64_t Size;
if (Type == ELF::SHT_NOBITS)
Size = Layout.getSectionAddressSize(Section);
else
Size = Offsets.second - Offsets.first;
writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
*Section);
}
}
void ELFObjectWriter::writeObject(MCAssembler &Asm,
const MCAsmLayout &Layout) {
MCContext &Ctx = Asm.getContext();
MCSectionELF *StrtabSection =
Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
StringTableIndex = addToSectionTable(StrtabSection);
RevGroupMapTy RevGroupMap;
SectionIndexMapTy SectionIndexMap;
std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
// Write out the ELF header ...
writeHeader(Asm);
// ... then the sections ...
SectionOffsetsTy SectionOffsets;
std::vector<MCSectionELF *> Groups;
std::vector<MCSectionELF *> Relocations;
for (MCSection &Sec : Asm) {
MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
align(Section.getAlignment());
// Remember the offset into the file for this section.
uint64_t SecStart = OS.tell();
const MCSymbolELF *SignatureSymbol = Section.getGroup();
writeSectionData(Asm, Section, Layout);
uint64_t SecEnd = OS.tell();
SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
if (SignatureSymbol) {
Asm.registerSymbol(*SignatureSymbol);
unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
if (!GroupIdx) {
MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
GroupIdx = addToSectionTable(Group);
Group->setAlignment(4);
Groups.push_back(Group);
}
std::vector<const MCSectionELF *> &Members =
GroupMembers[SignatureSymbol];
Members.push_back(&Section);
if (RelSection)
Members.push_back(RelSection);
}
SectionIndexMap[&Section] = addToSectionTable(&Section);
if (RelSection) {
SectionIndexMap[RelSection] = addToSectionTable(RelSection);
Relocations.push_back(RelSection);
}
}
for (MCSectionELF *Group : Groups) {
align(Group->getAlignment());
// Remember the offset into the file for this section.
uint64_t SecStart = OS.tell();
const MCSymbol *SignatureSymbol = Group->getGroup();
assert(SignatureSymbol);
write(uint32_t(ELF::GRP_COMDAT));
for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
uint32_t SecIndex = SectionIndexMap.lookup(Member);
write(SecIndex);
}
uint64_t SecEnd = OS.tell();
SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
}
// Compute symbol table information.
computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap, SectionOffsets);
for (MCSectionELF *RelSection : Relocations) {
align(RelSection->getAlignment());
// Remember the offset into the file for this section.
uint64_t SecStart = OS.tell();
writeRelocations(Asm, *RelSection->getAssociatedSection());
uint64_t SecEnd = OS.tell();
SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
}
{
uint64_t SecStart = OS.tell();
const MCSectionELF *Sec = createStringTable(Ctx);
uint64_t SecEnd = OS.tell();
SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
}
uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
align(NaturalAlignment);
const unsigned SectionHeaderOffset = OS.tell();
// ... then the section header table ...
writeSectionHeader(Layout, SectionIndexMap, SectionOffsets);
uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE)
? (uint16_t)ELF::SHN_UNDEF
: SectionTable.size() + 1;
if (sys::IsLittleEndianHost != IsLittleEndian)
sys::swapByteOrder(NumSections);
unsigned NumSectionsOffset;
if (is64Bit()) {
uint64_t Val = SectionHeaderOffset;
if (sys::IsLittleEndianHost != IsLittleEndian)
sys::swapByteOrder(Val);
OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
offsetof(ELF::Elf64_Ehdr, e_shoff));
NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
} else {
uint32_t Val = SectionHeaderOffset;
if (sys::IsLittleEndianHost != IsLittleEndian)
sys::swapByteOrder(Val);
OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
offsetof(ELF::Elf32_Ehdr, e_shoff));
NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
}
OS.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
NumSectionsOffset);
}
bool ELFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB,
bool InSet, bool IsPCRel) const {
const auto &SymA = cast<MCSymbolELF>(SA);
if (IsPCRel) {
assert(!InSet);
if (::isWeak(SymA))
return false;
}
return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
InSet, IsPCRel);
}
bool ELFObjectWriter::isWeak(const MCSymbol &S) const {
const auto &Sym = cast<MCSymbolELF>(S);
if (::isWeak(Sym))
return true;
// It is invalid to replace a reference to a global in a comdat
// with a reference to a local since out of comdat references
// to a local are forbidden.
// We could try to return false for more cases, like the reference
// being in the same comdat or Sym being an alias to another global,
// but it is not clear if it is worth the effort.
if (Sym.getBinding() != ELF::STB_GLOBAL)
return false;
if (!Sym.isInSection())
return false;
const auto &Sec = cast<MCSectionELF>(Sym.getSection());
return Sec.getGroup();
}
MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
raw_pwrite_stream &OS,
bool IsLittleEndian) {
return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/WinCOFFObjectWriter.cpp | //===-- llvm/MC/WinCOFFObjectWriter.cpp -------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains an implementation of a Win32 COFF object file writer.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCWinCOFFObjectWriter.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/MC/MCAsmLayout.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCSectionCOFF.h"
#include "llvm/MC/MCSymbolCOFF.h"
#include "llvm/MC/MCValue.h"
#include "llvm/MC/StringTableBuilder.h"
#include "llvm/Support/COFF.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TimeValue.h"
#include <cstdio>
using namespace llvm;
#define DEBUG_TYPE "WinCOFFObjectWriter"
namespace {
typedef SmallString<COFF::NameSize> name;
enum AuxiliaryType {
ATFunctionDefinition,
ATbfAndefSymbol,
ATWeakExternal,
ATFile,
ATSectionDefinition
};
struct AuxSymbol {
AuxiliaryType AuxType;
COFF::Auxiliary Aux;
};
class COFFSymbol;
class COFFSection;
class COFFSymbol {
public:
COFF::symbol Data;
typedef SmallVector<AuxSymbol, 1> AuxiliarySymbols;
name Name;
int Index;
AuxiliarySymbols Aux;
COFFSymbol *Other;
COFFSection *Section;
int Relocations;
const MCSymbol *MC;
COFFSymbol(StringRef name);
void set_name_offset(uint32_t Offset);
bool should_keep() const;
int64_t getIndex() const { return Index; }
void setIndex(int Value) {
Index = Value;
if (MC)
MC->setIndex(static_cast<uint32_t>(Value));
}
};
// This class contains staging data for a COFF relocation entry.
struct COFFRelocation {
COFF::relocation Data;
COFFSymbol *Symb;
COFFRelocation() : Symb(nullptr) {}
static size_t size() { return COFF::RelocationSize; }
};
typedef std::vector<COFFRelocation> relocations;
class COFFSection {
public:
COFF::section Header;
std::string Name;
int Number;
MCSectionCOFF const *MCSection;
COFFSymbol *Symbol;
relocations Relocations;
COFFSection(StringRef name);
static size_t size();
};
class WinCOFFObjectWriter : public MCObjectWriter {
public:
typedef std::vector<std::unique_ptr<COFFSymbol>> symbols;
typedef std::vector<std::unique_ptr<COFFSection>> sections;
typedef DenseMap<MCSymbol const *, COFFSymbol *> symbol_map;
typedef DenseMap<MCSection const *, COFFSection *> section_map;
std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
// Root level file contents.
COFF::header Header;
sections Sections;
symbols Symbols;
StringTableBuilder Strings;
// Maps used during object file creation.
section_map SectionMap;
symbol_map SymbolMap;
bool UseBigObj;
WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_pwrite_stream &OS);
void reset() override {
memset(&Header, 0, sizeof(Header));
Header.Machine = TargetObjectWriter->getMachine();
Sections.clear();
Symbols.clear();
Strings.clear();
SectionMap.clear();
SymbolMap.clear();
MCObjectWriter::reset();
}
COFFSymbol *createSymbol(StringRef Name);
COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol *Symbol);
COFFSection *createSection(StringRef Name);
template <typename object_t, typename list_t>
object_t *createCOFFEntity(StringRef Name, list_t &List);
void defineSection(MCSectionCOFF const &Sec);
void DefineSymbol(const MCSymbol &Symbol, MCAssembler &Assembler,
const MCAsmLayout &Layout);
void SetSymbolName(COFFSymbol &S);
void SetSectionName(COFFSection &S);
bool ExportSymbol(const MCSymbol &Symbol, MCAssembler &Asm);
bool IsPhysicalSection(COFFSection *S);
// Entity writing methods.
void WriteFileHeader(const COFF::header &Header);
void WriteSymbol(const COFFSymbol &S);
void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
void writeSectionHeader(const COFF::section &S);
void WriteRelocation(const COFF::relocation &R);
// MCObjectWriter interface implementation.
void executePostLayoutBinding(MCAssembler &Asm,
const MCAsmLayout &Layout) override;
bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
const MCSymbol &SymA,
const MCFragment &FB, bool InSet,
bool IsPCRel) const override;
bool isWeak(const MCSymbol &Sym) const override;
void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
const MCFragment *Fragment, const MCFixup &Fixup,
MCValue Target, bool &IsPCRel,
uint64_t &FixedValue) override;
void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
};
}
static inline void write_uint32_le(void *Data, uint32_t Value) {
support::endian::write<uint32_t, support::little, support::unaligned>(Data,
Value);
}
//------------------------------------------------------------------------------
// Symbol class implementation
COFFSymbol::COFFSymbol(StringRef name)
: Name(name.begin(), name.end()), Other(nullptr), Section(nullptr),
Relocations(0), MC(nullptr) {
memset(&Data, 0, sizeof(Data));
}
// In the case that the name does not fit within 8 bytes, the offset
// into the string table is stored in the last 4 bytes instead, leaving
// the first 4 bytes as 0.
void COFFSymbol::set_name_offset(uint32_t Offset) {
write_uint32_le(Data.Name + 0, 0);
write_uint32_le(Data.Name + 4, Offset);
}
/// logic to decide if the symbol should be reported in the symbol table
bool COFFSymbol::should_keep() const {
// no section means its external, keep it
if (!Section)
return true;
// if it has relocations pointing at it, keep it
if (Relocations > 0) {
assert(Section->Number != -1 && "Sections with relocations must be real!");
return true;
}
// if this is a safeseh handler, keep it
if (MC && (cast<MCSymbolCOFF>(MC)->isSafeSEH()))
return true;
// if the section its in is being droped, drop it
if (Section->Number == -1)
return false;
// if it is the section symbol, keep it
if (Section->Symbol == this)
return true;
// if its temporary, drop it
if (MC && MC->isTemporary())
return false;
// otherwise, keep it
return true;
}
//------------------------------------------------------------------------------
// Section class implementation
COFFSection::COFFSection(StringRef name)
: Name(name), MCSection(nullptr), Symbol(nullptr) {
memset(&Header, 0, sizeof(Header));
}
size_t COFFSection::size() { return COFF::SectionSize; }
//------------------------------------------------------------------------------
// WinCOFFObjectWriter class implementation
WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
raw_pwrite_stream &OS)
: MCObjectWriter(OS, true), TargetObjectWriter(MOTW) {
memset(&Header, 0, sizeof(Header));
Header.Machine = TargetObjectWriter->getMachine();
}
COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
return createCOFFEntity<COFFSymbol>(Name, Symbols);
}
COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol *Symbol) {
symbol_map::iterator i = SymbolMap.find(Symbol);
if (i != SymbolMap.end())
return i->second;
COFFSymbol *RetSymbol =
createCOFFEntity<COFFSymbol>(Symbol->getName(), Symbols);
SymbolMap[Symbol] = RetSymbol;
return RetSymbol;
}
COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
return createCOFFEntity<COFFSection>(Name, Sections);
}
/// A template used to lookup or create a symbol/section, and initialize it if
/// needed.
template <typename object_t, typename list_t>
object_t *WinCOFFObjectWriter::createCOFFEntity(StringRef Name, list_t &List) {
List.push_back(make_unique<object_t>(Name));
return List.back().get();
}
/// This function takes a section data object from the assembler
/// and creates the associated COFF section staging object.
void WinCOFFObjectWriter::defineSection(MCSectionCOFF const &Sec) {
COFFSection *coff_section = createSection(Sec.getSectionName());
COFFSymbol *coff_symbol = createSymbol(Sec.getSectionName());
if (Sec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
if (const MCSymbol *S = Sec.getCOMDATSymbol()) {
COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
if (COMDATSymbol->Section)
report_fatal_error("two sections have the same comdat");
COMDATSymbol->Section = coff_section;
}
}
coff_section->Symbol = coff_symbol;
coff_symbol->Section = coff_section;
coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
// In this case the auxiliary symbol is a Section Definition.
coff_symbol->Aux.resize(1);
memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
coff_symbol->Aux[0].AuxType = ATSectionDefinition;
coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection();
coff_section->Header.Characteristics = Sec.getCharacteristics();
uint32_t &Characteristics = coff_section->Header.Characteristics;
switch (Sec.getAlignment()) {
case 1:
Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES;
break;
case 2:
Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES;
break;
case 4:
Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES;
break;
case 8:
Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES;
break;
case 16:
Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES;
break;
case 32:
Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES;
break;
case 64:
Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES;
break;
case 128:
Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES;
break;
case 256:
Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES;
break;
case 512:
Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES;
break;
case 1024:
Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES;
break;
case 2048:
Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES;
break;
case 4096:
Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES;
break;
case 8192:
Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES;
break;
default:
llvm_unreachable("unsupported section alignment");
}
// Bind internal COFF section to MC section.
coff_section->MCSection = &Sec;
SectionMap[&Sec] = coff_section;
}
static uint64_t getSymbolValue(const MCSymbol &Symbol,
const MCAsmLayout &Layout) {
if (Symbol.isCommon() && Symbol.isExternal())
return Symbol.getCommonSize();
uint64_t Res;
if (!Layout.getSymbolOffset(Symbol, Res))
return 0;
return Res;
}
/// This function takes a symbol data object from the assembler
/// and creates the associated COFF symbol staging object.
void WinCOFFObjectWriter::DefineSymbol(const MCSymbol &Symbol,
MCAssembler &Assembler,
const MCAsmLayout &Layout) {
COFFSymbol *coff_symbol = GetOrCreateCOFFSymbol(&Symbol);
SymbolMap[&Symbol] = coff_symbol;
if (cast<MCSymbolCOFF>(Symbol).isWeakExternal()) {
coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
if (Symbol.isVariable()) {
const MCSymbolRefExpr *SymRef =
dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
if (!SymRef)
report_fatal_error("Weak externals may only alias symbols");
coff_symbol->Other = GetOrCreateCOFFSymbol(&SymRef->getSymbol());
} else {
std::string WeakName = (".weak." + Symbol.getName() + ".default").str();
COFFSymbol *WeakDefault = createSymbol(WeakName);
WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
WeakDefault->Data.StorageClass = COFF::IMAGE_SYM_CLASS_EXTERNAL;
WeakDefault->Data.Type = 0;
WeakDefault->Data.Value = 0;
coff_symbol->Other = WeakDefault;
}
// Setup the Weak External auxiliary symbol.
coff_symbol->Aux.resize(1);
memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
coff_symbol->Aux[0].AuxType = ATWeakExternal;
coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0;
coff_symbol->Aux[0].Aux.WeakExternal.Characteristics =
COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
coff_symbol->MC = &Symbol;
} else {
const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
coff_symbol->Data.Value = getSymbolValue(Symbol, Layout);
const MCSymbolCOFF &SymbolCOFF = cast<MCSymbolCOFF>(Symbol);
coff_symbol->Data.Type = SymbolCOFF.getType();
coff_symbol->Data.StorageClass = SymbolCOFF.getClass();
// If no storage class was specified in the streamer, define it here.
if (coff_symbol->Data.StorageClass == COFF::IMAGE_SYM_CLASS_NULL) {
bool IsExternal = Symbol.isExternal() ||
(!Symbol.getFragment() && !Symbol.isVariable());
coff_symbol->Data.StorageClass = IsExternal
? COFF::IMAGE_SYM_CLASS_EXTERNAL
: COFF::IMAGE_SYM_CLASS_STATIC;
}
if (!Base) {
coff_symbol->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
} else {
if (Base->getFragment()) {
COFFSection *Sec = SectionMap[Base->getFragment()->getParent()];
if (coff_symbol->Section && coff_symbol->Section != Sec)
report_fatal_error("conflicting sections for symbol");
coff_symbol->Section = Sec;
}
}
coff_symbol->MC = &Symbol;
}
}
// Maximum offsets for different string table entry encodings.
static const unsigned Max6DecimalOffset = 999999;
static const unsigned Max7DecimalOffset = 9999999;
static const uint64_t MaxBase64Offset = 0xFFFFFFFFFULL; // 64^6, including 0
// Encode a string table entry offset in base 64, padded to 6 chars, and
// prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
// Buffer must be at least 8 bytes large. No terminating null appended.
static void encodeBase64StringEntry(char *Buffer, uint64_t Value) {
assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
"Illegal section name encoding for value");
static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
Buffer[0] = '/';
Buffer[1] = '/';
char *Ptr = Buffer + 7;
for (unsigned i = 0; i < 6; ++i) {
unsigned Rem = Value % 64;
Value /= 64;
*(Ptr--) = Alphabet[Rem];
}
}
void WinCOFFObjectWriter::SetSectionName(COFFSection &S) {
if (S.Name.size() > COFF::NameSize) {
uint64_t StringTableEntry = Strings.getOffset(S.Name);
if (StringTableEntry <= Max6DecimalOffset) {
//std::sprintf(S.Header.Name, "/%d", unsigned(StringTableEntry)); // HLSL Change - use sprintf_s
sprintf_s(S.Header.Name, _countof(S.Header.Name), "/%d", unsigned(StringTableEntry));
} else if (StringTableEntry <= Max7DecimalOffset) {
// With seven digits, we have to skip the terminating null. Because
// sprintf always appends it, we use a larger temporary buffer.
char buffer[9] = { 0 }; // HLSL Change - initialize first element with 0
//std::sprintf(buffer, "/%d", unsigned(StringTableEntry)); // HLSL Change - use sprintf_s instead
sprintf_s(buffer, _countof(buffer), "/%d", unsigned(StringTableEntry));
std::memcpy(S.Header.Name, buffer, 8);
} else if (StringTableEntry <= MaxBase64Offset) {
// Starting with 10,000,000, offsets are encoded as base64.
encodeBase64StringEntry(S.Header.Name, StringTableEntry);
} else {
report_fatal_error("COFF string table is greater than 64 GB.");
}
} else
std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
}
void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
if (S.Name.size() > COFF::NameSize)
S.set_name_offset(Strings.getOffset(S.Name));
else
std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
}
bool WinCOFFObjectWriter::ExportSymbol(const MCSymbol &Symbol,
MCAssembler &Asm) {
// This doesn't seem to be right. Strings referred to from the .data section
// need symbols so they can be linked to code in the .text section right?
// return Asm.isSymbolLinkerVisible(Symbol);
// Non-temporary labels should always be visible to the linker.
if (!Symbol.isTemporary())
return true;
// Temporary variable symbols are invisible.
if (Symbol.isVariable())
return false;
// Absolute temporary labels are never visible.
return !Symbol.isAbsolute();
}
bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
return (S->Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) ==
0;
}
//------------------------------------------------------------------------------
// entity writing methods
void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
if (UseBigObj) {
writeLE16(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
writeLE16(0xFFFF);
writeLE16(COFF::BigObjHeader::MinBigObjectVersion);
writeLE16(Header.Machine);
writeLE32(Header.TimeDateStamp);
writeBytes(StringRef(COFF::BigObjMagic, sizeof(COFF::BigObjMagic)));
writeLE32(0);
writeLE32(0);
writeLE32(0);
writeLE32(0);
writeLE32(Header.NumberOfSections);
writeLE32(Header.PointerToSymbolTable);
writeLE32(Header.NumberOfSymbols);
} else {
writeLE16(Header.Machine);
writeLE16(static_cast<int16_t>(Header.NumberOfSections));
writeLE32(Header.TimeDateStamp);
writeLE32(Header.PointerToSymbolTable);
writeLE32(Header.NumberOfSymbols);
writeLE16(Header.SizeOfOptionalHeader);
writeLE16(Header.Characteristics);
}
}
void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
writeBytes(StringRef(S.Data.Name, COFF::NameSize));
writeLE32(S.Data.Value);
if (UseBigObj)
writeLE32(S.Data.SectionNumber);
else
writeLE16(static_cast<int16_t>(S.Data.SectionNumber));
writeLE16(S.Data.Type);
write8(S.Data.StorageClass);
write8(S.Data.NumberOfAuxSymbols);
WriteAuxiliarySymbols(S.Aux);
}
void WinCOFFObjectWriter::WriteAuxiliarySymbols(
const COFFSymbol::AuxiliarySymbols &S) {
for (COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
i != e; ++i) {
switch (i->AuxType) {
case ATFunctionDefinition:
writeLE32(i->Aux.FunctionDefinition.TagIndex);
writeLE32(i->Aux.FunctionDefinition.TotalSize);
writeLE32(i->Aux.FunctionDefinition.PointerToLinenumber);
writeLE32(i->Aux.FunctionDefinition.PointerToNextFunction);
WriteZeros(sizeof(i->Aux.FunctionDefinition.unused));
if (UseBigObj)
WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
break;
case ATbfAndefSymbol:
WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1));
writeLE16(i->Aux.bfAndefSymbol.Linenumber);
WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2));
writeLE32(i->Aux.bfAndefSymbol.PointerToNextFunction);
WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3));
if (UseBigObj)
WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
break;
case ATWeakExternal:
writeLE32(i->Aux.WeakExternal.TagIndex);
writeLE32(i->Aux.WeakExternal.Characteristics);
WriteZeros(sizeof(i->Aux.WeakExternal.unused));
if (UseBigObj)
WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
break;
case ATFile:
writeBytes(
StringRef(reinterpret_cast<const char *>(&i->Aux),
UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size));
break;
case ATSectionDefinition:
writeLE32(i->Aux.SectionDefinition.Length);
writeLE16(i->Aux.SectionDefinition.NumberOfRelocations);
writeLE16(i->Aux.SectionDefinition.NumberOfLinenumbers);
writeLE32(i->Aux.SectionDefinition.CheckSum);
writeLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number));
write8(i->Aux.SectionDefinition.Selection);
WriteZeros(sizeof(i->Aux.SectionDefinition.unused));
writeLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number >> 16));
if (UseBigObj)
WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
break;
}
}
}
void WinCOFFObjectWriter::writeSectionHeader(const COFF::section &S) {
writeBytes(StringRef(S.Name, COFF::NameSize));
writeLE32(S.VirtualSize);
writeLE32(S.VirtualAddress);
writeLE32(S.SizeOfRawData);
writeLE32(S.PointerToRawData);
writeLE32(S.PointerToRelocations);
writeLE32(S.PointerToLineNumbers);
writeLE16(S.NumberOfRelocations);
writeLE16(S.NumberOfLineNumbers);
writeLE32(S.Characteristics);
}
void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
writeLE32(R.VirtualAddress);
writeLE32(R.SymbolTableIndex);
writeLE16(R.Type);
}
////////////////////////////////////////////////////////////////////////////////
// MCObjectWriter interface implementations
void WinCOFFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
const MCAsmLayout &Layout) {
// "Define" each section & symbol. This creates section & symbol
// entries in the staging area.
for (const auto &Section : Asm)
defineSection(static_cast<const MCSectionCOFF &>(Section));
for (const MCSymbol &Symbol : Asm.symbols())
if (ExportSymbol(Symbol, Asm))
DefineSymbol(Symbol, Asm, Layout);
}
bool WinCOFFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
bool InSet, bool IsPCRel) const {
// MS LINK expects to be able to replace all references to a function with a
// thunk to implement their /INCREMENTAL feature. Make sure we don't optimize
// away any relocations to functions.
uint16_t Type = cast<MCSymbolCOFF>(SymA).getType();
if ((Type >> COFF::SCT_COMPLEX_TYPE_SHIFT) == COFF::IMAGE_SYM_DTYPE_FUNCTION)
return false;
return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
InSet, IsPCRel);
}
bool WinCOFFObjectWriter::isWeak(const MCSymbol &Sym) const {
if (!Sym.isExternal())
return false;
if (!Sym.isInSection())
return false;
const auto &Sec = cast<MCSectionCOFF>(Sym.getSection());
if (!Sec.getCOMDATSymbol())
return false;
// It looks like for COFF it is invalid to replace a reference to a global
// in a comdat with a reference to a local.
// FIXME: Add a specification reference if available.
return true;
}
void WinCOFFObjectWriter::recordRelocation(
MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment,
const MCFixup &Fixup, MCValue Target, bool &IsPCRel, uint64_t &FixedValue) {
assert(Target.getSymA() && "Relocation must reference a symbol!");
const MCSymbol &Symbol = Target.getSymA()->getSymbol();
const MCSymbol &A = Symbol;
if (!A.isRegistered())
Asm.getContext().reportFatalError(Fixup.getLoc(),
Twine("symbol '") + A.getName() +
"' can not be undefined");
MCSection *Section = Fragment->getParent();
// Mark this symbol as requiring an entry in the symbol table.
assert(SectionMap.find(Section) != SectionMap.end() &&
"Section must already have been defined in executePostLayoutBinding!");
assert(SymbolMap.find(&A) != SymbolMap.end() &&
"Symbol must already have been defined in executePostLayoutBinding!");
COFFSection *coff_section = SectionMap[Section];
COFFSymbol *coff_symbol = SymbolMap[&A];
const MCSymbolRefExpr *SymB = Target.getSymB();
bool CrossSection = false;
if (SymB) {
const MCSymbol *B = &SymB->getSymbol();
if (!B->getFragment())
Asm.getContext().reportFatalError(
Fixup.getLoc(),
Twine("symbol '") + B->getName() +
"' can not be undefined in a subtraction expression");
if (!A.getFragment())
Asm.getContext().reportFatalError(
Fixup.getLoc(),
Twine("symbol '") + Symbol.getName() +
"' can not be undefined in a subtraction expression");
CrossSection = &Symbol.getSection() != &B->getSection();
// Offset of the symbol in the section
int64_t OffsetOfB = Layout.getSymbolOffset(*B);
// In the case where we have SymbA and SymB, we just need to store the delta
// between the two symbols. Update FixedValue to account for the delta, and
// skip recording the relocation.
if (!CrossSection) {
int64_t OffsetOfA = Layout.getSymbolOffset(A);
FixedValue = (OffsetOfA - OffsetOfB) + Target.getConstant();
return;
}
// Offset of the relocation in the section
int64_t OffsetOfRelocation =
Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.getConstant();
} else {
FixedValue = Target.getConstant();
}
COFFRelocation Reloc;
Reloc.Data.SymbolTableIndex = 0;
Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
// Turn relocations for temporary symbols into section relocations.
if (coff_symbol->MC->isTemporary() || CrossSection) {
Reloc.Symb = coff_symbol->Section->Symbol;
FixedValue += Layout.getFragmentOffset(coff_symbol->MC->getFragment()) +
coff_symbol->MC->getOffset();
} else
Reloc.Symb = coff_symbol;
++Reloc.Symb->Relocations;
Reloc.Data.VirtualAddress += Fixup.getOffset();
Reloc.Data.Type = TargetObjectWriter->getRelocType(
Target, Fixup, CrossSection, Asm.getBackend());
// FIXME: Can anyone explain what this does other than adjust for the size
// of the offset?
if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
(Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
FixedValue += 4;
if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
switch (Reloc.Data.Type) {
case COFF::IMAGE_REL_ARM_ABSOLUTE:
case COFF::IMAGE_REL_ARM_ADDR32:
case COFF::IMAGE_REL_ARM_ADDR32NB:
case COFF::IMAGE_REL_ARM_TOKEN:
case COFF::IMAGE_REL_ARM_SECTION:
case COFF::IMAGE_REL_ARM_SECREL:
break;
case COFF::IMAGE_REL_ARM_BRANCH11:
case COFF::IMAGE_REL_ARM_BLX11:
// IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
// pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
// for Windows CE).
case COFF::IMAGE_REL_ARM_BRANCH24:
case COFF::IMAGE_REL_ARM_BLX24:
case COFF::IMAGE_REL_ARM_MOV32A:
// IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
// only used for ARM mode code, which is documented as being unsupported
// by Windows on ARM. Empirical proof indicates that masm is able to
// generate the relocations however the rest of the MSVC toolchain is
// unable to handle it.
llvm_unreachable("unsupported relocation");
break;
case COFF::IMAGE_REL_ARM_MOV32T:
break;
case COFF::IMAGE_REL_ARM_BRANCH20T:
case COFF::IMAGE_REL_ARM_BRANCH24T:
case COFF::IMAGE_REL_ARM_BLX23T:
// IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
// perform a 4 byte adjustment to the relocation. Relative branches are
// offset by 4 on ARM, however, because there is no RELA relocations, all
// branches are offset by 4.
FixedValue = FixedValue + 4;
break;
}
}
if (TargetObjectWriter->recordRelocation(Fixup))
coff_section->Relocations.push_back(Reloc);
}
void WinCOFFObjectWriter::writeObject(MCAssembler &Asm,
const MCAsmLayout &Layout) {
size_t SectionsSize = Sections.size();
if (SectionsSize > static_cast<size_t>(INT32_MAX))
report_fatal_error(
"PE COFF object files can't have more than 2147483647 sections");
// Assign symbol and section indexes and offsets.
int32_t NumberOfSections = static_cast<int32_t>(SectionsSize);
UseBigObj = NumberOfSections > COFF::MaxNumberOfSections16;
// Assign section numbers.
size_t Number = 1;
for (const auto &Section : Sections) {
Section->Number = Number;
Section->Symbol->Data.SectionNumber = Number;
Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Number;
++Number;
}
Header.NumberOfSections = NumberOfSections;
Header.NumberOfSymbols = 0;
for (const std::string &Name : Asm.getFileNames()) {
// round up to calculate the number of auxiliary symbols required
unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
unsigned Count = (Name.size() + SymbolSize - 1) / SymbolSize;
COFFSymbol *file = createSymbol(".file");
file->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
file->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
file->Aux.resize(Count);
unsigned Offset = 0;
unsigned Length = Name.size();
for (auto &Aux : file->Aux) {
Aux.AuxType = ATFile;
if (Length > SymbolSize) {
memcpy(&Aux.Aux, Name.c_str() + Offset, SymbolSize);
Length = Length - SymbolSize;
} else {
memcpy(&Aux.Aux, Name.c_str() + Offset, Length);
memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
break;
}
Offset += SymbolSize;
}
}
for (auto &Symbol : Symbols) {
// Update section number & offset for symbols that have them.
if (Symbol->Section)
Symbol->Data.SectionNumber = Symbol->Section->Number;
if (Symbol->should_keep()) {
Symbol->setIndex(Header.NumberOfSymbols++);
// Update auxiliary symbol info.
Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
} else {
Symbol->setIndex(-1);
}
}
// Build string table.
for (const auto &S : Sections)
if (S->Name.size() > COFF::NameSize)
Strings.add(S->Name);
for (const auto &S : Symbols)
if (S->should_keep() && S->Name.size() > COFF::NameSize)
Strings.add(S->Name);
Strings.finalize(StringTableBuilder::WinCOFF);
// Set names.
for (const auto &S : Sections)
SetSectionName(*S);
for (auto &S : Symbols)
if (S->should_keep())
SetSymbolName(*S);
// Fixup weak external references.
for (auto &Symbol : Symbols) {
if (Symbol->Other) {
assert(Symbol->getIndex() != -1);
assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
"Symbol's aux symbol must be a Weak External!");
Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->getIndex();
}
}
// Fixup associative COMDAT sections.
for (auto &Section : Sections) {
if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
continue;
const MCSectionCOFF &MCSec = *Section->MCSection;
const MCSymbol *COMDAT = MCSec.getCOMDATSymbol();
assert(COMDAT);
COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
assert(COMDATSymbol);
COFFSection *Assoc = COMDATSymbol->Section;
if (!Assoc)
report_fatal_error(
Twine("Missing associated COMDAT section for section ") +
MCSec.getSectionName());
// Skip this section if the associated section is unused.
if (Assoc->Number == -1)
continue;
Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Assoc->Number;
}
// Assign file offsets to COFF object file structures.
unsigned offset = 0;
if (UseBigObj)
offset += COFF::Header32Size;
else
offset += COFF::Header16Size;
offset += COFF::SectionSize * Header.NumberOfSections;
for (const auto &Section : Asm) {
COFFSection *Sec = SectionMap[&Section];
if (Sec->Number == -1)
continue;
Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
if (IsPhysicalSection(Sec)) {
// Align the section data to a four byte boundary.
offset = RoundUpToAlignment(offset, 4);
Sec->Header.PointerToRawData = offset;
offset += Sec->Header.SizeOfRawData;
}
if (Sec->Relocations.size() > 0) {
bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
if (RelocationsOverflow) {
// Signal overflow by setting NumberOfRelocations to max value. Actual
// size is found in reloc #0. Microsoft tools understand this.
Sec->Header.NumberOfRelocations = 0xffff;
} else {
Sec->Header.NumberOfRelocations = Sec->Relocations.size();
}
Sec->Header.PointerToRelocations = offset;
if (RelocationsOverflow) {
// Reloc #0 will contain actual count, so make room for it.
offset += COFF::RelocationSize;
}
offset += COFF::RelocationSize * Sec->Relocations.size();
for (auto &Relocation : Sec->Relocations) {
assert(Relocation.Symb->getIndex() != -1);
Relocation.Data.SymbolTableIndex = Relocation.Symb->getIndex();
}
}
assert(Sec->Symbol->Aux.size() == 1 &&
"Section's symbol must have one aux!");
AuxSymbol &Aux = Sec->Symbol->Aux[0];
assert(Aux.AuxType == ATSectionDefinition &&
"Section's symbol's aux symbol must be a Section Definition!");
Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
Aux.Aux.SectionDefinition.NumberOfRelocations =
Sec->Header.NumberOfRelocations;
Aux.Aux.SectionDefinition.NumberOfLinenumbers =
Sec->Header.NumberOfLineNumbers;
}
Header.PointerToSymbolTable = offset;
// We want a deterministic output. It looks like GNU as also writes 0 in here.
Header.TimeDateStamp = 0;
// Write it all to disk...
WriteFileHeader(Header);
{
sections::iterator i, ie;
MCAssembler::iterator j, je;
for (auto &Section : Sections) {
if (Section->Number != -1) {
if (Section->Relocations.size() >= 0xffff)
Section->Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
writeSectionHeader(Section->Header);
}
}
for (i = Sections.begin(), ie = Sections.end(), j = Asm.begin(),
je = Asm.end();
(i != ie) && (j != je); ++i, ++j) {
if ((*i)->Number == -1)
continue;
if ((*i)->Header.PointerToRawData != 0) {
assert(OS.tell() <= (*i)->Header.PointerToRawData &&
"Section::PointerToRawData is insane!");
unsigned SectionDataPadding = (*i)->Header.PointerToRawData - OS.tell();
assert(SectionDataPadding < 4 &&
"Should only need at most three bytes of padding!");
WriteZeros(SectionDataPadding);
Asm.writeSectionData(&*j, Layout);
}
if ((*i)->Relocations.size() > 0) {
assert(OS.tell() == (*i)->Header.PointerToRelocations &&
"Section::PointerToRelocations is insane!");
if ((*i)->Relocations.size() >= 0xffff) {
// In case of overflow, write actual relocation count as first
// relocation. Including the synthetic reloc itself (+ 1).
COFF::relocation r;
r.VirtualAddress = (*i)->Relocations.size() + 1;
r.SymbolTableIndex = 0;
r.Type = 0;
WriteRelocation(r);
}
for (const auto &Relocation : (*i)->Relocations)
WriteRelocation(Relocation.Data);
} else
assert((*i)->Header.PointerToRelocations == 0 &&
"Section::PointerToRelocations is insane!");
}
}
assert(OS.tell() == Header.PointerToSymbolTable &&
"Header::PointerToSymbolTable is insane!");
for (auto &Symbol : Symbols)
if (Symbol->getIndex() != -1)
WriteSymbol(*Symbol);
OS.write(Strings.data().data(), Strings.data().size());
}
MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_)
: Machine(Machine_) {}
// Pin the vtable to this file.
void MCWinCOFFObjectTargetWriter::anchor() {}
//------------------------------------------------------------------------------
// WinCOFFObjectWriter factory function
MCObjectWriter *
llvm::createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
raw_pwrite_stream &OS) {
return new WinCOFFObjectWriter(MOTW, OS);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/MachObjectWriter.cpp | //===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCMachObjectWriter.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/Twine.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCAsmLayout.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCFixupKindInfo.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCSymbolMachO.h"
#include "llvm/MC/MCValue.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MachO.h"
#include "llvm/Support/raw_ostream.h"
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "mc"
void MachObjectWriter::reset() {
Relocations.clear();
IndirectSymBase.clear();
StringTable.clear();
LocalSymbolData.clear();
ExternalSymbolData.clear();
UndefinedSymbolData.clear();
MCObjectWriter::reset();
}
bool MachObjectWriter::doesSymbolRequireExternRelocation(const MCSymbol &S) {
// Undefined symbols are always extern.
if (S.isUndefined())
return true;
// References to weak definitions require external relocation entries; the
// definition may not always be the one in the same object file.
if (cast<MCSymbolMachO>(S).isWeakDefinition())
return true;
// Otherwise, we can use an internal relocation.
return false;
}
bool MachObjectWriter::
MachSymbolData::operator<(const MachSymbolData &RHS) const {
return Symbol->getName() < RHS.Symbol->getName();
}
bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
(MCFixupKind) Kind);
return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
}
uint64_t MachObjectWriter::getFragmentAddress(const MCFragment *Fragment,
const MCAsmLayout &Layout) const {
return getSectionAddress(Fragment->getParent()) +
Layout.getFragmentOffset(Fragment);
}
uint64_t MachObjectWriter::getSymbolAddress(const MCSymbol &S,
const MCAsmLayout &Layout) const {
// If this is a variable, then recursively evaluate now.
if (S.isVariable()) {
if (const MCConstantExpr *C =
dyn_cast<const MCConstantExpr>(S.getVariableValue()))
return C->getValue();
MCValue Target;
if (!S.getVariableValue()->evaluateAsRelocatable(Target, &Layout, nullptr))
report_fatal_error("unable to evaluate offset for variable '" +
S.getName() + "'");
// Verify that any used symbols are defined.
if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
report_fatal_error("unable to evaluate offset to undefined symbol '" +
Target.getSymA()->getSymbol().getName() + "'");
if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
report_fatal_error("unable to evaluate offset to undefined symbol '" +
Target.getSymB()->getSymbol().getName() + "'");
uint64_t Address = Target.getConstant();
if (Target.getSymA())
Address += getSymbolAddress(Target.getSymA()->getSymbol(), Layout);
if (Target.getSymB())
Address += getSymbolAddress(Target.getSymB()->getSymbol(), Layout);
return Address;
}
return getSectionAddress(S.getFragment()->getParent()) +
Layout.getSymbolOffset(S);
}
uint64_t MachObjectWriter::getPaddingSize(const MCSection *Sec,
const MCAsmLayout &Layout) const {
uint64_t EndAddr = getSectionAddress(Sec) + Layout.getSectionAddressSize(Sec);
unsigned Next = Sec->getLayoutOrder() + 1;
if (Next >= Layout.getSectionOrder().size())
return 0;
const MCSection &NextSec = *Layout.getSectionOrder()[Next];
if (NextSec.isVirtualSection())
return 0;
return OffsetToAlignment(EndAddr, NextSec.getAlignment());
}
void MachObjectWriter::writeHeader(unsigned NumLoadCommands,
unsigned LoadCommandsSize,
bool SubsectionsViaSymbols) {
uint32_t Flags = 0;
if (SubsectionsViaSymbols)
Flags |= MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
// struct mach_header (28 bytes) or
// struct mach_header_64 (32 bytes)
uint64_t Start = OS.tell();
(void) Start;
write32(is64Bit() ? MachO::MH_MAGIC_64 : MachO::MH_MAGIC);
write32(TargetObjectWriter->getCPUType());
write32(TargetObjectWriter->getCPUSubtype());
write32(MachO::MH_OBJECT);
write32(NumLoadCommands);
write32(LoadCommandsSize);
write32(Flags);
if (is64Bit())
write32(0); // reserved
assert(OS.tell() - Start ==
(is64Bit()?sizeof(MachO::mach_header_64): sizeof(MachO::mach_header)));
}
/// writeSegmentLoadCommand - Write a segment load command.
///
/// \param NumSections The number of sections in this segment.
/// \param SectionDataSize The total size of the sections.
void MachObjectWriter::writeSegmentLoadCommand(unsigned NumSections,
uint64_t VMSize,
uint64_t SectionDataStartOffset,
uint64_t SectionDataSize) {
// struct segment_command (56 bytes) or
// struct segment_command_64 (72 bytes)
uint64_t Start = OS.tell();
(void) Start;
unsigned SegmentLoadCommandSize =
is64Bit() ? sizeof(MachO::segment_command_64):
sizeof(MachO::segment_command);
write32(is64Bit() ? MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT);
write32(SegmentLoadCommandSize +
NumSections * (is64Bit() ? sizeof(MachO::section_64) :
sizeof(MachO::section)));
writeBytes("", 16);
if (is64Bit()) {
write64(0); // vmaddr
write64(VMSize); // vmsize
write64(SectionDataStartOffset); // file offset
write64(SectionDataSize); // file size
} else {
write32(0); // vmaddr
write32(VMSize); // vmsize
write32(SectionDataStartOffset); // file offset
write32(SectionDataSize); // file size
}
// maxprot
write32(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE);
// initprot
write32(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE);
write32(NumSections);
write32(0); // flags
assert(OS.tell() - Start == SegmentLoadCommandSize);
}
void MachObjectWriter::writeSection(const MCAssembler &Asm,
const MCAsmLayout &Layout,
const MCSection &Sec, uint64_t FileOffset,
uint64_t RelocationsStart,
unsigned NumRelocations) {
uint64_t SectionSize = Layout.getSectionAddressSize(&Sec);
const MCSectionMachO &Section = cast<MCSectionMachO>(Sec);
// The offset is unused for virtual sections.
if (Section.isVirtualSection()) {
assert(Layout.getSectionFileSize(&Sec) == 0 && "Invalid file size!");
FileOffset = 0;
}
// struct section (68 bytes) or
// struct section_64 (80 bytes)
uint64_t Start = OS.tell();
(void) Start;
writeBytes(Section.getSectionName(), 16);
writeBytes(Section.getSegmentName(), 16);
if (is64Bit()) {
write64(getSectionAddress(&Sec)); // address
write64(SectionSize); // size
} else {
write32(getSectionAddress(&Sec)); // address
write32(SectionSize); // size
}
write32(FileOffset);
unsigned Flags = Section.getTypeAndAttributes();
if (Section.hasInstructions())
Flags |= MachO::S_ATTR_SOME_INSTRUCTIONS;
assert(isPowerOf2_32(Section.getAlignment()) && "Invalid alignment!");
write32(Log2_32(Section.getAlignment()));
write32(NumRelocations ? RelocationsStart : 0);
write32(NumRelocations);
write32(Flags);
write32(IndirectSymBase.lookup(&Sec)); // reserved1
write32(Section.getStubSize()); // reserved2
if (is64Bit())
write32(0); // reserved3
assert(OS.tell() - Start == (is64Bit() ? sizeof(MachO::section_64) :
sizeof(MachO::section)));
}
void MachObjectWriter::writeSymtabLoadCommand(uint32_t SymbolOffset,
uint32_t NumSymbols,
uint32_t StringTableOffset,
uint32_t StringTableSize) {
// struct symtab_command (24 bytes)
uint64_t Start = OS.tell();
(void) Start;
write32(MachO::LC_SYMTAB);
write32(sizeof(MachO::symtab_command));
write32(SymbolOffset);
write32(NumSymbols);
write32(StringTableOffset);
write32(StringTableSize);
assert(OS.tell() - Start == sizeof(MachO::symtab_command));
}
void MachObjectWriter::writeDysymtabLoadCommand(uint32_t FirstLocalSymbol,
uint32_t NumLocalSymbols,
uint32_t FirstExternalSymbol,
uint32_t NumExternalSymbols,
uint32_t FirstUndefinedSymbol,
uint32_t NumUndefinedSymbols,
uint32_t IndirectSymbolOffset,
uint32_t NumIndirectSymbols) {
// struct dysymtab_command (80 bytes)
uint64_t Start = OS.tell();
(void) Start;
write32(MachO::LC_DYSYMTAB);
write32(sizeof(MachO::dysymtab_command));
write32(FirstLocalSymbol);
write32(NumLocalSymbols);
write32(FirstExternalSymbol);
write32(NumExternalSymbols);
write32(FirstUndefinedSymbol);
write32(NumUndefinedSymbols);
write32(0); // tocoff
write32(0); // ntoc
write32(0); // modtaboff
write32(0); // nmodtab
write32(0); // extrefsymoff
write32(0); // nextrefsyms
write32(IndirectSymbolOffset);
write32(NumIndirectSymbols);
write32(0); // extreloff
write32(0); // nextrel
write32(0); // locreloff
write32(0); // nlocrel
assert(OS.tell() - Start == sizeof(MachO::dysymtab_command));
}
MachObjectWriter::MachSymbolData *
MachObjectWriter::findSymbolData(const MCSymbol &Sym) {
for (auto *SymbolData :
{&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
for (MachSymbolData &Entry : *SymbolData)
if (Entry.Symbol == &Sym)
return &Entry;
return nullptr;
}
const MCSymbol &MachObjectWriter::findAliasedSymbol(const MCSymbol &Sym) const {
const MCSymbol *S = &Sym;
while (S->isVariable()) {
const MCExpr *Value = S->getVariableValue();
const auto *Ref = dyn_cast<MCSymbolRefExpr>(Value);
if (!Ref)
return *S;
S = &Ref->getSymbol();
}
return *S;
}
void MachObjectWriter::writeNlist(MachSymbolData &MSD,
const MCAsmLayout &Layout) {
const MCSymbol *Symbol = MSD.Symbol;
const MCSymbol &Data = *Symbol;
const MCSymbol *AliasedSymbol = &findAliasedSymbol(*Symbol);
uint8_t SectionIndex = MSD.SectionIndex;
uint8_t Type = 0;
uint64_t Address = 0;
bool IsAlias = Symbol != AliasedSymbol;
const MCSymbol &OrigSymbol = *Symbol;
MachSymbolData *AliaseeInfo;
if (IsAlias) {
AliaseeInfo = findSymbolData(*AliasedSymbol);
if (AliaseeInfo)
SectionIndex = AliaseeInfo->SectionIndex;
Symbol = AliasedSymbol;
// FIXME: Should this update Data as well? Do we need OrigSymbol at all?
}
// Set the N_TYPE bits. See <mach-o/nlist.h>.
//
// FIXME: Are the prebound or indirect fields possible here?
if (IsAlias && Symbol->isUndefined())
Type = MachO::N_INDR;
else if (Symbol->isUndefined())
Type = MachO::N_UNDF;
else if (Symbol->isAbsolute())
Type = MachO::N_ABS;
else
Type = MachO::N_SECT;
// FIXME: Set STAB bits.
if (Data.isPrivateExtern())
Type |= MachO::N_PEXT;
// Set external bit.
if (Data.isExternal() || (!IsAlias && Symbol->isUndefined()))
Type |= MachO::N_EXT;
// Compute the symbol address.
if (IsAlias && Symbol->isUndefined())
Address = AliaseeInfo->StringIndex;
else if (Symbol->isDefined())
Address = getSymbolAddress(OrigSymbol, Layout);
else if (Symbol->isCommon()) {
// Common symbols are encoded with the size in the address
// field, and their alignment in the flags.
Address = Symbol->getCommonSize();
}
// struct nlist (12 bytes)
write32(MSD.StringIndex);
write8(Type);
write8(SectionIndex);
// The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
// value.
write16(cast<MCSymbolMachO>(Symbol)->getEncodedFlags());
if (is64Bit())
write64(Address);
else
write32(Address);
}
void MachObjectWriter::writeLinkeditLoadCommand(uint32_t Type,
uint32_t DataOffset,
uint32_t DataSize) {
uint64_t Start = OS.tell();
(void) Start;
write32(Type);
write32(sizeof(MachO::linkedit_data_command));
write32(DataOffset);
write32(DataSize);
assert(OS.tell() - Start == sizeof(MachO::linkedit_data_command));
}
static unsigned ComputeLinkerOptionsLoadCommandSize(
const std::vector<std::string> &Options, bool is64Bit)
{
unsigned Size = sizeof(MachO::linker_option_command);
for (const std::string &Option : Options)
Size += Option.size() + 1;
return RoundUpToAlignment(Size, is64Bit ? 8 : 4);
}
void MachObjectWriter::writeLinkerOptionsLoadCommand(
const std::vector<std::string> &Options)
{
unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit());
uint64_t Start = OS.tell();
(void) Start;
write32(MachO::LC_LINKER_OPTION);
write32(Size);
write32(Options.size());
uint64_t BytesWritten = sizeof(MachO::linker_option_command);
for (const std::string &Option : Options) {
// Write each string, including the null byte.
writeBytes(Option.c_str(), Option.size() + 1);
BytesWritten += Option.size() + 1;
}
// Pad to a multiple of the pointer size.
writeBytes("", OffsetToAlignment(BytesWritten, is64Bit() ? 8 : 4));
assert(OS.tell() - Start == Size);
}
void MachObjectWriter::recordRelocation(MCAssembler &Asm,
const MCAsmLayout &Layout,
const MCFragment *Fragment,
const MCFixup &Fixup, MCValue Target,
bool &IsPCRel, uint64_t &FixedValue) {
TargetObjectWriter->recordRelocation(this, Asm, Layout, Fragment, Fixup,
Target, FixedValue);
}
void MachObjectWriter::bindIndirectSymbols(MCAssembler &Asm) {
// This is the point where 'as' creates actual symbols for indirect symbols
// (in the following two passes). It would be easier for us to do this sooner
// when we see the attribute, but that makes getting the order in the symbol
// table much more complicated than it is worth.
//
// FIXME: Revisit this when the dust settles.
// Report errors for use of .indirect_symbol not in a symbol pointer section
// or stub section.
for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
ie = Asm.indirect_symbol_end(); it != ie; ++it) {
const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
Section.getType() != MachO::S_SYMBOL_STUBS) {
MCSymbol &Symbol = *it->Symbol;
report_fatal_error("indirect symbol '" + Symbol.getName() +
"' not in a symbol pointer or stub section");
}
}
// Bind non-lazy symbol pointers first.
unsigned IndirectIndex = 0;
for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS)
continue;
// Initialize the section indirect symbol base, if necessary.
IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
Asm.registerSymbol(*it->Symbol);
}
// Then lazy symbol pointers and symbol stubs.
IndirectIndex = 0;
for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
if (Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
Section.getType() != MachO::S_SYMBOL_STUBS)
continue;
// Initialize the section indirect symbol base, if necessary.
IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
// Set the symbol type to undefined lazy, but only on construction.
//
// FIXME: Do not hardcode.
bool Created;
Asm.registerSymbol(*it->Symbol, &Created);
if (Created)
cast<MCSymbolMachO>(it->Symbol)->setReferenceTypeUndefinedLazy(true);
}
}
/// computeSymbolTable - Compute the symbol table data
void MachObjectWriter::computeSymbolTable(
MCAssembler &Asm, std::vector<MachSymbolData> &LocalSymbolData,
std::vector<MachSymbolData> &ExternalSymbolData,
std::vector<MachSymbolData> &UndefinedSymbolData) {
// Build section lookup table.
DenseMap<const MCSection*, uint8_t> SectionIndexMap;
unsigned Index = 1;
for (MCAssembler::iterator it = Asm.begin(),
ie = Asm.end(); it != ie; ++it, ++Index)
SectionIndexMap[&*it] = Index;
assert(Index <= 256 && "Too many sections!");
// Build the string table.
for (const MCSymbol &Symbol : Asm.symbols()) {
if (!Asm.isSymbolLinkerVisible(Symbol))
continue;
StringTable.add(Symbol.getName());
}
StringTable.finalize(StringTableBuilder::MachO);
// Build the symbol arrays but only for non-local symbols.
//
// The particular order that we collect and then sort the symbols is chosen to
// match 'as'. Even though it doesn't matter for correctness, this is
// important for letting us diff .o files.
for (const MCSymbol &Symbol : Asm.symbols()) {
// Ignore non-linker visible symbols.
if (!Asm.isSymbolLinkerVisible(Symbol))
continue;
if (!Symbol.isExternal() && !Symbol.isUndefined())
continue;
MachSymbolData MSD;
MSD.Symbol = &Symbol;
MSD.StringIndex = StringTable.getOffset(Symbol.getName());
if (Symbol.isUndefined()) {
MSD.SectionIndex = 0;
UndefinedSymbolData.push_back(MSD);
} else if (Symbol.isAbsolute()) {
MSD.SectionIndex = 0;
ExternalSymbolData.push_back(MSD);
} else {
MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
assert(MSD.SectionIndex && "Invalid section index!");
ExternalSymbolData.push_back(MSD);
}
}
// Now add the data for local symbols.
for (const MCSymbol &Symbol : Asm.symbols()) {
// Ignore non-linker visible symbols.
if (!Asm.isSymbolLinkerVisible(Symbol))
continue;
if (Symbol.isExternal() || Symbol.isUndefined())
continue;
MachSymbolData MSD;
MSD.Symbol = &Symbol;
MSD.StringIndex = StringTable.getOffset(Symbol.getName());
if (Symbol.isAbsolute()) {
MSD.SectionIndex = 0;
LocalSymbolData.push_back(MSD);
} else {
MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
assert(MSD.SectionIndex && "Invalid section index!");
LocalSymbolData.push_back(MSD);
}
}
// External and undefined symbols are required to be in lexicographic order.
std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
// Set the symbol indices.
Index = 0;
for (auto *SymbolData :
{&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
for (MachSymbolData &Entry : *SymbolData)
Entry.Symbol->setIndex(Index++);
for (const MCSection &Section : Asm) {
for (RelAndSymbol &Rel : Relocations[&Section]) {
if (!Rel.Sym)
continue;
// Set the Index and the IsExtern bit.
unsigned Index = Rel.Sym->getIndex();
assert(isInt<24>(Index));
if (IsLittleEndian)
Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (~0U << 24)) | Index | (1 << 27);
else
Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) | Index << 8 | (1 << 4);
}
}
}
void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
const MCAsmLayout &Layout) {
uint64_t StartAddress = 0;
for (const MCSection *Sec : Layout.getSectionOrder()) {
StartAddress = RoundUpToAlignment(StartAddress, Sec->getAlignment());
SectionAddress[Sec] = StartAddress;
StartAddress += Layout.getSectionAddressSize(Sec);
// Explicitly pad the section to match the alignment requirements of the
// following one. This is for 'gas' compatibility, it shouldn't
/// strictly be necessary.
StartAddress += getPaddingSize(Sec, Layout);
}
}
void MachObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
const MCAsmLayout &Layout) {
computeSectionAddresses(Asm, Layout);
// Create symbol data for any indirect symbols.
bindIndirectSymbols(Asm);
}
bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
bool InSet, bool IsPCRel) const {
if (InSet)
return true;
// The effective address is
// addr(atom(A)) + offset(A)
// - addr(atom(B)) - offset(B)
// and the offsets are not relocatable, so the fixup is fully resolved when
// addr(atom(A)) - addr(atom(B)) == 0.
const MCSymbol &SA = findAliasedSymbol(SymA);
const MCSection &SecA = SA.getSection();
const MCSection &SecB = *FB.getParent();
if (IsPCRel) {
// The simple (Darwin, except on x86_64) way of dealing with this was to
// assume that any reference to a temporary symbol *must* be a temporary
// symbol in the same atom, unless the sections differ. Therefore, any PCrel
// relocation to a temporary symbol (in the same section) is fully
// resolved. This also works in conjunction with absolutized .set, which
// requires the compiler to use .set to absolutize the differences between
// symbols which the compiler knows to be assembly time constants, so we
// don't need to worry about considering symbol differences fully resolved.
//
// If the file isn't using sub-sections-via-symbols, we can make the
// same assumptions about any symbol that we normally make about
// assembler locals.
bool hasReliableSymbolDifference = isX86_64();
if (!hasReliableSymbolDifference) {
if (!SA.isInSection() || &SecA != &SecB ||
(!SA.isTemporary() && FB.getAtom() != SA.getFragment()->getAtom() &&
Asm.getSubsectionsViaSymbols()))
return false;
return true;
}
// For Darwin x86_64, there is one special case when the reference IsPCRel.
// If the fragment with the reference does not have a base symbol but meets
// the simple way of dealing with this, in that it is a temporary symbol in
// the same atom then it is assumed to be fully resolved. This is needed so
// a relocation entry is not created and so the static linker does not
// mess up the reference later.
else if(!FB.getAtom() &&
SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
return true;
}
}
// If they are not in the same section, we can't compute the diff.
if (&SecA != &SecB)
return false;
const MCFragment *FA = SA.getFragment();
// Bail if the symbol has no fragment.
if (!FA)
return false;
// If the atoms are the same, they are guaranteed to have the same address.
if (FA->getAtom() == FB.getAtom())
return true;
// Otherwise, we can't prove this is fully resolved.
return false;
}
void MachObjectWriter::writeObject(MCAssembler &Asm,
const MCAsmLayout &Layout) {
// Compute symbol table information and bind symbol indices.
computeSymbolTable(Asm, LocalSymbolData, ExternalSymbolData,
UndefinedSymbolData);
unsigned NumSections = Asm.size();
const MCAssembler::VersionMinInfoType &VersionInfo =
Layout.getAssembler().getVersionMinInfo();
// The section data starts after the header, the segment load command (and
// section headers) and the symbol table.
unsigned NumLoadCommands = 1;
uint64_t LoadCommandsSize = is64Bit() ?
sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
// Add the deployment target version info load command size, if used.
if (VersionInfo.Major != 0) {
++NumLoadCommands;
LoadCommandsSize += sizeof(MachO::version_min_command);
}
// Add the data-in-code load command size, if used.
unsigned NumDataRegions = Asm.getDataRegions().size();
if (NumDataRegions) {
++NumLoadCommands;
LoadCommandsSize += sizeof(MachO::linkedit_data_command);
}
// Add the loh load command size, if used.
uint64_t LOHRawSize = Asm.getLOHContainer().getEmitSize(*this, Layout);
uint64_t LOHSize = RoundUpToAlignment(LOHRawSize, is64Bit() ? 8 : 4);
if (LOHSize) {
++NumLoadCommands;
LoadCommandsSize += sizeof(MachO::linkedit_data_command);
}
// Add the symbol table load command sizes, if used.
unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
UndefinedSymbolData.size();
if (NumSymbols) {
NumLoadCommands += 2;
LoadCommandsSize += (sizeof(MachO::symtab_command) +
sizeof(MachO::dysymtab_command));
}
// Add the linker option load commands sizes.
for (const auto &Option : Asm.getLinkerOptions()) {
++NumLoadCommands;
LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(Option, is64Bit());
}
// Compute the total size of the section data, as well as its file size and vm
// size.
uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) :
sizeof(MachO::mach_header)) + LoadCommandsSize;
uint64_t SectionDataSize = 0;
uint64_t SectionDataFileSize = 0;
uint64_t VMSize = 0;
for (const MCSection &Sec : Asm) {
uint64_t Address = getSectionAddress(&Sec);
uint64_t Size = Layout.getSectionAddressSize(&Sec);
uint64_t FileSize = Layout.getSectionFileSize(&Sec);
FileSize += getPaddingSize(&Sec, Layout);
VMSize = std::max(VMSize, Address + Size);
if (Sec.isVirtualSection())
continue;
SectionDataSize = std::max(SectionDataSize, Address + Size);
SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
}
// The section data is padded to 4 bytes.
//
// FIXME: Is this machine dependent?
unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
SectionDataFileSize += SectionDataPadding;
// Write the prolog, starting with the header and load command...
writeHeader(NumLoadCommands, LoadCommandsSize,
Asm.getSubsectionsViaSymbols());
writeSegmentLoadCommand(NumSections, VMSize,
SectionDataStart, SectionDataSize);
// ... and then the section headers.
uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
for (const MCSection &Sec : Asm) {
std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
unsigned NumRelocs = Relocs.size();
uint64_t SectionStart = SectionDataStart + getSectionAddress(&Sec);
writeSection(Asm, Layout, Sec, SectionStart, RelocTableEnd, NumRelocs);
RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
}
// Write out the deployment target information, if it's available.
if (VersionInfo.Major != 0) {
assert(VersionInfo.Update < 256 && "unencodable update target version");
assert(VersionInfo.Minor < 256 && "unencodable minor target version");
assert(VersionInfo.Major < 65536 && "unencodable major target version");
uint32_t EncodedVersion = VersionInfo.Update | (VersionInfo.Minor << 8) |
(VersionInfo.Major << 16);
write32(VersionInfo.Kind == MCVM_OSXVersionMin ? MachO::LC_VERSION_MIN_MACOSX :
MachO::LC_VERSION_MIN_IPHONEOS);
write32(sizeof(MachO::version_min_command));
write32(EncodedVersion);
write32(0); // reserved.
}
// Write the data-in-code load command, if used.
uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
if (NumDataRegions) {
uint64_t DataRegionsOffset = RelocTableEnd;
uint64_t DataRegionsSize = NumDataRegions * 8;
writeLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
DataRegionsSize);
}
// Write the loh load command, if used.
uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
if (LOHSize)
writeLinkeditLoadCommand(MachO::LC_LINKER_OPTIMIZATION_HINT,
DataInCodeTableEnd, LOHSize);
// Write the symbol table load command, if used.
if (NumSymbols) {
unsigned FirstLocalSymbol = 0;
unsigned NumLocalSymbols = LocalSymbolData.size();
unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
unsigned NumExternalSymbols = ExternalSymbolData.size();
unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
unsigned NumSymTabSymbols =
NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
uint64_t IndirectSymbolOffset = 0;
// If used, the indirect symbols are written after the section data.
if (NumIndirectSymbols)
IndirectSymbolOffset = LOHTableEnd;
// The symbol table is written after the indirect symbol data.
uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
// The string table is written after symbol table.
uint64_t StringTableOffset =
SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
sizeof(MachO::nlist_64) :
sizeof(MachO::nlist));
writeSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
StringTableOffset, StringTable.data().size());
writeDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
FirstExternalSymbol, NumExternalSymbols,
FirstUndefinedSymbol, NumUndefinedSymbols,
IndirectSymbolOffset, NumIndirectSymbols);
}
// Write the linker options load commands.
for (const auto &Option : Asm.getLinkerOptions())
writeLinkerOptionsLoadCommand(Option);
// Write the actual section data.
for (const MCSection &Sec : Asm) {
Asm.writeSectionData(&Sec, Layout);
uint64_t Pad = getPaddingSize(&Sec, Layout);
WriteZeros(Pad);
}
// Write the extra padding.
WriteZeros(SectionDataPadding);
// Write the relocation entries.
for (const MCSection &Sec : Asm) {
// Write the section relocation entries, in reverse order to match 'as'
// (approximately, the exact algorithm is more complicated than this).
std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
for (const RelAndSymbol &Rel : make_range(Relocs.rbegin(), Relocs.rend())) {
write32(Rel.MRE.r_word0);
write32(Rel.MRE.r_word1);
}
}
// Write out the data-in-code region payload, if there is one.
for (MCAssembler::const_data_region_iterator
it = Asm.data_region_begin(), ie = Asm.data_region_end();
it != ie; ++it) {
const DataRegionData *Data = &(*it);
uint64_t Start = getSymbolAddress(*Data->Start, Layout);
uint64_t End = getSymbolAddress(*Data->End, Layout);
DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
<< " start: " << Start << "(" << Data->Start->getName() << ")"
<< " end: " << End << "(" << Data->End->getName() << ")"
<< " size: " << End - Start
<< "\n");
write32(Start);
write16(End - Start);
write16(Data->Kind);
}
// Write out the loh commands, if there is one.
if (LOHSize) {
#ifndef NDEBUG
unsigned Start = OS.tell();
#endif
Asm.getLOHContainer().emit(*this, Layout);
// Pad to a multiple of the pointer size.
writeBytes("", OffsetToAlignment(LOHRawSize, is64Bit() ? 8 : 4));
assert(OS.tell() - Start == LOHSize);
}
// Write the symbol table data, if used.
if (NumSymbols) {
// Write the indirect symbol entries.
for (MCAssembler::const_indirect_symbol_iterator
it = Asm.indirect_symbol_begin(),
ie = Asm.indirect_symbol_end(); it != ie; ++it) {
// Indirect symbols in the non-lazy symbol pointer section have some
// special handling.
const MCSectionMachO &Section =
static_cast<const MCSectionMachO &>(*it->Section);
if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) {
// If this symbol is defined and internal, mark it as such.
if (it->Symbol->isDefined() && !it->Symbol->isExternal()) {
uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL;
if (it->Symbol->isAbsolute())
Flags |= MachO::INDIRECT_SYMBOL_ABS;
write32(Flags);
continue;
}
}
write32(it->Symbol->getIndex());
}
// FIXME: Check that offsets match computed ones.
// Write the symbol table entries.
for (auto *SymbolData :
{&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
for (MachSymbolData &Entry : *SymbolData)
writeNlist(Entry, Layout);
// Write the string table.
OS << StringTable.data();
}
}
MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
raw_pwrite_stream &OS,
bool IsLittleEndian) {
return new MachObjectWriter(MOTW, OS, IsLittleEndian);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/MCSymbol.cpp | //===- lib/MC/MCSymbol.cpp - MCSymbol implementation ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
// Sentinel value for the absolute pseudo section.
MCSection *MCSymbol::AbsolutePseudoSection = reinterpret_cast<MCSection *>(1);
void *MCSymbol::operator new(size_t s, const StringMapEntry<bool> *Name,
MCContext &Ctx) {
// We may need more space for a Name to account for alignment. So allocate
// space for the storage type and not the name pointer.
size_t Size = s + (Name ? sizeof(NameEntryStorageTy) : 0);
// For safety, ensure that the alignment of a pointer is enough for an
// MCSymbol. This also ensures we don't need padding between the name and
// symbol.
static_assert((unsigned)AlignOf<MCSymbol>::Alignment <=
AlignOf<NameEntryStorageTy>::Alignment,
"Bad alignment of MCSymbol");
void *Storage = Ctx.allocate(Size, alignOf<NameEntryStorageTy>());
NameEntryStorageTy *Start = static_cast<NameEntryStorageTy*>(Storage);
NameEntryStorageTy *End = Start + (Name ? 1 : 0);
return End;
}
void MCSymbol::setVariableValue(const MCExpr *Value) {
assert(!IsUsed && "Cannot set a variable that has already been used.");
assert(Value && "Invalid variable value!");
assert((SymbolContents == SymContentsUnset ||
SymbolContents == SymContentsVariable) &&
"Cannot give common/offset symbol a variable value");
this->Value = Value;
SymbolContents = SymContentsVariable;
setUndefined();
}
void MCSymbol::print(raw_ostream &OS, const MCAsmInfo *MAI) const {
// The name for this MCSymbol is required to be a valid target name. However,
// some targets support quoting names with funny characters. If the name
// contains a funny character, then print it quoted.
StringRef Name = getName();
if (!MAI || MAI->isValidUnquotedName(Name)) {
OS << Name;
return;
}
if (MAI && !MAI->supportsNameQuoting())
report_fatal_error("Symbol name with unsupported characters");
OS << '"';
for (char C : Name) {
if (C == '\n')
OS << "\\n";
else if (C == '"')
OS << "\\\"";
else
OS << C;
}
OS << '"';
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
void MCSymbol::dump() const { dbgs() << *this; }
#endif
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/MCDwarf.cpp | //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCDwarf.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Config/config.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCObjectStreamer.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
// Given a special op, return the address skip amount (in units of
// DWARF2_LINE_MIN_INSN_LENGTH.
#define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
// The maximum address skip amount that can be encoded with a special op.
#define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255)
// First special line opcode - leave room for the standard opcodes.
// Note: If you want to change this, you'll have to update the
// "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
#define DWARF2_LINE_OPCODE_BASE 13
// Minimum line offset in a special line info. opcode. This value
// was chosen to give a reasonable range of values.
#define DWARF2_LINE_BASE -5
// Range of line offsets in a special line info. opcode.
#define DWARF2_LINE_RANGE 14
static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
if (MinInsnLength == 1)
return AddrDelta;
if (AddrDelta % MinInsnLength != 0) {
// TODO: report this error, but really only once.
;
}
return AddrDelta / MinInsnLength;
}
//
// This is called when an instruction is assembled into the specified section
// and if there is information from the last .loc directive that has yet to have
// a line entry made for it is made.
//
void MCLineEntry::Make(MCObjectStreamer *MCOS, MCSection *Section) {
if (!MCOS->getContext().getDwarfLocSeen())
return;
// Create a symbol at in the current section for use in the line entry.
MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
// Set the value of the symbol to use for the MCLineEntry.
MCOS->EmitLabel(LineSym);
// Get the current .loc info saved in the context.
const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
// Create a (local) line entry with the symbol and the current .loc info.
MCLineEntry LineEntry(LineSym, DwarfLoc);
// clear DwarfLocSeen saying the current .loc info is now used.
MCOS->getContext().clearDwarfLocSeen();
// Add the line entry to this section's entries.
MCOS->getContext()
.getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())
.getMCLineSections()
.addLineEntry(LineEntry, Section);
}
//
// This helper routine returns an expression of End - Start + IntVal .
//
static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
const MCSymbol &Start,
const MCSymbol &End,
int IntVal) {
MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
const MCExpr *Res =
MCSymbolRefExpr::create(&End, Variant, MCOS.getContext());
const MCExpr *RHS =
MCSymbolRefExpr::create(&Start, Variant, MCOS.getContext());
const MCExpr *Res1 =
MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
const MCExpr *Res2 =
MCConstantExpr::create(IntVal, MCOS.getContext());
const MCExpr *Res3 =
MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
return Res3;
}
//
// This emits the Dwarf line table for the specified section from the entries
// in the LineSection.
//
static inline void
EmitDwarfLineTable(MCObjectStreamer *MCOS, MCSection *Section,
const MCLineSection::MCLineEntryCollection &LineEntries) {
unsigned FileNum = 1;
unsigned LastLine = 1;
unsigned Column = 0;
unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
unsigned Isa = 0;
unsigned Discriminator = 0;
MCSymbol *LastLabel = nullptr;
// Loop through each MCLineEntry and encode the dwarf line number table.
for (auto it = LineEntries.begin(),
ie = LineEntries.end();
it != ie; ++it) {
if (FileNum != it->getFileNum()) {
FileNum = it->getFileNum();
MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
MCOS->EmitULEB128IntValue(FileNum);
}
if (Column != it->getColumn()) {
Column = it->getColumn();
MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
MCOS->EmitULEB128IntValue(Column);
}
if (Discriminator != it->getDiscriminator()) {
Discriminator = it->getDiscriminator();
unsigned Size = getULEB128Size(Discriminator);
MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
MCOS->EmitULEB128IntValue(Size + 1);
MCOS->EmitIntValue(dwarf::DW_LNE_set_discriminator, 1);
MCOS->EmitULEB128IntValue(Discriminator);
}
if (Isa != it->getIsa()) {
Isa = it->getIsa();
MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
MCOS->EmitULEB128IntValue(Isa);
}
if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
Flags = it->getFlags();
MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
}
if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
MCSymbol *Label = it->getLabel();
// At this point we want to emit/create the sequence to encode the delta in
// line numbers and the increment of the address from the previous Label
// and the current Label.
const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
asmInfo->getPointerSize());
LastLine = it->getLine();
LastLabel = Label;
}
// Emit a DW_LNE_end_sequence for the end of the section.
// Use the section end label to compute the address delta and use INT64_MAX
// as the line delta which is the signal that this is actually a
// DW_LNE_end_sequence.
MCSymbol *SectionEnd = MCOS->endSection(Section);
// Switch back the dwarf line section, in case endSection had to switch the
// section.
MCContext &Ctx = MCOS->getContext();
MCOS->SwitchSection(Ctx.getObjectFileInfo()->getDwarfLineSection());
const MCAsmInfo *AsmInfo = Ctx.getAsmInfo();
MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
AsmInfo->getPointerSize());
}
//
// This emits the Dwarf file and the line tables.
//
void MCDwarfLineTable::Emit(MCObjectStreamer *MCOS) {
MCContext &context = MCOS->getContext();
auto &LineTables = context.getMCDwarfLineTables();
// Bail out early so we don't switch to the debug_line section needlessly and
// in doing so create an unnecessary (if empty) section.
if (LineTables.empty())
return;
// Switch to the section where the table will be emitted into.
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
// Handle the rest of the Compile Units.
for (const auto &CUIDTablePair : LineTables)
CUIDTablePair.second.EmitCU(MCOS);
}
void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS) const {
MCOS.EmitLabel(Header.Emit(&MCOS, None).second);
}
std::pair<MCSymbol *, MCSymbol *> MCDwarfLineTableHeader::Emit(MCStreamer *MCOS) const {
static const char StandardOpcodeLengths[] = {
0, // length of DW_LNS_copy
1, // length of DW_LNS_advance_pc
1, // length of DW_LNS_advance_line
1, // length of DW_LNS_set_file
1, // length of DW_LNS_set_column
0, // length of DW_LNS_negate_stmt
0, // length of DW_LNS_set_basic_block
0, // length of DW_LNS_const_add_pc
1, // length of DW_LNS_fixed_advance_pc
0, // length of DW_LNS_set_prologue_end
0, // length of DW_LNS_set_epilogue_begin
1 // DW_LNS_set_isa
};
assert(array_lengthof(StandardOpcodeLengths) ==
(DWARF2_LINE_OPCODE_BASE - 1));
return Emit(MCOS, StandardOpcodeLengths);
}
static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) {
MCContext &Context = OS.getContext();
assert(!isa<MCSymbolRefExpr>(Expr));
if (Context.getAsmInfo()->hasAggressiveSymbolFolding())
return Expr;
MCSymbol *ABS = Context.createTempSymbol();
OS.EmitAssignment(ABS, Expr);
return MCSymbolRefExpr::create(ABS, Context);
}
static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) {
const MCExpr *ABS = forceExpAbs(OS, Value);
OS.EmitValue(ABS, Size);
}
std::pair<MCSymbol *, MCSymbol *>
MCDwarfLineTableHeader::Emit(MCStreamer *MCOS,
ArrayRef<char> StandardOpcodeLengths) const {
MCContext &context = MCOS->getContext();
// Create a symbol at the beginning of the line table.
MCSymbol *LineStartSym = Label;
if (!LineStartSym)
LineStartSym = context.createTempSymbol();
// Set the value of the symbol, as we are at the start of the line table.
MCOS->EmitLabel(LineStartSym);
// Create a symbol for the end of the section (to be set when we get there).
MCSymbol *LineEndSym = context.createTempSymbol();
// The first 4 bytes is the total length of the information for this
// compilation unit (not including these 4 bytes for the length).
emitAbsValue(*MCOS,
MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym, 4), 4);
// Next 2 bytes is the Version, which is Dwarf 2.
MCOS->EmitIntValue(2, 2);
// Create a symbol for the end of the prologue (to be set when we get there).
MCSymbol *ProEndSym = context.createTempSymbol(); // Lprologue_end
// Length of the prologue, is the next 4 bytes. Which is the start of the
// section to the end of the prologue. Not including the 4 bytes for the
// total length, the 2 bytes for the version, and these 4 bytes for the
// length of the prologue.
emitAbsValue(
*MCOS,
MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym, (4 + 2 + 4)), 4);
// Parameters of the state machine, are next.
MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1);
MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
MCOS->EmitIntValue(StandardOpcodeLengths.size() + 1, 1);
// Standard opcode lengths
for (char Length : StandardOpcodeLengths)
MCOS->EmitIntValue(Length, 1);
// Put out the directory and file tables.
// First the directory table.
for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName
MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
}
MCOS->EmitIntValue(0, 1); // Terminate the directory list
// Second the file table.
for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
assert(!MCDwarfFiles[i].Name.empty());
MCOS->EmitBytes(MCDwarfFiles[i].Name); // FileName
MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
// the Directory num
MCOS->EmitULEB128IntValue(MCDwarfFiles[i].DirIndex);
MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
MCOS->EmitIntValue(0, 1); // filesize (always 0)
}
MCOS->EmitIntValue(0, 1); // Terminate the file list
// This is the end of the prologue, so set the value of the symbol at the
// end of the prologue (that was used in a previous expression).
MCOS->EmitLabel(ProEndSym);
return std::make_pair(LineStartSym, LineEndSym);
}
void MCDwarfLineTable::EmitCU(MCObjectStreamer *MCOS) const {
MCSymbol *LineEndSym = Header.Emit(MCOS).second;
// Put out the line tables.
for (const auto &LineSec : MCLineSections.getMCLineEntries())
EmitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
// This is the end of the section, so set the value of the symbol at the end
// of this section (that was used in a previous expression).
MCOS->EmitLabel(LineEndSym);
}
unsigned MCDwarfLineTable::getFile(StringRef &Directory, StringRef &FileName,
unsigned FileNumber) {
return Header.getFile(Directory, FileName, FileNumber);
}
unsigned MCDwarfLineTableHeader::getFile(StringRef &Directory,
StringRef &FileName,
unsigned FileNumber) {
if (Directory == CompilationDir)
Directory = "";
if (FileName.empty()) {
FileName = "<stdin>";
Directory = "";
}
assert(!FileName.empty());
if (FileNumber == 0) {
FileNumber = SourceIdMap.size() + 1;
assert((MCDwarfFiles.empty() || FileNumber == MCDwarfFiles.size()) &&
"Don't mix autonumbered and explicit numbered line table usage");
SmallString<256> Buffer;
auto IterBool = SourceIdMap.insert(
std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer),
FileNumber));
if (!IterBool.second)
return IterBool.first->second;
}
// Make space for this FileNumber in the MCDwarfFiles vector if needed.
MCDwarfFiles.resize(FileNumber + 1);
// Get the new MCDwarfFile slot for this FileNumber.
MCDwarfFile &File = MCDwarfFiles[FileNumber];
// It is an error to use see the same number more than once.
if (!File.Name.empty())
return 0;
if (Directory.empty()) {
// Separate the directory part from the basename of the FileName.
StringRef tFileName = sys::path::filename(FileName);
if (!tFileName.empty()) {
Directory = sys::path::parent_path(FileName);
if (!Directory.empty())
FileName = tFileName;
}
}
// Find or make an entry in the MCDwarfDirs vector for this Directory.
// Capture directory name.
unsigned DirIndex;
if (Directory.empty()) {
// For FileNames with no directories a DirIndex of 0 is used.
DirIndex = 0;
} else {
DirIndex = 0;
for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
if (Directory == MCDwarfDirs[DirIndex])
break;
}
if (DirIndex >= MCDwarfDirs.size())
MCDwarfDirs.push_back(Directory);
// The DirIndex is one based, as DirIndex of 0 is used for FileNames with
// no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
// directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
// are stored at MCDwarfFiles[FileNumber].Name .
DirIndex++;
}
File.Name = FileName;
File.DirIndex = DirIndex;
// return the allocated FileNumber.
return FileNumber;
}
/// Utility function to emit the encoding to a streamer.
void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
uint64_t AddrDelta) {
MCContext &Context = MCOS->getContext();
SmallString<256> Tmp;
raw_svector_ostream OS(Tmp);
MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
MCOS->EmitBytes(OS.str());
}
/// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
void MCDwarfLineAddr::Encode(MCContext &Context, int64_t LineDelta,
uint64_t AddrDelta, raw_ostream &OS) {
uint64_t Temp, Opcode;
bool NeedCopy = false;
// Scale the address delta by the minimum instruction length.
AddrDelta = ScaleAddrDelta(Context, AddrDelta);
// A LineDelta of INT64_MAX is a signal that this is actually a
// DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
// end_sequence to emit the matrix entry.
if (LineDelta == INT64_MAX) {
if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
OS << char(dwarf::DW_LNS_const_add_pc);
else if (AddrDelta) {
OS << char(dwarf::DW_LNS_advance_pc);
encodeULEB128(AddrDelta, OS);
}
OS << char(dwarf::DW_LNS_extended_op);
OS << char(1);
OS << char(dwarf::DW_LNE_end_sequence);
return;
}
// Bias the line delta by the base.
Temp = LineDelta - DWARF2_LINE_BASE;
// If the line increment is out of range of a special opcode, we must encode
// it with DW_LNS_advance_line.
if (Temp >= DWARF2_LINE_RANGE) {
OS << char(dwarf::DW_LNS_advance_line);
encodeSLEB128(LineDelta, OS);
LineDelta = 0;
Temp = 0 - DWARF2_LINE_BASE;
NeedCopy = true;
}
// Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
if (LineDelta == 0 && AddrDelta == 0) {
OS << char(dwarf::DW_LNS_copy);
return;
}
// Bias the opcode by the special opcode base.
Temp += DWARF2_LINE_OPCODE_BASE;
// Avoid overflow when addr_delta is large.
if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
// Try using a special opcode.
Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
if (Opcode <= 255) {
OS << char(Opcode);
return;
}
// Try using DW_LNS_const_add_pc followed by special op.
Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
if (Opcode <= 255) {
OS << char(dwarf::DW_LNS_const_add_pc);
OS << char(Opcode);
return;
}
}
// Otherwise use DW_LNS_advance_pc.
OS << char(dwarf::DW_LNS_advance_pc);
encodeULEB128(AddrDelta, OS);
if (NeedCopy)
OS << char(dwarf::DW_LNS_copy);
else
OS << char(Temp);
}
// Utility function to write a tuple for .debug_abbrev.
static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
MCOS->EmitULEB128IntValue(Name);
MCOS->EmitULEB128IntValue(Form);
}
// When generating dwarf for assembly source files this emits
// the data for .debug_abbrev section which contains three DIEs.
static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
MCContext &context = MCOS->getContext();
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
// DW_TAG_compile_unit DIE abbrev (1).
MCOS->EmitULEB128IntValue(1);
MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
if (MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
MCOS->getContext().getDwarfVersion() >= 3) {
EmitAbbrev(MCOS, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4);
} else {
EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
}
EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
if (!context.getCompilationDir().empty())
EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
if (!DwarfDebugFlags.empty())
EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
EmitAbbrev(MCOS, 0, 0);
// DW_TAG_label DIE abbrev (2).
MCOS->EmitULEB128IntValue(2);
MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
EmitAbbrev(MCOS, 0, 0);
// DW_TAG_unspecified_parameters DIE abbrev (3).
MCOS->EmitULEB128IntValue(3);
MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
EmitAbbrev(MCOS, 0, 0);
// Terminate the abbreviations for this compilation unit.
MCOS->EmitIntValue(0, 1);
}
// When generating dwarf for assembly source files this emits the data for
// .debug_aranges section. This section contains a header and a table of pairs
// of PointerSize'ed values for the address and size of section(s) with line
// table entries.
static void EmitGenDwarfAranges(MCStreamer *MCOS,
const MCSymbol *InfoSectionSymbol) {
MCContext &context = MCOS->getContext();
auto &Sections = context.getGenDwarfSectionSyms();
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
// This will be the length of the .debug_aranges section, first account for
// the size of each item in the header (see below where we emit these items).
int Length = 4 + 2 + 4 + 1 + 1;
// Figure the padding after the header before the table of address and size
// pairs who's values are PointerSize'ed.
const MCAsmInfo *asmInfo = context.getAsmInfo();
int AddrSize = asmInfo->getPointerSize();
int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
if (Pad == 2 * AddrSize)
Pad = 0;
Length += Pad;
// Add the size of the pair of PointerSize'ed values for the address and size
// of each section we have in the table.
Length += 2 * AddrSize * Sections.size();
// And the pair of terminating zeros.
Length += 2 * AddrSize;
// Emit the header for this section.
// The 4 byte length not including the 4 byte value for the length.
MCOS->EmitIntValue(Length - 4, 4);
// The 2 byte version, which is 2.
MCOS->EmitIntValue(2, 2);
// The 4 byte offset to the compile unit in the .debug_info from the start
// of the .debug_info.
if (InfoSectionSymbol)
MCOS->EmitSymbolValue(InfoSectionSymbol, 4,
asmInfo->needsDwarfSectionOffsetDirective());
else
MCOS->EmitIntValue(0, 4);
// The 1 byte size of an address.
MCOS->EmitIntValue(AddrSize, 1);
// The 1 byte size of a segment descriptor, we use a value of zero.
MCOS->EmitIntValue(0, 1);
// Align the header with the padding if needed, before we put out the table.
for(int i = 0; i < Pad; i++)
MCOS->EmitIntValue(0, 1);
// Now emit the table of pairs of PointerSize'ed values for the section
// addresses and sizes.
for (MCSection *Sec : Sections) {
const MCSymbol *StartSymbol = Sec->getBeginSymbol();
MCSymbol *EndSymbol = Sec->getEndSymbol(context);
assert(StartSymbol && "StartSymbol must not be NULL");
assert(EndSymbol && "EndSymbol must not be NULL");
const MCExpr *Addr = MCSymbolRefExpr::create(
StartSymbol, MCSymbolRefExpr::VK_None, context);
const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
*StartSymbol, *EndSymbol, 0);
MCOS->EmitValue(Addr, AddrSize);
emitAbsValue(*MCOS, Size, AddrSize);
}
// And finally the pair of terminating zeros.
MCOS->EmitIntValue(0, AddrSize);
MCOS->EmitIntValue(0, AddrSize);
}
// When generating dwarf for assembly source files this emits the data for
// .debug_info section which contains three parts. The header, the compile_unit
// DIE and a list of label DIEs.
static void EmitGenDwarfInfo(MCStreamer *MCOS,
const MCSymbol *AbbrevSectionSymbol,
const MCSymbol *LineSectionSymbol,
const MCSymbol *RangesSectionSymbol) {
MCContext &context = MCOS->getContext();
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
// Create a symbol at the start and end of this section used in here for the
// expression to calculate the length in the header.
MCSymbol *InfoStart = context.createTempSymbol();
MCOS->EmitLabel(InfoStart);
MCSymbol *InfoEnd = context.createTempSymbol();
// First part: the header.
// The 4 byte total length of the information for this compilation unit, not
// including these 4 bytes.
const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
emitAbsValue(*MCOS, Length, 4);
// The 2 byte DWARF version.
MCOS->EmitIntValue(context.getDwarfVersion(), 2);
const MCAsmInfo &AsmInfo = *context.getAsmInfo();
// The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
// it is at the start of that section so this is zero.
if (AbbrevSectionSymbol == nullptr)
MCOS->EmitIntValue(0, 4);
else
MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4,
AsmInfo.needsDwarfSectionOffsetDirective());
const MCAsmInfo *asmInfo = context.getAsmInfo();
int AddrSize = asmInfo->getPointerSize();
// The 1 byte size of an address.
MCOS->EmitIntValue(AddrSize, 1);
// Second part: the compile_unit DIE.
// The DW_TAG_compile_unit DIE abbrev (1).
MCOS->EmitULEB128IntValue(1);
// DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
// which is at the start of that section so this is zero.
if (LineSectionSymbol)
MCOS->EmitSymbolValue(LineSectionSymbol, 4,
AsmInfo.needsDwarfSectionOffsetDirective());
else
MCOS->EmitIntValue(0, 4);
if (RangesSectionSymbol) {
// There are multiple sections containing code, so we must use the
// .debug_ranges sections.
// AT_ranges, the 4 byte offset from the start of the .debug_ranges section
// to the address range list for this compilation unit.
MCOS->EmitSymbolValue(RangesSectionSymbol, 4);
} else {
// If we only have one non-empty code section, we can use the simpler
// AT_low_pc and AT_high_pc attributes.
// Find the first (and only) non-empty text section
auto &Sections = context.getGenDwarfSectionSyms();
const auto TextSection = Sections.begin();
assert(TextSection != Sections.end() && "No text section found");
MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol();
MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context);
assert(StartSymbol && "StartSymbol must not be NULL");
assert(EndSymbol && "EndSymbol must not be NULL");
// AT_low_pc, the first address of the default .text section.
const MCExpr *Start = MCSymbolRefExpr::create(
StartSymbol, MCSymbolRefExpr::VK_None, context);
MCOS->EmitValue(Start, AddrSize);
// AT_high_pc, the last address of the default .text section.
const MCExpr *End = MCSymbolRefExpr::create(
EndSymbol, MCSymbolRefExpr::VK_None, context);
MCOS->EmitValue(End, AddrSize);
}
// AT_name, the name of the source file. Reconstruct from the first directory
// and file table entries.
const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
if (MCDwarfDirs.size() > 0) {
MCOS->EmitBytes(MCDwarfDirs[0]);
MCOS->EmitBytes(sys::path::get_separator());
}
const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles =
MCOS->getContext().getMCDwarfFiles();
MCOS->EmitBytes(MCDwarfFiles[1].Name);
MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
// AT_comp_dir, the working directory the assembly was done in.
if (!context.getCompilationDir().empty()) {
MCOS->EmitBytes(context.getCompilationDir());
MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
}
// AT_APPLE_flags, the command line arguments of the assembler tool.
StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
if (!DwarfDebugFlags.empty()){
MCOS->EmitBytes(DwarfDebugFlags);
MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
}
// AT_producer, the version of the assembler tool.
StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
if (!DwarfDebugProducer.empty())
MCOS->EmitBytes(DwarfDebugProducer);
else
MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
// AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
// draft has no standard code for assembler.
MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
// Third part: the list of label DIEs.
// Loop on saved info for dwarf labels and create the DIEs for them.
const std::vector<MCGenDwarfLabelEntry> &Entries =
MCOS->getContext().getMCGenDwarfLabelEntries();
for (const auto &Entry : Entries) {
// The DW_TAG_label DIE abbrev (2).
MCOS->EmitULEB128IntValue(2);
// AT_name, of the label without any leading underbar.
MCOS->EmitBytes(Entry.getName());
MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
// AT_decl_file, index into the file table.
MCOS->EmitIntValue(Entry.getFileNumber(), 4);
// AT_decl_line, source line number.
MCOS->EmitIntValue(Entry.getLineNumber(), 4);
// AT_low_pc, start address of the label.
const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(),
MCSymbolRefExpr::VK_None, context);
MCOS->EmitValue(AT_low_pc, AddrSize);
// DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
MCOS->EmitIntValue(0, 1);
// The DW_TAG_unspecified_parameters DIE abbrev (3).
MCOS->EmitULEB128IntValue(3);
// Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
MCOS->EmitIntValue(0, 1);
}
// Add the NULL DIE terminating the Compile Unit DIE's.
MCOS->EmitIntValue(0, 1);
// Now set the value of the symbol at the end of the info section.
MCOS->EmitLabel(InfoEnd);
}
// When generating dwarf for assembly source files this emits the data for
// .debug_ranges section. We only emit one range list, which spans all of the
// executable sections of this file.
static void EmitGenDwarfRanges(MCStreamer *MCOS) {
MCContext &context = MCOS->getContext();
auto &Sections = context.getGenDwarfSectionSyms();
const MCAsmInfo *AsmInfo = context.getAsmInfo();
int AddrSize = AsmInfo->getPointerSize();
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
for (MCSection *Sec : Sections) {
const MCSymbol *StartSymbol = Sec->getBeginSymbol();
MCSymbol *EndSymbol = Sec->getEndSymbol(context);
assert(StartSymbol && "StartSymbol must not be NULL");
assert(EndSymbol && "EndSymbol must not be NULL");
// Emit a base address selection entry for the start of this section
const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
StartSymbol, MCSymbolRefExpr::VK_None, context);
MCOS->EmitFill(AddrSize, 0xFF);
MCOS->EmitValue(SectionStartAddr, AddrSize);
// Emit a range list entry spanning this section
const MCExpr *SectionSize = MakeStartMinusEndExpr(*MCOS,
*StartSymbol, *EndSymbol, 0);
MCOS->EmitIntValue(0, AddrSize);
emitAbsValue(*MCOS, SectionSize, AddrSize);
}
// Emit end of list entry
MCOS->EmitIntValue(0, AddrSize);
MCOS->EmitIntValue(0, AddrSize);
}
//
// When generating dwarf for assembly source files this emits the Dwarf
// sections.
//
void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
MCContext &context = MCOS->getContext();
// Create the dwarf sections in this order (.debug_line already created).
const MCAsmInfo *AsmInfo = context.getAsmInfo();
bool CreateDwarfSectionSymbols =
AsmInfo->doesDwarfUseRelocationsAcrossSections();
MCSymbol *LineSectionSymbol = nullptr;
if (CreateDwarfSectionSymbols)
LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
MCSymbol *AbbrevSectionSymbol = nullptr;
MCSymbol *InfoSectionSymbol = nullptr;
MCSymbol *RangesSectionSymbol = NULL;
// Create end symbols for each section, and remove empty sections
MCOS->getContext().finalizeDwarfSections(*MCOS);
// If there are no sections to generate debug info for, we don't need
// to do anything
if (MCOS->getContext().getGenDwarfSectionSyms().empty())
return;
// We only use the .debug_ranges section if we have multiple code sections,
// and we are emitting a DWARF version which supports it.
const bool UseRangesSection =
MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
MCOS->getContext().getDwarfVersion() >= 3;
CreateDwarfSectionSymbols |= UseRangesSection;
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
if (CreateDwarfSectionSymbols) {
InfoSectionSymbol = context.createTempSymbol();
MCOS->EmitLabel(InfoSectionSymbol);
}
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
if (CreateDwarfSectionSymbols) {
AbbrevSectionSymbol = context.createTempSymbol();
MCOS->EmitLabel(AbbrevSectionSymbol);
}
if (UseRangesSection) {
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
if (CreateDwarfSectionSymbols) {
RangesSectionSymbol = context.createTempSymbol();
MCOS->EmitLabel(RangesSectionSymbol);
}
}
assert((RangesSectionSymbol != NULL) || !UseRangesSection);
MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
// Output the data for .debug_aranges section.
EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
if (UseRangesSection)
EmitGenDwarfRanges(MCOS);
// Output the data for .debug_abbrev section.
EmitGenDwarfAbbrev(MCOS);
// Output the data for .debug_info section.
EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol,
RangesSectionSymbol);
}
//
// When generating dwarf for assembly source files this is called when symbol
// for a label is created. If this symbol is not a temporary and is in the
// section that dwarf is being generated for, save the needed info to create
// a dwarf label.
//
void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
SourceMgr &SrcMgr, SMLoc &Loc) {
// We won't create dwarf labels for temporary symbols.
if (Symbol->isTemporary())
return;
MCContext &context = MCOS->getContext();
// We won't create dwarf labels for symbols in sections that we are not
// generating debug info for.
if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSection().first))
return;
// The dwarf label's name does not have the symbol name's leading
// underbar if any.
StringRef Name = Symbol->getName();
if (Name.startswith("_"))
Name = Name.substr(1, Name.size()-1);
// Get the dwarf file number to be used for the dwarf label.
unsigned FileNumber = context.getGenDwarfFileNumber();
// Finding the line number is the expensive part which is why we just don't
// pass it in as for some symbols we won't create a dwarf label.
unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
// We create a temporary symbol for use for the AT_high_pc and AT_low_pc
// values so that they don't have things like an ARM thumb bit from the
// original symbol. So when used they won't get a low bit set after
// relocation.
MCSymbol *Label = context.createTempSymbol();
MCOS->EmitLabel(Label);
// Create and entry for the info and add it to the other entries.
MCOS->getContext().addMCGenDwarfLabelEntry(
MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
}
static int getDataAlignmentFactor(MCStreamer &streamer) {
MCContext &context = streamer.getContext();
const MCAsmInfo *asmInfo = context.getAsmInfo();
int size = asmInfo->getCalleeSaveStackSlotSize();
if (asmInfo->isStackGrowthDirectionUp())
return size;
else
return -size;
}
static unsigned getSizeForEncoding(MCStreamer &streamer,
unsigned symbolEncoding) {
MCContext &context = streamer.getContext();
unsigned format = symbolEncoding & 0x0f;
switch (format) {
default: llvm_unreachable("Unknown Encoding");
case dwarf::DW_EH_PE_absptr:
case dwarf::DW_EH_PE_signed:
return context.getAsmInfo()->getPointerSize();
case dwarf::DW_EH_PE_udata2:
case dwarf::DW_EH_PE_sdata2:
return 2;
case dwarf::DW_EH_PE_udata4:
case dwarf::DW_EH_PE_sdata4:
return 4;
case dwarf::DW_EH_PE_udata8:
case dwarf::DW_EH_PE_sdata8:
return 8;
}
}
static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
unsigned symbolEncoding, bool isEH) {
MCContext &context = streamer.getContext();
const MCAsmInfo *asmInfo = context.getAsmInfo();
const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
symbolEncoding,
streamer);
unsigned size = getSizeForEncoding(streamer, symbolEncoding);
if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
emitAbsValue(streamer, v, size);
else
streamer.EmitValue(v, size);
}
static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
unsigned symbolEncoding) {
MCContext &context = streamer.getContext();
const MCAsmInfo *asmInfo = context.getAsmInfo();
const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
symbolEncoding,
streamer);
unsigned size = getSizeForEncoding(streamer, symbolEncoding);
streamer.EmitValue(v, size);
}
namespace {
class FrameEmitterImpl {
int CFAOffset;
int InitialCFAOffset;
bool IsEH;
const MCSymbol *SectionStart;
public:
FrameEmitterImpl(bool isEH)
: CFAOffset(0), InitialCFAOffset(0), IsEH(isEH), SectionStart(nullptr) {
}
void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
/// Emit the unwind information in a compact way.
void EmitCompactUnwind(MCObjectStreamer &streamer,
const MCDwarfFrameInfo &frame);
const MCSymbol &EmitCIE(MCObjectStreamer &streamer,
const MCSymbol *personality,
unsigned personalityEncoding,
const MCSymbol *lsda,
bool IsSignalFrame,
unsigned lsdaEncoding,
bool IsSimple);
MCSymbol *EmitFDE(MCObjectStreamer &streamer,
const MCSymbol &cieStart,
const MCDwarfFrameInfo &frame);
void EmitCFIInstructions(MCObjectStreamer &streamer,
ArrayRef<MCCFIInstruction> Instrs,
MCSymbol *BaseLabel);
void EmitCFIInstruction(MCObjectStreamer &Streamer,
const MCCFIInstruction &Instr);
};
} // end anonymous namespace
static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
Streamer.EmitIntValue(Encoding, 1);
}
void FrameEmitterImpl::EmitCFIInstruction(MCObjectStreamer &Streamer,
const MCCFIInstruction &Instr) {
int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
auto *MRI = Streamer.getContext().getRegisterInfo();
switch (Instr.getOperation()) {
case MCCFIInstruction::OpRegister: {
unsigned Reg1 = Instr.getRegister();
unsigned Reg2 = Instr.getRegister2();
if (!IsEH) {
Reg1 = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg1, true), false);
Reg2 = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg2, true), false);
}
Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
Streamer.EmitULEB128IntValue(Reg1);
Streamer.EmitULEB128IntValue(Reg2);
return;
}
case MCCFIInstruction::OpWindowSave: {
Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
return;
}
case MCCFIInstruction::OpUndefined: {
unsigned Reg = Instr.getRegister();
Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
Streamer.EmitULEB128IntValue(Reg);
return;
}
case MCCFIInstruction::OpAdjustCfaOffset:
case MCCFIInstruction::OpDefCfaOffset: {
const bool IsRelative =
Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
if (IsRelative)
CFAOffset += Instr.getOffset();
else
CFAOffset = -Instr.getOffset();
Streamer.EmitULEB128IntValue(CFAOffset);
return;
}
case MCCFIInstruction::OpDefCfa: {
unsigned Reg = Instr.getRegister();
if (!IsEH)
Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
Streamer.EmitULEB128IntValue(Reg);
CFAOffset = -Instr.getOffset();
Streamer.EmitULEB128IntValue(CFAOffset);
return;
}
case MCCFIInstruction::OpDefCfaRegister: {
unsigned Reg = Instr.getRegister();
if (!IsEH)
Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
Streamer.EmitULEB128IntValue(Reg);
return;
}
case MCCFIInstruction::OpOffset:
case MCCFIInstruction::OpRelOffset: {
const bool IsRelative =
Instr.getOperation() == MCCFIInstruction::OpRelOffset;
unsigned Reg = Instr.getRegister();
if (!IsEH)
Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
int Offset = Instr.getOffset();
if (IsRelative)
Offset -= CFAOffset;
Offset = Offset / dataAlignmentFactor;
if (Offset < 0) {
Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
Streamer.EmitULEB128IntValue(Reg);
Streamer.EmitSLEB128IntValue(Offset);
} else if (Reg < 64) {
Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
Streamer.EmitULEB128IntValue(Offset);
} else {
Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
Streamer.EmitULEB128IntValue(Reg);
Streamer.EmitULEB128IntValue(Offset);
}
return;
}
case MCCFIInstruction::OpRememberState:
Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
return;
case MCCFIInstruction::OpRestoreState:
Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
return;
case MCCFIInstruction::OpSameValue: {
unsigned Reg = Instr.getRegister();
Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
Streamer.EmitULEB128IntValue(Reg);
return;
}
case MCCFIInstruction::OpRestore: {
unsigned Reg = Instr.getRegister();
if (!IsEH)
Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
return;
}
case MCCFIInstruction::OpEscape:
Streamer.EmitBytes(Instr.getValues());
return;
}
llvm_unreachable("Unhandled case in switch");
}
/// Emit frame instructions to describe the layout of the frame.
void FrameEmitterImpl::EmitCFIInstructions(MCObjectStreamer &streamer,
ArrayRef<MCCFIInstruction> Instrs,
MCSymbol *BaseLabel) {
for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
const MCCFIInstruction &Instr = Instrs[i];
MCSymbol *Label = Instr.getLabel();
// Throw out move if the label is invalid.
if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
// Advance row if new location.
if (BaseLabel && Label) {
MCSymbol *ThisSym = Label;
if (ThisSym != BaseLabel) {
streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
BaseLabel = ThisSym;
}
}
EmitCFIInstruction(streamer, Instr);
}
}
/// Emit the unwind information in a compact way.
void FrameEmitterImpl::EmitCompactUnwind(MCObjectStreamer &Streamer,
const MCDwarfFrameInfo &Frame) {
MCContext &Context = Streamer.getContext();
const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
// range-start range-length compact-unwind-enc personality-func lsda
// _foo LfooEnd-_foo 0x00000023 0 0
// _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
//
// .section __LD,__compact_unwind,regular,debug
//
// # compact unwind for _foo
// .quad _foo
// .set L1,LfooEnd-_foo
// .long L1
// .long 0x01010001
// .quad 0
// .quad 0
//
// # compact unwind for _bar
// .quad _bar
// .set L2,LbarEnd-_bar
// .long L2
// .long 0x01020011
// .quad __gxx_personality
// .quad except_tab1
uint32_t Encoding = Frame.CompactUnwindEncoding;
if (!Encoding) return;
bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
// The encoding needs to know we have an LSDA.
if (!DwarfEHFrameOnly && Frame.Lsda)
Encoding |= 0x40000000;
// Range Start
unsigned FDEEncoding = MOFI->getFDEEncoding();
unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
Streamer.EmitSymbolValue(Frame.Begin, Size);
// Range Length
const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
*Frame.End, 0);
emitAbsValue(Streamer, Range, 4);
// Compact Encoding
Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
Streamer.EmitIntValue(Encoding, Size);
// Personality Function
Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
if (!DwarfEHFrameOnly && Frame.Personality)
Streamer.EmitSymbolValue(Frame.Personality, Size);
else
Streamer.EmitIntValue(0, Size); // No personality fn
// LSDA
Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
if (!DwarfEHFrameOnly && Frame.Lsda)
Streamer.EmitSymbolValue(Frame.Lsda, Size);
else
Streamer.EmitIntValue(0, Size); // No LSDA
}
static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) {
if (IsEH)
return 1;
switch (DwarfVersion) {
case 2:
return 1;
case 3:
return 3;
case 4:
return 4;
}
llvm_unreachable("Unknown version");
}
const MCSymbol &FrameEmitterImpl::EmitCIE(MCObjectStreamer &streamer,
const MCSymbol *personality,
unsigned personalityEncoding,
const MCSymbol *lsda,
bool IsSignalFrame,
unsigned lsdaEncoding,
bool IsSimple) {
MCContext &context = streamer.getContext();
const MCRegisterInfo *MRI = context.getRegisterInfo();
const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
MCSymbol *sectionStart = context.createTempSymbol();
streamer.EmitLabel(sectionStart);
MCSymbol *sectionEnd = context.createTempSymbol();
// Length
const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
*sectionEnd, 4);
emitAbsValue(streamer, Length, 4);
// CIE ID
unsigned CIE_ID = IsEH ? 0 : -1;
streamer.EmitIntValue(CIE_ID, 4);
// Version
uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion());
streamer.EmitIntValue(CIEVersion, 1);
// Augmentation String
SmallString<8> Augmentation;
if (IsEH) {
Augmentation += "z";
if (personality)
Augmentation += "P";
if (lsda)
Augmentation += "L";
Augmentation += "R";
if (IsSignalFrame)
Augmentation += "S";
streamer.EmitBytes(Augmentation);
}
streamer.EmitIntValue(0, 1);
if (CIEVersion >= 4) {
// Address Size
streamer.EmitIntValue(context.getAsmInfo()->getPointerSize(), 1);
// Segment Descriptor Size
streamer.EmitIntValue(0, 1);
}
// Code Alignment Factor
streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
// Data Alignment Factor
streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
// Return Address Register
if (CIEVersion == 1) {
assert(MRI->getRARegister() <= 255 &&
"DWARF 2 encodes return_address_register in one byte");
streamer.EmitIntValue(MRI->getDwarfRegNum(MRI->getRARegister(), IsEH), 1);
} else {
streamer.EmitULEB128IntValue(
MRI->getDwarfRegNum(MRI->getRARegister(), IsEH));
}
// Augmentation Data Length (optional)
unsigned augmentationLength = 0;
if (IsEH) {
if (personality) {
// Personality Encoding
augmentationLength += 1;
// Personality
augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
}
if (lsda)
augmentationLength += 1;
// Encoding of the FDE pointers
augmentationLength += 1;
streamer.EmitULEB128IntValue(augmentationLength);
// Augmentation Data (optional)
if (personality) {
// Personality Encoding
emitEncodingByte(streamer, personalityEncoding);
// Personality
EmitPersonality(streamer, *personality, personalityEncoding);
}
if (lsda)
emitEncodingByte(streamer, lsdaEncoding);
// Encoding of the FDE pointers
emitEncodingByte(streamer, MOFI->getFDEEncoding());
}
// Initial Instructions
const MCAsmInfo *MAI = context.getAsmInfo();
if (!IsSimple) {
const std::vector<MCCFIInstruction> &Instructions =
MAI->getInitialFrameState();
EmitCFIInstructions(streamer, Instructions, nullptr);
}
InitialCFAOffset = CFAOffset;
// Padding
streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
streamer.EmitLabel(sectionEnd);
return *sectionStart;
}
MCSymbol *FrameEmitterImpl::EmitFDE(MCObjectStreamer &streamer,
const MCSymbol &cieStart,
const MCDwarfFrameInfo &frame) {
MCContext &context = streamer.getContext();
MCSymbol *fdeStart = context.createTempSymbol();
MCSymbol *fdeEnd = context.createTempSymbol();
const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
CFAOffset = InitialCFAOffset;
// Length
const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
emitAbsValue(streamer, Length, 4);
streamer.EmitLabel(fdeStart);
// CIE Pointer
const MCAsmInfo *asmInfo = context.getAsmInfo();
if (IsEH) {
const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
0);
emitAbsValue(streamer, offset, 4);
} else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
cieStart, 0);
emitAbsValue(streamer, offset, 4);
} else {
streamer.EmitSymbolValue(&cieStart, 4);
}
// PC Begin
unsigned PCEncoding =
IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
emitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH);
// PC Range
const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
*frame.End, 0);
emitAbsValue(streamer, Range, PCSize);
if (IsEH) {
// Augmentation Data Length
unsigned augmentationLength = 0;
if (frame.Lsda)
augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
streamer.EmitULEB128IntValue(augmentationLength);
// Augmentation Data
if (frame.Lsda)
emitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true);
}
// Call Frame Instructions
EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
// Padding
streamer.EmitValueToAlignment(PCSize);
return fdeEnd;
}
namespace {
struct CIEKey {
static const CIEKey getEmptyKey() {
return CIEKey(nullptr, 0, -1, false, false);
}
static const CIEKey getTombstoneKey() {
return CIEKey(nullptr, -1, 0, false, false);
}
CIEKey(const MCSymbol *Personality_, unsigned PersonalityEncoding_,
unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_)
: Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_),
IsSimple(IsSimple_) {}
const MCSymbol *Personality;
unsigned PersonalityEncoding;
unsigned LsdaEncoding;
bool IsSignalFrame;
bool IsSimple;
};
}
namespace llvm {
template <>
struct DenseMapInfo<CIEKey> {
static CIEKey getEmptyKey() {
return CIEKey::getEmptyKey();
}
static CIEKey getTombstoneKey() {
return CIEKey::getTombstoneKey();
}
static unsigned getHashValue(const CIEKey &Key) {
return static_cast<unsigned>(hash_combine(Key.Personality,
Key.PersonalityEncoding,
Key.LsdaEncoding,
Key.IsSignalFrame,
Key.IsSimple));
}
static bool isEqual(const CIEKey &LHS,
const CIEKey &RHS) {
return LHS.Personality == RHS.Personality &&
LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
LHS.LsdaEncoding == RHS.LsdaEncoding &&
LHS.IsSignalFrame == RHS.IsSignalFrame &&
LHS.IsSimple == RHS.IsSimple;
}
};
}
void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
bool IsEH) {
Streamer.generateCompactUnwindEncodings(MAB);
MCContext &Context = Streamer.getContext();
const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
FrameEmitterImpl Emitter(IsEH);
ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
// Emit the compact unwind info if available.
bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
if (IsEH && MOFI->getCompactUnwindSection()) {
bool SectionEmitted = false;
for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
const MCDwarfFrameInfo &Frame = FrameArray[i];
if (Frame.CompactUnwindEncoding == 0) continue;
if (!SectionEmitted) {
Streamer.SwitchSection(MOFI->getCompactUnwindSection());
Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
SectionEmitted = true;
}
NeedsEHFrameSection |=
Frame.CompactUnwindEncoding ==
MOFI->getCompactUnwindDwarfEHFrameOnly();
Emitter.EmitCompactUnwind(Streamer, Frame);
}
}
if (!NeedsEHFrameSection) return;
MCSection &Section =
IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection()
: *MOFI->getDwarfFrameSection();
Streamer.SwitchSection(&Section);
MCSymbol *SectionStart = Context.createTempSymbol();
Streamer.EmitLabel(SectionStart);
Emitter.setSectionStart(SectionStart);
MCSymbol *FDEEnd = nullptr;
DenseMap<CIEKey, const MCSymbol *> CIEStarts;
const MCSymbol *DummyDebugKey = nullptr;
NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
const MCDwarfFrameInfo &Frame = FrameArray[i];
// Emit the label from the previous iteration
if (FDEEnd) {
Streamer.EmitLabel(FDEEnd);
FDEEnd = nullptr;
}
if (!NeedsEHFrameSection && Frame.CompactUnwindEncoding !=
MOFI->getCompactUnwindDwarfEHFrameOnly())
// Don't generate an EH frame if we don't need one. I.e., it's taken care
// of by the compact unwind encoding.
continue;
CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
if (!CIEStart)
CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
Frame.PersonalityEncoding, Frame.Lsda,
Frame.IsSignalFrame,
Frame.LsdaEncoding,
Frame.IsSimple);
FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
}
Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
if (FDEEnd)
Streamer.EmitLabel(FDEEnd);
}
void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
uint64_t AddrDelta) {
MCContext &Context = Streamer.getContext();
SmallString<256> Tmp;
raw_svector_ostream OS(Tmp);
MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
Streamer.EmitBytes(OS.str());
}
void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
uint64_t AddrDelta,
raw_ostream &OS) {
// Scale the address delta by the minimum instruction length.
AddrDelta = ScaleAddrDelta(Context, AddrDelta);
if (AddrDelta == 0) {
} else if (isUIntN(6, AddrDelta)) {
uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
OS << Opcode;
} else if (isUInt<8>(AddrDelta)) {
OS << uint8_t(dwarf::DW_CFA_advance_loc1);
OS << uint8_t(AddrDelta);
} else if (isUInt<16>(AddrDelta)) {
OS << uint8_t(dwarf::DW_CFA_advance_loc2);
if (Context.getAsmInfo()->isLittleEndian())
support::endian::Writer<support::little>(OS).write<uint16_t>(AddrDelta);
else
support::endian::Writer<support::big>(OS).write<uint16_t>(AddrDelta);
} else {
assert(isUInt<32>(AddrDelta));
OS << uint8_t(dwarf::DW_CFA_advance_loc4);
if (Context.getAsmInfo()->isLittleEndian())
support::endian::Writer<support::little>(OS).write<uint32_t>(AddrDelta);
else
support::endian::Writer<support::big>(OS).write<uint32_t>(AddrDelta);
}
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/MCWinEH.cpp | //===- lib/MC/MCWinEH.cpp - Windows EH implementation ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/StringRef.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCSectionCOFF.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCWinEH.h"
#include "llvm/Support/COFF.h"
namespace llvm {
namespace WinEH {
/// We can't have one section for all .pdata or .xdata because the Microsoft
/// linker seems to want all code relocations to refer to the same object file
/// section. If the code described is comdat, create a new comdat section
/// associated with that comdat. If the code described is not in the main .text
/// section, make a new section for it. Otherwise use the main unwind info
/// section.
static MCSection *getUnwindInfoSection(StringRef SecName,
MCSectionCOFF *UnwindSec,
const MCSymbol *Function,
MCContext &Context) {
if (Function && Function->isInSection()) {
// If Function is in a COMDAT, get or create an unwind info section in that
// COMDAT group.
const MCSectionCOFF *FunctionSection =
cast<MCSectionCOFF>(&Function->getSection());
if (FunctionSection->getCharacteristics() & COFF::IMAGE_SCN_LNK_COMDAT) {
return Context.getAssociativeCOFFSection(
UnwindSec, FunctionSection->getCOMDATSymbol());
}
// If Function is in a section other than .text, create a new .pdata section.
// Otherwise use the plain .pdata section.
if (const auto *Section = dyn_cast<MCSectionCOFF>(FunctionSection)) {
StringRef CodeSecName = Section->getSectionName();
if (CodeSecName == ".text")
return UnwindSec;
if (CodeSecName.startswith(".text$"))
CodeSecName = CodeSecName.substr(6);
return Context.getCOFFSection(
(SecName + Twine('$') + CodeSecName).str(),
COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
SectionKind::getDataRel());
}
}
return UnwindSec;
}
MCSection *UnwindEmitter::getPDataSection(const MCSymbol *Function,
MCContext &Context) {
MCSectionCOFF *PData =
cast<MCSectionCOFF>(Context.getObjectFileInfo()->getPDataSection());
return getUnwindInfoSection(".pdata", PData, Function, Context);
}
MCSection *UnwindEmitter::getXDataSection(const MCSymbol *Function,
MCContext &Context) {
MCSectionCOFF *XData =
cast<MCSectionCOFF>(Context.getObjectFileInfo()->getXDataSection());
return getUnwindInfoSection(".xdata", XData, Function, Context);
}
}
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/MCELFObjectTargetWriter.cpp | //===-- MCELFObjectTargetWriter.cpp - ELF Target Writer Subclass ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/MC/MCELFObjectWriter.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCValue.h"
using namespace llvm;
MCELFObjectTargetWriter::MCELFObjectTargetWriter(bool Is64Bit_,
uint8_t OSABI_,
uint16_t EMachine_,
bool HasRelocationAddend_,
bool IsN64_)
: OSABI(OSABI_), EMachine(EMachine_),
HasRelocationAddend(HasRelocationAddend_), Is64Bit(Is64Bit_),
IsN64(IsN64_){
}
bool MCELFObjectTargetWriter::needsRelocateWithSymbol(const MCSymbol &Sym,
unsigned Type) const {
return false;
}
// ELF doesn't require relocations to be in any order. We sort by the Offset,
// just to match gnu as for easier comparison. The use type is an arbitrary way
// of making the sort deterministic.
// HLSL Change: changed calling convention to __cdecl
static int __cdecl cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
const ELFRelocationEntry &A = *AP;
const ELFRelocationEntry &B = *BP;
if (A.Offset != B.Offset)
return B.Offset - A.Offset;
if (B.Type != A.Type)
return A.Type - B.Type;
//llvm_unreachable("ELFRelocs might be unstable!");
return 0;
}
void
MCELFObjectTargetWriter::sortRelocs(const MCAssembler &Asm,
std::vector<ELFRelocationEntry> &Relocs) {
array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MC/MCAssembler.cpp | //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCAssembler.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Twine.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCAsmLayout.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCFixupKindInfo.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCValue.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/raw_ostream.h"
#include <tuple>
using namespace llvm;
#define DEBUG_TYPE "assembler"
namespace {
namespace stats {
STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
STATISTIC(EmittedRelaxableFragments,
"Number of emitted assembler fragments - relaxable");
STATISTIC(EmittedDataFragments,
"Number of emitted assembler fragments - data");
STATISTIC(EmittedCompactEncodedInstFragments,
"Number of emitted assembler fragments - compact encoded inst");
STATISTIC(EmittedAlignFragments,
"Number of emitted assembler fragments - align");
STATISTIC(EmittedFillFragments,
"Number of emitted assembler fragments - fill");
STATISTIC(EmittedOrgFragments,
"Number of emitted assembler fragments - org");
STATISTIC(evaluateFixup, "Number of evaluated fixups");
STATISTIC(FragmentLayouts, "Number of fragment layouts");
STATISTIC(ObjectBytes, "Number of emitted object file bytes");
STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
}
}
// FIXME FIXME FIXME: There are number of places in this file where we convert
// what is a 64-bit assembler value used for computation into a value in the
// object file, which may truncate it. We should detect that truncation where
// invalid and report errors back.
/* *** */
MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
: Assembler(Asm), LastValidFragment()
{
// Compute the section layout order. Virtual sections must go last.
for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
if (!it->isVirtualSection())
SectionOrder.push_back(&*it);
for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
if (it->isVirtualSection())
SectionOrder.push_back(&*it);
}
bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
const MCSection *Sec = F->getParent();
const MCFragment *LastValid = LastValidFragment.lookup(Sec);
if (!LastValid)
return false;
assert(LastValid->getParent() == Sec);
return F->getLayoutOrder() <= LastValid->getLayoutOrder();
}
void MCAsmLayout::invalidateFragmentsFrom(MCFragment *F) {
// If this fragment wasn't already valid, we don't need to do anything.
if (!isFragmentValid(F))
return;
// Otherwise, reset the last valid fragment to the previous fragment
// (if this is the first fragment, it will be NULL).
LastValidFragment[F->getParent()] = F->getPrevNode();
}
void MCAsmLayout::ensureValid(const MCFragment *F) const {
MCSection *Sec = F->getParent();
MCFragment *Cur = LastValidFragment[Sec];
if (!Cur)
Cur = Sec->begin();
else
Cur = Cur->getNextNode();
// Advance the layout position until the fragment is valid.
while (!isFragmentValid(F)) {
assert(Cur && "Layout bookkeeping error");
const_cast<MCAsmLayout*>(this)->layoutFragment(Cur);
Cur = Cur->getNextNode();
}
}
uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
ensureValid(F);
assert(F->Offset != ~UINT64_C(0) && "Address not set!");
return F->Offset;
}
// Simple getSymbolOffset helper for the non-varibale case.
static bool getLabelOffset(const MCAsmLayout &Layout, const MCSymbol &S,
bool ReportError, uint64_t &Val) {
if (!S.getFragment()) {
if (ReportError)
report_fatal_error("unable to evaluate offset to undefined symbol '" +
S.getName() + "'");
return false;
}
Val = Layout.getFragmentOffset(S.getFragment()) + S.getOffset();
return true;
}
static bool getSymbolOffsetImpl(const MCAsmLayout &Layout, const MCSymbol &S,
bool ReportError, uint64_t &Val) {
if (!S.isVariable())
return getLabelOffset(Layout, S, ReportError, Val);
// If SD is a variable, evaluate it.
MCValue Target;
if (!S.getVariableValue()->evaluateAsRelocatable(Target, &Layout, nullptr))
report_fatal_error("unable to evaluate offset for variable '" +
S.getName() + "'");
uint64_t Offset = Target.getConstant();
const MCSymbolRefExpr *A = Target.getSymA();
if (A) {
uint64_t ValA;
if (!getLabelOffset(Layout, A->getSymbol(), ReportError, ValA))
return false;
Offset += ValA;
}
const MCSymbolRefExpr *B = Target.getSymB();
if (B) {
uint64_t ValB;
if (!getLabelOffset(Layout, B->getSymbol(), ReportError, ValB))
return false;
Offset -= ValB;
}
Val = Offset;
return true;
}
bool MCAsmLayout::getSymbolOffset(const MCSymbol &S, uint64_t &Val) const {
return getSymbolOffsetImpl(*this, S, false, Val);
}
uint64_t MCAsmLayout::getSymbolOffset(const MCSymbol &S) const {
uint64_t Val;
getSymbolOffsetImpl(*this, S, true, Val);
return Val;
}
const MCSymbol *MCAsmLayout::getBaseSymbol(const MCSymbol &Symbol) const {
if (!Symbol.isVariable())
return &Symbol;
const MCExpr *Expr = Symbol.getVariableValue();
MCValue Value;
if (!Expr->evaluateAsValue(Value, *this))
llvm_unreachable("Invalid Expression");
const MCSymbolRefExpr *RefB = Value.getSymB();
if (RefB)
Assembler.getContext().reportFatalError(
SMLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
"' could not be evaluated in a subtraction expression");
const MCSymbolRefExpr *A = Value.getSymA();
if (!A)
return nullptr;
const MCSymbol &ASym = A->getSymbol();
const MCAssembler &Asm = getAssembler();
if (ASym.isCommon()) {
// FIXME: we should probably add a SMLoc to MCExpr.
Asm.getContext().reportFatalError(SMLoc(),
"Common symbol " + ASym.getName() +
" cannot be used in assignment expr");
}
return &ASym;
}
uint64_t MCAsmLayout::getSectionAddressSize(const MCSection *Sec) const {
// The size is the last fragment's end offset.
const MCFragment &F = Sec->getFragmentList().back();
return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
}
uint64_t MCAsmLayout::getSectionFileSize(const MCSection *Sec) const {
// Virtual sections have no file size.
if (Sec->isVirtualSection())
return 0;
// Otherwise, the file size is the same as the address space size.
return getSectionAddressSize(Sec);
}
uint64_t llvm::computeBundlePadding(const MCAssembler &Assembler,
const MCFragment *F,
uint64_t FOffset, uint64_t FSize) {
uint64_t BundleSize = Assembler.getBundleAlignSize();
assert(BundleSize > 0 &&
"computeBundlePadding should only be called if bundling is enabled");
uint64_t BundleMask = BundleSize - 1;
uint64_t OffsetInBundle = FOffset & BundleMask;
uint64_t EndOfFragment = OffsetInBundle + FSize;
// There are two kinds of bundling restrictions:
//
// 1) For alignToBundleEnd(), add padding to ensure that the fragment will
// *end* on a bundle boundary.
// 2) Otherwise, check if the fragment would cross a bundle boundary. If it
// would, add padding until the end of the bundle so that the fragment
// will start in a new one.
if (F->alignToBundleEnd()) {
// Three possibilities here:
//
// A) The fragment just happens to end at a bundle boundary, so we're good.
// B) The fragment ends before the current bundle boundary: pad it just
// enough to reach the boundary.
// C) The fragment ends after the current bundle boundary: pad it until it
// reaches the end of the next bundle boundary.
//
// Note: this code could be made shorter with some modulo trickery, but it's
// intentionally kept in its more explicit form for simplicity.
if (EndOfFragment == BundleSize)
return 0;
else if (EndOfFragment < BundleSize)
return BundleSize - EndOfFragment;
else { // EndOfFragment > BundleSize
return 2 * BundleSize - EndOfFragment;
}
} else if (OffsetInBundle > 0 && EndOfFragment > BundleSize)
return BundleSize - OffsetInBundle;
else
return 0;
}
/* *** */
void ilist_node_traits<MCFragment>::deleteNode(MCFragment *V) {
V->destroy();
}
MCFragment::MCFragment() : Kind(FragmentType(~0)), HasInstructions(false),
AlignToBundleEnd(false), BundlePadding(0) {
}
MCFragment::~MCFragment() { }
MCFragment::MCFragment(FragmentType Kind, bool HasInstructions,
uint8_t BundlePadding, MCSection *Parent)
: Kind(Kind), HasInstructions(HasInstructions), AlignToBundleEnd(false),
BundlePadding(BundlePadding), Parent(Parent), Atom(nullptr),
Offset(~UINT64_C(0)) {
if (Parent)
Parent->getFragmentList().push_back(this);
}
void MCFragment::destroy() {
// First check if we are the sentinal.
if (Kind == FragmentType(~0)) {
delete this;
return;
}
switch (Kind) {
case FT_Align:
delete cast<MCAlignFragment>(this);
return;
case FT_Data:
delete cast<MCDataFragment>(this);
return;
case FT_CompactEncodedInst:
delete cast<MCCompactEncodedInstFragment>(this);
return;
case FT_Fill:
delete cast<MCFillFragment>(this);
return;
case FT_Relaxable:
delete cast<MCRelaxableFragment>(this);
return;
case FT_Org:
delete cast<MCOrgFragment>(this);
return;
case FT_Dwarf:
delete cast<MCDwarfLineAddrFragment>(this);
return;
case FT_DwarfFrame:
delete cast<MCDwarfCallFrameFragment>(this);
return;
case FT_LEB:
delete cast<MCLEBFragment>(this);
return;
case FT_SafeSEH:
delete cast<MCSafeSEHFragment>(this);
return;
}
}
/* *** */
MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
raw_ostream &OS_)
: Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
OS(OS_), BundleAlignSize(0), RelaxAll(false),
SubsectionsViaSymbols(false), ELFHeaderEFlags(0) {
VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
}
MCAssembler::~MCAssembler() {
}
void MCAssembler::reset() {
Sections.clear();
Symbols.clear();
IndirectSymbols.clear();
DataRegions.clear();
LinkerOptions.clear();
FileNames.clear();
ThumbFuncs.clear();
BundleAlignSize = 0;
RelaxAll = false;
SubsectionsViaSymbols = false;
ELFHeaderEFlags = 0;
LOHContainer.reset();
VersionMinInfo.Major = 0;
// reset objects owned by us
getBackend().reset();
getEmitter().reset();
getWriter().reset();
getLOHContainer().reset();
}
bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
if (ThumbFuncs.count(Symbol))
return true;
if (!Symbol->isVariable())
return false;
// FIXME: It looks like gas supports some cases of the form "foo + 2". It
// is not clear if that is a bug or a feature.
const MCExpr *Expr = Symbol->getVariableValue();
const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
if (!Ref)
return false;
if (Ref->getKind() != MCSymbolRefExpr::VK_None)
return false;
const MCSymbol &Sym = Ref->getSymbol();
if (!isThumbFunc(&Sym))
return false;
ThumbFuncs.insert(Symbol); // Cache it.
return true;
}
bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
// Non-temporary labels should always be visible to the linker.
if (!Symbol.isTemporary())
return true;
// Absolute temporary labels are never visible.
if (!Symbol.isInSection())
return false;
if (Symbol.isUsedInReloc())
return true;
return false;
}
const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
// Linker visible symbols define atoms.
if (isSymbolLinkerVisible(S))
return &S;
// Absolute and undefined symbols have no defining atom.
if (!S.getFragment())
return nullptr;
// Non-linker visible symbols in sections which can't be atomized have no
// defining atom.
if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
*S.getFragment()->getParent()))
return nullptr;
// Otherwise, return the atom for the containing fragment.
return S.getFragment()->getAtom();
}
bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
const MCFixup &Fixup, const MCFragment *DF,
MCValue &Target, uint64_t &Value) const {
++stats::evaluateFixup;
// FIXME: This code has some duplication with recordRelocation. We should
// probably merge the two into a single callback that tries to evaluate a
// fixup and records a relocation if one is needed.
const MCExpr *Expr = Fixup.getValue();
if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup))
getContext().reportFatalError(Fixup.getLoc(), "expected relocatable expression");
bool IsPCRel = Backend.getFixupKindInfo(
Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
bool IsResolved;
if (IsPCRel) {
if (Target.getSymB()) {
IsResolved = false;
} else if (!Target.getSymA()) {
IsResolved = false;
} else {
const MCSymbolRefExpr *A = Target.getSymA();
const MCSymbol &SA = A->getSymbol();
if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
IsResolved = false;
} else {
IsResolved = getWriter().isSymbolRefDifferenceFullyResolvedImpl(
*this, SA, *DF, false, true);
}
}
} else {
IsResolved = Target.isAbsolute();
}
Value = Target.getConstant();
if (const MCSymbolRefExpr *A = Target.getSymA()) {
const MCSymbol &Sym = A->getSymbol();
if (Sym.isDefined())
Value += Layout.getSymbolOffset(Sym);
}
if (const MCSymbolRefExpr *B = Target.getSymB()) {
const MCSymbol &Sym = B->getSymbol();
if (Sym.isDefined())
Value -= Layout.getSymbolOffset(Sym);
}
bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
assert((ShouldAlignPC ? IsPCRel : true) &&
"FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
if (IsPCRel) {
uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
// A number of ARM fixups in Thumb mode require that the effective PC
// address be determined as the 32-bit aligned version of the actual offset.
if (ShouldAlignPC) Offset &= ~0x3;
Value -= Offset;
}
// Let the backend adjust the fixup value if necessary, including whether
// we need a relocation.
Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
IsResolved);
return IsResolved;
}
uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
const MCFragment &F) const {
switch (F.getKind()) {
case MCFragment::FT_Data:
return cast<MCDataFragment>(F).getContents().size();
case MCFragment::FT_Relaxable:
return cast<MCRelaxableFragment>(F).getContents().size();
case MCFragment::FT_CompactEncodedInst:
return cast<MCCompactEncodedInstFragment>(F).getContents().size();
case MCFragment::FT_Fill:
return cast<MCFillFragment>(F).getSize();
case MCFragment::FT_LEB:
return cast<MCLEBFragment>(F).getContents().size();
case MCFragment::FT_SafeSEH:
return 4;
case MCFragment::FT_Align: {
const MCAlignFragment &AF = cast<MCAlignFragment>(F);
unsigned Offset = Layout.getFragmentOffset(&AF);
unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
// If we are padding with nops, force the padding to be larger than the
// minimum nop size.
if (Size > 0 && AF.hasEmitNops()) {
while (Size % getBackend().getMinimumNopSize())
Size += AF.getAlignment();
}
if (Size > AF.getMaxBytesToEmit())
return 0;
return Size;
}
case MCFragment::FT_Org: {
const MCOrgFragment &OF = cast<MCOrgFragment>(F);
int64_t TargetLocation;
if (!OF.getOffset().evaluateAsAbsolute(TargetLocation, Layout))
report_fatal_error("expected assembly-time absolute expression");
// FIXME: We need a way to communicate this error.
uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
int64_t Size = TargetLocation - FragmentOffset;
if (Size < 0 || Size >= 0x40000000)
report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
"' (at offset '" + Twine(FragmentOffset) + "')");
return Size;
}
case MCFragment::FT_Dwarf:
return cast<MCDwarfLineAddrFragment>(F).getContents().size();
case MCFragment::FT_DwarfFrame:
return cast<MCDwarfCallFrameFragment>(F).getContents().size();
}
llvm_unreachable("invalid fragment kind");
}
void MCAsmLayout::layoutFragment(MCFragment *F) {
MCFragment *Prev = F->getPrevNode();
// We should never try to recompute something which is valid.
assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
// We should never try to compute the fragment layout if its predecessor
// isn't valid.
assert((!Prev || isFragmentValid(Prev)) &&
"Attempt to compute fragment before its predecessor!");
++stats::FragmentLayouts;
// Compute fragment offset and size.
if (Prev)
F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
else
F->Offset = 0;
LastValidFragment[F->getParent()] = F;
// If bundling is enabled and this fragment has instructions in it, it has to
// obey the bundling restrictions. With padding, we'll have:
//
//
// BundlePadding
// |||
// -------------------------------------
// Prev |##########| F |
// -------------------------------------
// ^
// |
// F->Offset
//
// The fragment's offset will point to after the padding, and its computed
// size won't include the padding.
//
// When the -mc-relax-all flag is used, we optimize bundling by writting the
// padding directly into fragments when the instructions are emitted inside
// the streamer. When the fragment is larger than the bundle size, we need to
// ensure that it's bundle aligned. This means that if we end up with
// multiple fragments, we must emit bundle padding between fragments.
//
// ".align N" is an example of a directive that introduces multiple
// fragments. We could add a special case to handle ".align N" by emitting
// within-fragment padding (which would produce less padding when N is less
// than the bundle size), but for now we don't.
//
if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
assert(isa<MCEncodedFragment>(F) &&
"Only MCEncodedFragment implementations have instructions");
uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
report_fatal_error("Fragment can't be larger than a bundle size");
uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
F->Offset, FSize);
if (RequiredBundlePadding > UINT8_MAX)
report_fatal_error("Padding cannot exceed 255 bytes");
F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
F->Offset += RequiredBundlePadding;
}
}
void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
bool New = !Symbol.isRegistered();
if (Created)
*Created = New;
if (New) {
Symbol.setIsRegistered(true);
Symbols.push_back(&Symbol);
}
}
void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
MCObjectWriter *OW) const {
// Should NOP padding be written out before this fragment?
unsigned BundlePadding = F.getBundlePadding();
if (BundlePadding > 0) {
assert(isBundlingEnabled() &&
"Writing bundle padding with disabled bundling");
assert(F.hasInstructions() &&
"Writing bundle padding for a fragment without instructions");
unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
// If the padding itself crosses a bundle boundary, it must be emitted
// in 2 pieces, since even nop instructions must not cross boundaries.
// v--------------v <- BundleAlignSize
// v---------v <- BundlePadding
// ----------------------------
// | Prev |####|####| F |
// ----------------------------
// ^-------------------^ <- TotalLength
unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
if (!getBackend().writeNopData(DistanceToBoundary, OW))
report_fatal_error("unable to write NOP sequence of " +
Twine(DistanceToBoundary) + " bytes");
BundlePadding -= DistanceToBoundary;
}
if (!getBackend().writeNopData(BundlePadding, OW))
report_fatal_error("unable to write NOP sequence of " +
Twine(BundlePadding) + " bytes");
}
}
/// \brief Write the fragment \p F to the output file.
static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
const MCFragment &F) {
MCObjectWriter *OW = &Asm.getWriter();
// FIXME: Embed in fragments instead?
uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
Asm.writeFragmentPadding(F, FragmentSize, OW);
// This variable (and its dummy usage) is to participate in the assert at
// the end of the function.
uint64_t Start = OW->getStream().tell();
(void) Start;
++stats::EmittedFragments;
switch (F.getKind()) {
case MCFragment::FT_Align: {
++stats::EmittedAlignFragments;
const MCAlignFragment &AF = cast<MCAlignFragment>(F);
assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
uint64_t Count = FragmentSize / AF.getValueSize();
// FIXME: This error shouldn't actually occur (the front end should emit
// multiple .align directives to enforce the semantics it wants), but is
// severe enough that we want to report it. How to handle this?
if (Count * AF.getValueSize() != FragmentSize)
report_fatal_error("undefined .align directive, value size '" +
Twine(AF.getValueSize()) +
"' is not a divisor of padding size '" +
Twine(FragmentSize) + "'");
// See if we are aligning with nops, and if so do that first to try to fill
// the Count bytes. Then if that did not fill any bytes or there are any
// bytes left to fill use the Value and ValueSize to fill the rest.
// If we are aligning with nops, ask that target to emit the right data.
if (AF.hasEmitNops()) {
if (!Asm.getBackend().writeNopData(Count, OW))
report_fatal_error("unable to write nop sequence of " +
Twine(Count) + " bytes");
break;
}
// Otherwise, write out in multiples of the value size.
for (uint64_t i = 0; i != Count; ++i) {
switch (AF.getValueSize()) {
default: llvm_unreachable("Invalid size!");
case 1: OW->write8 (uint8_t (AF.getValue())); break;
case 2: OW->write16(uint16_t(AF.getValue())); break;
case 4: OW->write32(uint32_t(AF.getValue())); break;
case 8: OW->write64(uint64_t(AF.getValue())); break;
}
}
break;
}
case MCFragment::FT_Data:
++stats::EmittedDataFragments;
OW->writeBytes(cast<MCDataFragment>(F).getContents());
break;
case MCFragment::FT_Relaxable:
++stats::EmittedRelaxableFragments;
OW->writeBytes(cast<MCRelaxableFragment>(F).getContents());
break;
case MCFragment::FT_CompactEncodedInst:
++stats::EmittedCompactEncodedInstFragments;
OW->writeBytes(cast<MCCompactEncodedInstFragment>(F).getContents());
break;
case MCFragment::FT_Fill: {
++stats::EmittedFillFragments;
const MCFillFragment &FF = cast<MCFillFragment>(F);
assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
switch (FF.getValueSize()) {
default: llvm_unreachable("Invalid size!");
case 1: OW->write8 (uint8_t (FF.getValue())); break;
case 2: OW->write16(uint16_t(FF.getValue())); break;
case 4: OW->write32(uint32_t(FF.getValue())); break;
case 8: OW->write64(uint64_t(FF.getValue())); break;
}
}
break;
}
case MCFragment::FT_LEB: {
const MCLEBFragment &LF = cast<MCLEBFragment>(F);
OW->writeBytes(LF.getContents());
break;
}
case MCFragment::FT_SafeSEH: {
const MCSafeSEHFragment &SF = cast<MCSafeSEHFragment>(F);
OW->write32(SF.getSymbol()->getIndex());
break;
}
case MCFragment::FT_Org: {
++stats::EmittedOrgFragments;
const MCOrgFragment &OF = cast<MCOrgFragment>(F);
for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
OW->write8(uint8_t(OF.getValue()));
break;
}
case MCFragment::FT_Dwarf: {
const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
OW->writeBytes(OF.getContents());
break;
}
case MCFragment::FT_DwarfFrame: {
const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
OW->writeBytes(CF.getContents());
break;
}
}
assert(OW->getStream().tell() - Start == FragmentSize &&
"The stream should advance by fragment size");
}
void MCAssembler::writeSectionData(const MCSection *Sec,
const MCAsmLayout &Layout) const {
// Ignore virtual sections.
if (Sec->isVirtualSection()) {
assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
// Check that contents are only things legal inside a virtual section.
for (MCSection::const_iterator it = Sec->begin(), ie = Sec->end(); it != ie;
++it) {
switch (it->getKind()) {
default: llvm_unreachable("Invalid fragment in virtual section!");
case MCFragment::FT_Data: {
// Check that we aren't trying to write a non-zero contents (or fixups)
// into a virtual section. This is to support clients which use standard
// directives to fill the contents of virtual sections.
const MCDataFragment &DF = cast<MCDataFragment>(*it);
assert(DF.fixup_begin() == DF.fixup_end() &&
"Cannot have fixups in virtual section!");
for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
if (DF.getContents()[i]) {
if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
report_fatal_error("non-zero initializer found in section '" +
ELFSec->getSectionName() + "'");
else
report_fatal_error("non-zero initializer found in virtual section");
}
break;
}
case MCFragment::FT_Align:
// Check that we aren't trying to write a non-zero value into a virtual
// section.
assert((cast<MCAlignFragment>(it)->getValueSize() == 0 ||
cast<MCAlignFragment>(it)->getValue() == 0) &&
"Invalid align in virtual section!");
break;
case MCFragment::FT_Fill:
assert((cast<MCFillFragment>(it)->getValueSize() == 0 ||
cast<MCFillFragment>(it)->getValue() == 0) &&
"Invalid fill in virtual section!");
break;
}
}
return;
}
uint64_t Start = getWriter().getStream().tell();
(void)Start;
for (MCSection::const_iterator it = Sec->begin(), ie = Sec->end(); it != ie;
++it)
writeFragment(*this, Layout, *it);
assert(getWriter().getStream().tell() - Start ==
Layout.getSectionAddressSize(Sec));
}
std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
MCFragment &F,
const MCFixup &Fixup) {
// Evaluate the fixup.
MCValue Target;
uint64_t FixedValue;
bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
MCFixupKindInfo::FKF_IsPCRel;
if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
// The fixup was unresolved, we need a relocation. Inform the object
// writer of the relocation, and give it an opportunity to adjust the
// fixup value if need be.
getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
FixedValue);
}
return std::make_pair(FixedValue, IsPCRel);
}
void MCAssembler::Finish() {
DEBUG_WITH_TYPE("mc-dump", {
llvm::errs() << "assembler backend - pre-layout\n--\n";
dump(); });
// Create the layout object.
MCAsmLayout Layout(*this);
// Create dummy fragments and assign section ordinals.
unsigned SectionIndex = 0;
for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
// Create dummy fragments to eliminate any empty sections, this simplifies
// layout.
if (it->getFragmentList().empty())
new MCDataFragment(&*it);
it->setOrdinal(SectionIndex++);
}
// Assign layout order indices to sections and fragments.
for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
MCSection *Sec = Layout.getSectionOrder()[i];
Sec->setLayoutOrder(i);
unsigned FragmentIndex = 0;
for (MCSection::iterator iFrag = Sec->begin(), iFragEnd = Sec->end();
iFrag != iFragEnd; ++iFrag)
iFrag->setLayoutOrder(FragmentIndex++);
}
// Layout until everything fits.
while (layoutOnce(Layout))
continue;
DEBUG_WITH_TYPE("mc-dump", {
llvm::errs() << "assembler backend - post-relaxation\n--\n";
dump(); });
// Finalize the layout, including fragment lowering.
finishLayout(Layout);
DEBUG_WITH_TYPE("mc-dump", {
llvm::errs() << "assembler backend - final-layout\n--\n";
dump(); });
uint64_t StartOffset = OS.tell();
// Allow the object writer a chance to perform post-layout binding (for
// example, to set the index fields in the symbol data).
getWriter().executePostLayoutBinding(*this, Layout);
// Evaluate and apply the fixups, generating relocation entries as necessary.
for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
for (MCSection::iterator it2 = it->begin(), ie2 = it->end(); it2 != ie2;
++it2) {
MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(it2);
// Data and relaxable fragments both have fixups. So only process
// those here.
// FIXME: Is there a better way to do this? MCEncodedFragmentWithFixups
// being templated makes this tricky.
if (!F || isa<MCCompactEncodedInstFragment>(F))
continue;
ArrayRef<MCFixup> Fixups;
MutableArrayRef<char> Contents;
if (auto *FragWithFixups = dyn_cast<MCDataFragment>(F)) {
Fixups = FragWithFixups->getFixups();
Contents = FragWithFixups->getContents();
} else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(F)) {
Fixups = FragWithFixups->getFixups();
Contents = FragWithFixups->getContents();
} else
llvm_unreachable("Unknown fragment with fixups!");
for (const MCFixup &Fixup : Fixups) {
uint64_t FixedValue;
bool IsPCRel;
std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
getBackend().applyFixup(Fixup, Contents.data(),
Contents.size(), FixedValue, IsPCRel);
}
}
}
// Write the object file.
getWriter().writeObject(*this, Layout);
stats::ObjectBytes += OS.tell() - StartOffset;
}
bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
const MCRelaxableFragment *DF,
const MCAsmLayout &Layout) const {
MCValue Target;
uint64_t Value;
bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value);
return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
Layout);
}
bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
const MCAsmLayout &Layout) const {
// If this inst doesn't ever need relaxation, ignore it. This occurs when we
// are intentionally pushing out inst fragments, or because we relaxed a
// previous instruction to one that doesn't need relaxation.
if (!getBackend().mayNeedRelaxation(F->getInst()))
return false;
for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
ie = F->fixup_end(); it != ie; ++it)
if (fixupNeedsRelaxation(*it, F, Layout))
return true;
return false;
}
bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
MCRelaxableFragment &F) {
if (!fragmentNeedsRelaxation(&F, Layout))
return false;
++stats::RelaxedInstructions;
// FIXME-PERF: We could immediately lower out instructions if we can tell
// they are fully resolved, to avoid retesting on later passes.
// Relax the fragment.
MCInst Relaxed;
getBackend().relaxInstruction(F.getInst(), Relaxed);
// Encode the new instruction.
//
// FIXME-PERF: If it matters, we could let the target do this. It can
// probably do so more efficiently in many cases.
SmallVector<MCFixup, 4> Fixups;
SmallString<256> Code;
raw_svector_ostream VecOS(Code);
getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
VecOS.flush();
// Update the fragment.
F.setInst(Relaxed);
F.getContents() = Code;
F.getFixups() = Fixups;
return true;
}
bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
uint64_t OldSize = LF.getContents().size();
int64_t Value;
bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
if (!Abs)
report_fatal_error("sleb128 and uleb128 expressions must be absolute");
SmallString<8> &Data = LF.getContents();
Data.clear();
raw_svector_ostream OSE(Data);
if (LF.isSigned())
encodeSLEB128(Value, OSE);
else
encodeULEB128(Value, OSE);
OSE.flush();
return OldSize != LF.getContents().size();
}
bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
MCDwarfLineAddrFragment &DF) {
MCContext &Context = Layout.getAssembler().getContext();
uint64_t OldSize = DF.getContents().size();
int64_t AddrDelta;
bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
assert(Abs && "We created a line delta with an invalid expression");
(void) Abs;
int64_t LineDelta;
LineDelta = DF.getLineDelta();
SmallString<8> &Data = DF.getContents();
Data.clear();
raw_svector_ostream OSE(Data);
MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OSE);
OSE.flush();
return OldSize != Data.size();
}
bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
MCDwarfCallFrameFragment &DF) {
MCContext &Context = Layout.getAssembler().getContext();
uint64_t OldSize = DF.getContents().size();
int64_t AddrDelta;
bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
assert(Abs && "We created call frame with an invalid expression");
(void) Abs;
SmallString<8> &Data = DF.getContents();
Data.clear();
raw_svector_ostream OSE(Data);
MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
OSE.flush();
return OldSize != Data.size();
}
bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
// Holds the first fragment which needed relaxing during this layout. It will
// remain NULL if none were relaxed.
// When a fragment is relaxed, all the fragments following it should get
// invalidated because their offset is going to change.
MCFragment *FirstRelaxedFragment = nullptr;
// Attempt to relax all the fragments in the section.
for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
// Check if this is a fragment that needs relaxation.
bool RelaxedFrag = false;
switch(I->getKind()) {
default:
break;
case MCFragment::FT_Relaxable:
assert(!getRelaxAll() &&
"Did not expect a MCRelaxableFragment in RelaxAll mode");
RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
break;
case MCFragment::FT_Dwarf:
RelaxedFrag = relaxDwarfLineAddr(Layout,
*cast<MCDwarfLineAddrFragment>(I));
break;
case MCFragment::FT_DwarfFrame:
RelaxedFrag =
relaxDwarfCallFrameFragment(Layout,
*cast<MCDwarfCallFrameFragment>(I));
break;
case MCFragment::FT_LEB:
RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
break;
}
if (RelaxedFrag && !FirstRelaxedFragment)
FirstRelaxedFragment = I;
}
if (FirstRelaxedFragment) {
Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
return true;
}
return false;
}
bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
++stats::RelaxationSteps;
bool WasRelaxed = false;
for (iterator it = begin(), ie = end(); it != ie; ++it) {
MCSection &Sec = *it;
while (layoutSectionOnce(Layout, Sec))
WasRelaxed = true;
}
return WasRelaxed;
}
void MCAssembler::finishLayout(MCAsmLayout &Layout) {
// The layout is done. Mark every fragment as valid.
for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
}
}
// Debugging methods
namespace llvm {
raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
OS << "<MCFixup" << " Offset:" << AF.getOffset()
<< " Value:" << *AF.getValue()
<< " Kind:" << AF.getKind() << ">";
return OS;
}
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
void MCFragment::dump() {
raw_ostream &OS = llvm::errs();
OS << "<";
switch (getKind()) {
case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
case MCFragment::FT_Data: OS << "MCDataFragment"; break;
case MCFragment::FT_CompactEncodedInst:
OS << "MCCompactEncodedInstFragment"; break;
case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
case MCFragment::FT_SafeSEH: OS << "MCSafeSEHFragment"; break;
}
OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
<< " Offset:" << Offset
<< " HasInstructions:" << hasInstructions()
<< " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
switch (getKind()) {
case MCFragment::FT_Align: {
const MCAlignFragment *AF = cast<MCAlignFragment>(this);
if (AF->hasEmitNops())
OS << " (emit nops)";
OS << "\n ";
OS << " Alignment:" << AF->getAlignment()
<< " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
<< " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
break;
}
case MCFragment::FT_Data: {
const MCDataFragment *DF = cast<MCDataFragment>(this);
OS << "\n ";
OS << " Contents:[";
const SmallVectorImpl<char> &Contents = DF->getContents();
for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
if (i) OS << ",";
OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
}
OS << "] (" << Contents.size() << " bytes)";
if (DF->fixup_begin() != DF->fixup_end()) {
OS << ",\n ";
OS << " Fixups:[";
for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
ie = DF->fixup_end(); it != ie; ++it) {
if (it != DF->fixup_begin()) OS << ",\n ";
OS << *it;
}
OS << "]";
}
break;
}
case MCFragment::FT_CompactEncodedInst: {
const MCCompactEncodedInstFragment *CEIF =
cast<MCCompactEncodedInstFragment>(this);
OS << "\n ";
OS << " Contents:[";
const SmallVectorImpl<char> &Contents = CEIF->getContents();
for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
if (i) OS << ",";
OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
}
OS << "] (" << Contents.size() << " bytes)";
break;
}
case MCFragment::FT_Fill: {
const MCFillFragment *FF = cast<MCFillFragment>(this);
OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
<< " Size:" << FF->getSize();
break;
}
case MCFragment::FT_Relaxable: {
const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
OS << "\n ";
OS << " Inst:";
F->getInst().dump_pretty(OS);
break;
}
case MCFragment::FT_Org: {
const MCOrgFragment *OF = cast<MCOrgFragment>(this);
OS << "\n ";
OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
break;
}
case MCFragment::FT_Dwarf: {
const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
OS << "\n ";
OS << " AddrDelta:" << OF->getAddrDelta()
<< " LineDelta:" << OF->getLineDelta();
break;
}
case MCFragment::FT_DwarfFrame: {
const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
OS << "\n ";
OS << " AddrDelta:" << CF->getAddrDelta();
break;
}
case MCFragment::FT_LEB: {
const MCLEBFragment *LF = cast<MCLEBFragment>(this);
OS << "\n ";
OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
break;
}
case MCFragment::FT_SafeSEH: {
const MCSafeSEHFragment *F = cast<MCSafeSEHFragment>(this);
OS << "\n ";
OS << " Sym:" << F->getSymbol();
break;
}
}
OS << ">";
}
void MCAssembler::dump() {
raw_ostream &OS = llvm::errs();
OS << "<MCAssembler\n";
OS << " Sections:[\n ";
for (iterator it = begin(), ie = end(); it != ie; ++it) {
if (it != begin()) OS << ",\n ";
it->dump();
}
OS << "],\n";
OS << " Symbols:[";
for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
if (it != symbol_begin()) OS << ",\n ";
OS << "(";
it->dump();
OS << ", Index:" << it->getIndex() << ", ";
OS << ")";
}
OS << "]>\n";
}
#endif
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCParser/AsmParser.cpp | //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class implements the parser for assembly files.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/Twine.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCParser/AsmCond.h"
#include "llvm/MC/MCParser/AsmLexer.h"
#include "llvm/MC/MCParser/MCAsmParser.h"
#include "llvm/MC/MCParser/MCAsmParserUtils.h"
#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCTargetAsmParser.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include <cctype>
#include <deque>
#include <set>
#include <string>
#include <vector>
using namespace llvm;
MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
namespace {
/// \brief Helper types for tracking macro definitions.
typedef std::vector<AsmToken> MCAsmMacroArgument;
typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
struct MCAsmMacroParameter {
StringRef Name;
MCAsmMacroArgument Value;
bool Required;
bool Vararg;
MCAsmMacroParameter() : Required(false), Vararg(false) {}
};
typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
struct MCAsmMacro {
StringRef Name;
StringRef Body;
MCAsmMacroParameters Parameters;
public:
MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
: Name(N), Body(B), Parameters(std::move(P)) {}
};
/// \brief Helper class for storing information about an active macro
/// instantiation.
struct MacroInstantiation {
/// The location of the instantiation.
SMLoc InstantiationLoc;
/// The buffer where parsing should resume upon instantiation completion.
int ExitBuffer;
/// The location where parsing should resume upon instantiation completion.
SMLoc ExitLoc;
/// The depth of TheCondStack at the start of the instantiation.
size_t CondStackDepth;
public:
MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
};
struct ParseStatementInfo {
/// \brief The parsed operands from the last parsed statement.
SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
/// \brief The opcode from the last parsed instruction.
unsigned Opcode;
/// \brief Was there an error parsing the inline assembly?
bool ParseError;
SmallVectorImpl<AsmRewrite> *AsmRewrites;
ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
: Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
};
/// \brief The concrete assembly parser instance.
class AsmParser : public MCAsmParser {
AsmParser(const AsmParser &) = delete;
void operator=(const AsmParser &) = delete;
private:
AsmLexer Lexer;
MCContext &Ctx;
MCStreamer &Out;
const MCAsmInfo &MAI;
SourceMgr &SrcMgr;
SourceMgr::DiagHandlerTy SavedDiagHandler;
void *SavedDiagContext;
std::unique_ptr<MCAsmParserExtension> PlatformParser;
/// This is the current buffer index we're lexing from as managed by the
/// SourceMgr object.
unsigned CurBuffer;
AsmCond TheCondState;
std::vector<AsmCond> TheCondStack;
/// \brief maps directive names to handler methods in parser
/// extensions. Extensions register themselves in this map by calling
/// addDirectiveHandler.
StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
/// \brief Map of currently defined macros.
StringMap<MCAsmMacro> MacroMap;
/// \brief Stack of active macro instantiations.
std::vector<MacroInstantiation*> ActiveMacros;
/// \brief List of bodies of anonymous macros.
std::deque<MCAsmMacro> MacroLikeBodies;
/// Boolean tracking whether macro substitution is enabled.
unsigned MacrosEnabledFlag : 1;
/// \brief Keeps track of how many .macro's have been instantiated.
unsigned NumOfMacroInstantiations;
/// Flag tracking whether any errors have been encountered.
unsigned HadError : 1;
/// The values from the last parsed cpp hash file line comment if any.
StringRef CppHashFilename;
int64_t CppHashLineNumber;
SMLoc CppHashLoc;
unsigned CppHashBuf;
/// When generating dwarf for assembly source files we need to calculate the
/// logical line number based on the last parsed cpp hash file line comment
/// and current line. Since this is slow and messes up the SourceMgr's
/// cache we save the last info we queried with SrcMgr.FindLineNumber().
SMLoc LastQueryIDLoc;
unsigned LastQueryBuffer;
unsigned LastQueryLine;
/// AssemblerDialect. ~OU means unset value and use value provided by MAI.
unsigned AssemblerDialect;
/// \brief is Darwin compatibility enabled?
bool IsDarwin;
/// \brief Are we parsing ms-style inline assembly?
bool ParsingInlineAsm;
public:
AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
const MCAsmInfo &MAI);
~AsmParser() override;
bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
void addDirectiveHandler(StringRef Directive,
ExtensionDirectiveHandler Handler) override {
ExtensionDirectiveMap[Directive] = Handler;
}
void addAliasForDirective(StringRef Directive, StringRef Alias) override {
DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
}
public:
/// @name MCAsmParser Interface
/// {
SourceMgr &getSourceManager() override { return SrcMgr; }
MCAsmLexer &getLexer() override { return Lexer; }
MCContext &getContext() override { return Ctx; }
MCStreamer &getStreamer() override { return Out; }
unsigned getAssemblerDialect() override {
if (AssemblerDialect == ~0U)
return MAI.getAssemblerDialect();
else
return AssemblerDialect;
}
void setAssemblerDialect(unsigned i) override {
AssemblerDialect = i;
}
void Note(SMLoc L, const Twine &Msg,
ArrayRef<SMRange> Ranges = None) override;
bool Warning(SMLoc L, const Twine &Msg,
ArrayRef<SMRange> Ranges = None) override;
bool Error(SMLoc L, const Twine &Msg,
ArrayRef<SMRange> Ranges = None) override;
const AsmToken &Lex() override;
void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
bool isParsingInlineAsm() override { return ParsingInlineAsm; }
bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
unsigned &NumOutputs, unsigned &NumInputs,
SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
SmallVectorImpl<std::string> &Constraints,
SmallVectorImpl<std::string> &Clobbers,
const MCInstrInfo *MII, const MCInstPrinter *IP,
MCAsmParserSemaCallback &SI) override;
bool parseExpression(const MCExpr *&Res);
bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
SMLoc &EndLoc) override;
bool parseAbsoluteExpression(int64_t &Res) override;
/// \brief Parse an identifier or string (as a quoted identifier)
/// and set \p Res to the identifier contents.
bool parseIdentifier(StringRef &Res) override;
void eatToEndOfStatement() override;
void checkForValidSection() override;
/// }
private:
bool parseStatement(ParseStatementInfo &Info,
MCAsmParserSemaCallback *SI);
void eatToEndOfLine();
bool parseCppHashLineFilenameComment(const SMLoc &L);
void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
ArrayRef<MCAsmMacroParameter> Parameters);
bool expandMacro(raw_svector_ostream &OS, StringRef Body,
ArrayRef<MCAsmMacroParameter> Parameters,
ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
const SMLoc &L);
/// \brief Are macros enabled in the parser?
bool areMacrosEnabled() {return MacrosEnabledFlag;}
/// \brief Control a flag in the parser that enables or disables macros.
void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
/// \brief Lookup a previously defined macro.
/// \param Name Macro name.
/// \returns Pointer to macro. NULL if no such macro was defined.
const MCAsmMacro* lookupMacro(StringRef Name);
/// \brief Define a new macro with the given name and information.
void defineMacro(StringRef Name, MCAsmMacro Macro);
/// \brief Undefine a macro. If no such macro was defined, it's a no-op.
void undefineMacro(StringRef Name);
/// \brief Are we inside a macro instantiation?
bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
/// \brief Handle entry to macro instantiation.
///
/// \param M The macro.
/// \param NameLoc Instantiation location.
bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
/// \brief Handle exit from macro instantiation.
void handleMacroExit();
/// \brief Extract AsmTokens for a macro argument.
bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
/// \brief Parse all macro arguments for a given macro.
bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
void printMacroInstantiations();
void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
ArrayRef<SMRange> Ranges = None) const {
SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
}
static void DiagHandler(const SMDiagnostic &Diag, void *Context);
/// \brief Enter the specified file. This returns true on failure.
bool enterIncludeFile(const std::string &Filename);
/// \brief Process the specified file for the .incbin directive.
/// This returns true on failure.
bool processIncbinFile(const std::string &Filename);
/// \brief Reset the current lexer position to that given by \p Loc. The
/// current token is not set; clients should ensure Lex() is called
/// subsequently.
///
/// \param InBuffer If not 0, should be the known buffer id that contains the
/// location.
void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
/// \brief Parse up to the end of statement and a return the contents from the
/// current token until the end of the statement; the current token on exit
/// will be either the EndOfStatement or EOF.
StringRef parseStringToEndOfStatement() override;
/// \brief Parse until the end of a statement or a comma is encountered,
/// return the contents from the current token up to the end or comma.
StringRef parseStringToComma();
bool parseAssignment(StringRef Name, bool allow_redef,
bool NoDeadStrip = false);
unsigned getBinOpPrecedence(AsmToken::TokenKind K,
MCBinaryExpr::Opcode &Kind);
bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
// Generic (target and platform independent) directive parsing.
enum DirectiveKind {
DK_NO_DIRECTIVE, // Placeholder
DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
DK_MACROS_ON, DK_MACROS_OFF,
DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
DK_SLEB128, DK_ULEB128,
DK_ERR, DK_ERROR, DK_WARNING,
DK_END
};
/// \brief Maps directive name --> DirectiveKind enum, for
/// directives parsed by this class.
StringMap<DirectiveKind> DirectiveKindMap;
// ".ascii", ".asciz", ".string"
bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
bool parseDirectiveOctaValue(); // ".octa"
bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
bool parseDirectiveFill(); // ".fill"
bool parseDirectiveZero(); // ".zero"
// ".set", ".equ", ".equiv"
bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
bool parseDirectiveOrg(); // ".org"
// ".align{,32}", ".p2align{,w,l}"
bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
// ".file", ".line", ".loc", ".stabs"
bool parseDirectiveFile(SMLoc DirectiveLoc);
bool parseDirectiveLine();
bool parseDirectiveLoc();
bool parseDirectiveStabs();
// .cfi directives
bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
bool parseDirectiveCFIWindowSave();
bool parseDirectiveCFISections();
bool parseDirectiveCFIStartProc();
bool parseDirectiveCFIEndProc();
bool parseDirectiveCFIDefCfaOffset();
bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
bool parseDirectiveCFIAdjustCfaOffset();
bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
bool parseDirectiveCFIRememberState();
bool parseDirectiveCFIRestoreState();
bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
bool parseDirectiveCFIEscape();
bool parseDirectiveCFISignalFrame();
bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
// macro directives
bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
bool parseDirectiveExitMacro(StringRef Directive);
bool parseDirectiveEndMacro(StringRef Directive);
bool parseDirectiveMacro(SMLoc DirectiveLoc);
bool parseDirectiveMacrosOnOff(StringRef Directive);
// ".bundle_align_mode"
bool parseDirectiveBundleAlignMode();
// ".bundle_lock"
bool parseDirectiveBundleLock();
// ".bundle_unlock"
bool parseDirectiveBundleUnlock();
// ".space", ".skip"
bool parseDirectiveSpace(StringRef IDVal);
// .sleb128 (Signed=true) and .uleb128 (Signed=false)
bool parseDirectiveLEB128(bool Signed);
/// \brief Parse a directive like ".globl" which
/// accepts a single symbol (which should be a label or an external).
bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
bool parseDirectiveAbort(); // ".abort"
bool parseDirectiveInclude(); // ".include"
bool parseDirectiveIncbin(); // ".incbin"
// ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
// ".ifb" or ".ifnb", depending on ExpectBlank.
bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
// ".ifc" or ".ifnc", depending on ExpectEqual.
bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
// ".ifeqs" or ".ifnes", depending on ExpectEqual.
bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
// ".ifdef" or ".ifndef", depending on expect_defined
bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
bool parseEscapedString(std::string &Data) override;
const MCExpr *applyModifierToExpr(const MCExpr *E,
MCSymbolRefExpr::VariantKind Variant);
// Macro-like directives
MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
raw_svector_ostream &OS);
bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
// "_emit" or "__emit"
bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
size_t Len);
// "align"
bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
// "end"
bool parseDirectiveEnd(SMLoc DirectiveLoc);
// ".err" or ".error"
bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
// ".warning"
bool parseDirectiveWarning(SMLoc DirectiveLoc);
void initializeDirectiveKindMap();
};
}
namespace llvm {
extern MCAsmParserExtension *createDarwinAsmParser();
extern MCAsmParserExtension *createELFAsmParser();
extern MCAsmParserExtension *createCOFFAsmParser();
}
enum { DEFAULT_ADDRSPACE = 0 };
AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
const MCAsmInfo &MAI)
: Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
// Save the old handler.
SavedDiagHandler = SrcMgr.getDiagHandler();
SavedDiagContext = SrcMgr.getDiagContext();
// Set our own handler which calls the saved handler.
SrcMgr.setDiagHandler(DiagHandler, this);
Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
// Initialize the platform / file format parser.
switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
case MCObjectFileInfo::IsCOFF:
PlatformParser.reset(createCOFFAsmParser());
break;
case MCObjectFileInfo::IsMachO:
PlatformParser.reset(createDarwinAsmParser());
IsDarwin = true;
break;
case MCObjectFileInfo::IsELF:
PlatformParser.reset(createELFAsmParser());
break;
}
PlatformParser->Initialize(*this);
initializeDirectiveKindMap();
NumOfMacroInstantiations = 0;
}
AsmParser::~AsmParser() {
assert((HadError || ActiveMacros.empty()) &&
"Unexpected active macro instantiation!");
}
void AsmParser::printMacroInstantiations() {
// Print the active macro instantiation stack.
for (std::vector<MacroInstantiation *>::const_reverse_iterator
it = ActiveMacros.rbegin(),
ie = ActiveMacros.rend();
it != ie; ++it)
printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
"while in macro instantiation");
}
void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
printMacroInstantiations();
}
bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
if (getTargetParser().getTargetOptions().MCFatalWarnings)
return Error(L, Msg, Ranges);
printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
printMacroInstantiations();
return false;
}
bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
HadError = true;
printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
printMacroInstantiations();
return true;
}
bool AsmParser::enterIncludeFile(const std::string &Filename) {
std::string IncludedFile;
unsigned NewBuf =
SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
if (!NewBuf)
return true;
CurBuffer = NewBuf;
Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
return false;
}
/// Process the specified .incbin file by searching for it in the include paths
/// then just emitting the byte contents of the file to the streamer. This
/// returns true on failure.
bool AsmParser::processIncbinFile(const std::string &Filename) {
std::string IncludedFile;
unsigned NewBuf =
SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
if (!NewBuf)
return true;
// Pick up the bytes from the file and emit them.
getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
return false;
}
void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
Loc.getPointer());
}
const AsmToken &AsmParser::Lex() {
const AsmToken *tok = &Lexer.Lex();
if (tok->is(AsmToken::Eof)) {
// If this is the end of an included file, pop the parent file off the
// include stack.
SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
if (ParentIncludeLoc != SMLoc()) {
jumpToLoc(ParentIncludeLoc);
tok = &Lexer.Lex();
}
}
if (tok->is(AsmToken::Error))
Error(Lexer.getErrLoc(), Lexer.getErr());
return *tok;
}
bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
// Create the initial section, if requested.
if (!NoInitialTextSection)
Out.InitSections(false);
// Prime the lexer.
Lex();
HadError = false;
AsmCond StartingCondState = TheCondState;
// If we are generating dwarf for assembly source files save the initial text
// section and generate a .file directive.
if (getContext().getGenDwarfForAssembly()) {
MCSection *Sec = getStreamer().getCurrentSection().first;
if (!Sec->getBeginSymbol()) {
MCSymbol *SectionStartSym = getContext().createTempSymbol();
getStreamer().EmitLabel(SectionStartSym);
Sec->setBeginSymbol(SectionStartSym);
}
bool InsertResult = getContext().addGenDwarfSection(Sec);
assert(InsertResult && ".text section should not have debug info yet");
(void)InsertResult;
getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
0, StringRef(), getContext().getMainFileName()));
}
// While we have input, parse each statement.
while (Lexer.isNot(AsmToken::Eof)) {
ParseStatementInfo Info;
if (!parseStatement(Info, nullptr))
continue;
// We had an error, validate that one was emitted and recover by skipping to
// the next line.
assert(HadError && "Parse statement returned an error, but none emitted!");
eatToEndOfStatement();
}
if (TheCondState.TheCond != StartingCondState.TheCond ||
TheCondState.Ignore != StartingCondState.Ignore)
return TokError("unmatched .ifs or .elses");
// Check to see there are no empty DwarfFile slots.
const auto &LineTables = getContext().getMCDwarfLineTables();
if (!LineTables.empty()) {
unsigned Index = 0;
for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
if (File.Name.empty() && Index != 0)
TokError("unassigned file number: " + Twine(Index) +
" for .file directives");
++Index;
}
}
// Check to see that all assembler local symbols were actually defined.
// Targets that don't do subsections via symbols may not want this, though,
// so conservatively exclude them. Only do this if we're finalizing, though,
// as otherwise we won't necessarilly have seen everything yet.
if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
const MCContext::SymbolTable &Symbols = getContext().getSymbols();
for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
e = Symbols.end();
i != e; ++i) {
MCSymbol *Sym = i->getValue();
// Variable symbols may not be marked as defined, so check those
// explicitly. If we know it's a variable, we have a definition for
// the purposes of this check.
if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
// FIXME: We would really like to refer back to where the symbol was
// first referenced for a source location. We need to add something
// to track that. Currently, we just point to the end of the file.
printMessage(
getLexer().getLoc(), SourceMgr::DK_Error,
"assembler local symbol '" + Sym->getName() + "' not defined");
}
}
// Finalize the output stream if there are no errors and if the client wants
// us to.
if (!HadError && !NoFinalize)
Out.Finish();
return HadError;
}
void AsmParser::checkForValidSection() {
if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
TokError("expected section directive before assembly directive");
Out.InitSections(false);
}
}
/// \brief Throw away the rest of the line for testing purposes.
void AsmParser::eatToEndOfStatement() {
while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Lex();
// Eat EOL.
if (Lexer.is(AsmToken::EndOfStatement))
Lex();
}
StringRef AsmParser::parseStringToEndOfStatement() {
const char *Start = getTok().getLoc().getPointer();
while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Lex();
const char *End = getTok().getLoc().getPointer();
return StringRef(Start, End - Start);
}
StringRef AsmParser::parseStringToComma() {
const char *Start = getTok().getLoc().getPointer();
while (Lexer.isNot(AsmToken::EndOfStatement) &&
Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Lex();
const char *End = getTok().getLoc().getPointer();
return StringRef(Start, End - Start);
}
/// \brief Parse a paren expression and return it.
/// NOTE: This assumes the leading '(' has already been consumed.
///
/// parenexpr ::= expr)
///
bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
if (parseExpression(Res))
return true;
if (Lexer.isNot(AsmToken::RParen))
return TokError("expected ')' in parentheses expression");
EndLoc = Lexer.getTok().getEndLoc();
Lex();
return false;
}
/// \brief Parse a bracket expression and return it.
/// NOTE: This assumes the leading '[' has already been consumed.
///
/// bracketexpr ::= expr]
///
bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
if (parseExpression(Res))
return true;
if (Lexer.isNot(AsmToken::RBrac))
return TokError("expected ']' in brackets expression");
EndLoc = Lexer.getTok().getEndLoc();
Lex();
return false;
}
/// \brief Parse a primary expression and return it.
/// primaryexpr ::= (parenexpr
/// primaryexpr ::= symbol
/// primaryexpr ::= number
/// primaryexpr ::= '.'
/// primaryexpr ::= ~,+,- primaryexpr
bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
SMLoc FirstTokenLoc = getLexer().getLoc();
AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
switch (FirstTokenKind) {
default:
return TokError("unknown token in expression");
// If we have an error assume that we've already handled it.
case AsmToken::Error:
return true;
case AsmToken::Exclaim:
Lex(); // Eat the operator.
if (parsePrimaryExpr(Res, EndLoc))
return true;
Res = MCUnaryExpr::createLNot(Res, getContext());
return false;
case AsmToken::Dollar:
case AsmToken::At:
case AsmToken::String:
case AsmToken::Identifier: {
StringRef Identifier;
if (parseIdentifier(Identifier)) {
if (FirstTokenKind == AsmToken::Dollar) {
if (Lexer.getMAI().getDollarIsPC()) {
// This is a '$' reference, which references the current PC. Emit a
// temporary label to the streamer and refer to it.
MCSymbol *Sym = Ctx.createTempSymbol();
Out.EmitLabel(Sym);
Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
getContext());
EndLoc = FirstTokenLoc;
return false;
}
return Error(FirstTokenLoc, "invalid token in expression");
}
}
// Parse symbol variant
std::pair<StringRef, StringRef> Split;
if (!MAI.useParensForSymbolVariant()) {
if (FirstTokenKind == AsmToken::String) {
if (Lexer.is(AsmToken::At)) {
Lexer.Lex(); // eat @
SMLoc AtLoc = getLexer().getLoc();
StringRef VName;
if (parseIdentifier(VName))
return Error(AtLoc, "expected symbol variant after '@'");
Split = std::make_pair(Identifier, VName);
}
} else {
Split = Identifier.split('@');
}
} else if (Lexer.is(AsmToken::LParen)) {
Lexer.Lex(); // eat (
StringRef VName;
parseIdentifier(VName);
if (Lexer.isNot(AsmToken::RParen)) {
return Error(Lexer.getTok().getLoc(),
"unexpected token in variant, expected ')'");
}
Lexer.Lex(); // eat )
Split = std::make_pair(Identifier, VName);
}
EndLoc = SMLoc::getFromPointer(Identifier.end());
// This is a symbol reference.
StringRef SymbolName = Identifier;
MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
// Lookup the symbol variant if used.
if (Split.second.size()) {
Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
if (Variant != MCSymbolRefExpr::VK_Invalid) {
SymbolName = Split.first;
} else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Variant = MCSymbolRefExpr::VK_None;
} else {
return Error(SMLoc::getFromPointer(Split.second.begin()),
"invalid variant '" + Split.second + "'");
}
}
MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
// If this is an absolute variable reference, substitute it now to preserve
// semantics in the face of reassignment.
if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
if (Variant)
return Error(EndLoc, "unexpected modifier on variable reference");
Res = Sym->getVariableValue();
return false;
}
// Otherwise create a symbol ref.
Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
return false;
}
case AsmToken::BigNum:
return TokError("literal value out of range for directive");
case AsmToken::Integer: {
SMLoc Loc = getTok().getLoc();
int64_t IntVal = getTok().getIntVal();
Res = MCConstantExpr::create(IntVal, getContext());
EndLoc = Lexer.getTok().getEndLoc();
Lex(); // Eat token.
// Look for 'b' or 'f' following an Integer as a directional label
if (Lexer.getKind() == AsmToken::Identifier) {
StringRef IDVal = getTok().getString();
// Lookup the symbol variant if used.
std::pair<StringRef, StringRef> Split = IDVal.split('@');
MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
if (Split.first.size() != IDVal.size()) {
Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
if (Variant == MCSymbolRefExpr::VK_Invalid)
return TokError("invalid variant '" + Split.second + "'");
IDVal = Split.first;
}
if (IDVal == "f" || IDVal == "b") {
MCSymbol *Sym =
Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
if (IDVal == "b" && Sym->isUndefined())
return Error(Loc, "invalid reference to undefined symbol");
EndLoc = Lexer.getTok().getEndLoc();
Lex(); // Eat identifier.
}
}
return false;
}
case AsmToken::Real: {
APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Res = MCConstantExpr::create(IntVal, getContext());
EndLoc = Lexer.getTok().getEndLoc();
Lex(); // Eat token.
return false;
}
case AsmToken::Dot: {
// This is a '.' reference, which references the current PC. Emit a
// temporary label to the streamer and refer to it.
MCSymbol *Sym = Ctx.createTempSymbol();
Out.EmitLabel(Sym);
Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
EndLoc = Lexer.getTok().getEndLoc();
Lex(); // Eat identifier.
return false;
}
case AsmToken::LParen:
Lex(); // Eat the '('.
return parseParenExpr(Res, EndLoc);
case AsmToken::LBrac:
if (!PlatformParser->HasBracketExpressions())
return TokError("brackets expression not supported on this target");
Lex(); // Eat the '['.
return parseBracketExpr(Res, EndLoc);
case AsmToken::Minus:
Lex(); // Eat the operator.
if (parsePrimaryExpr(Res, EndLoc))
return true;
Res = MCUnaryExpr::createMinus(Res, getContext());
return false;
case AsmToken::Plus:
Lex(); // Eat the operator.
if (parsePrimaryExpr(Res, EndLoc))
return true;
Res = MCUnaryExpr::createPlus(Res, getContext());
return false;
case AsmToken::Tilde:
Lex(); // Eat the operator.
if (parsePrimaryExpr(Res, EndLoc))
return true;
Res = MCUnaryExpr::createNot(Res, getContext());
return false;
}
}
bool AsmParser::parseExpression(const MCExpr *&Res) {
SMLoc EndLoc;
return parseExpression(Res, EndLoc);
}
const MCExpr *
AsmParser::applyModifierToExpr(const MCExpr *E,
MCSymbolRefExpr::VariantKind Variant) {
// Ask the target implementation about this expression first.
const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
if (NewE)
return NewE;
// Recurse over the given expression, rebuilding it to apply the given variant
// if there is exactly one symbol.
switch (E->getKind()) {
case MCExpr::Target:
case MCExpr::Constant:
return nullptr;
case MCExpr::SymbolRef: {
const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
TokError("invalid variant on expression '" + getTok().getIdentifier() +
"' (already modified)");
return E;
}
return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
}
case MCExpr::Unary: {
const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
if (!Sub)
return nullptr;
return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
}
case MCExpr::Binary: {
const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
if (!LHS && !RHS)
return nullptr;
if (!LHS)
LHS = BE->getLHS();
if (!RHS)
RHS = BE->getRHS();
return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
}
}
llvm_unreachable("Invalid expression kind!");
}
/// \brief Parse an expression and return it.
///
/// expr ::= expr &&,|| expr -> lowest.
/// expr ::= expr |,^,&,! expr
/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
/// expr ::= expr <<,>> expr
/// expr ::= expr +,- expr
/// expr ::= expr *,/,% expr -> highest.
/// expr ::= primaryexpr
///
bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
// Parse the expression.
Res = nullptr;
if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
return true;
// As a special case, we support 'a op b @ modifier' by rewriting the
// expression to include the modifier. This is inefficient, but in general we
// expect users to use 'a@modifier op b'.
if (Lexer.getKind() == AsmToken::At) {
Lex();
if (Lexer.isNot(AsmToken::Identifier))
return TokError("unexpected symbol modifier following '@'");
MCSymbolRefExpr::VariantKind Variant =
MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
if (Variant == MCSymbolRefExpr::VK_Invalid)
return TokError("invalid variant '" + getTok().getIdentifier() + "'");
const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
if (!ModifiedRes) {
return TokError("invalid modifier '" + getTok().getIdentifier() +
"' (no symbols present)");
}
Res = ModifiedRes;
Lex();
}
// Try to constant fold it up front, if possible.
int64_t Value;
if (Res->evaluateAsAbsolute(Value))
Res = MCConstantExpr::create(Value, getContext());
return false;
}
bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Res = nullptr;
return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
}
bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
SMLoc &EndLoc) {
if (parseParenExpr(Res, EndLoc))
return true;
for (; ParenDepth > 0; --ParenDepth) {
if (parseBinOpRHS(1, Res, EndLoc))
return true;
// We don't Lex() the last RParen.
// This is the same behavior as parseParenExpression().
if (ParenDepth - 1 > 0) {
if (Lexer.isNot(AsmToken::RParen))
return TokError("expected ')' in parentheses expression");
EndLoc = Lexer.getTok().getEndLoc();
Lex();
}
}
return false;
}
bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
const MCExpr *Expr;
SMLoc StartLoc = Lexer.getLoc();
if (parseExpression(Expr))
return true;
if (!Expr->evaluateAsAbsolute(Res))
return Error(StartLoc, "expected absolute expression");
return false;
}
unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
MCBinaryExpr::Opcode &Kind) {
switch (K) {
default:
return 0; // not a binop.
// Lowest Precedence: &&, ||
case AsmToken::AmpAmp:
Kind = MCBinaryExpr::LAnd;
return 1;
case AsmToken::PipePipe:
Kind = MCBinaryExpr::LOr;
return 1;
// Low Precedence: |, &, ^
//
// FIXME: gas seems to support '!' as an infix operator?
case AsmToken::Pipe:
Kind = MCBinaryExpr::Or;
return 2;
case AsmToken::Caret:
Kind = MCBinaryExpr::Xor;
return 2;
case AsmToken::Amp:
Kind = MCBinaryExpr::And;
return 2;
// Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
case AsmToken::EqualEqual:
Kind = MCBinaryExpr::EQ;
return 3;
case AsmToken::ExclaimEqual:
case AsmToken::LessGreater:
Kind = MCBinaryExpr::NE;
return 3;
case AsmToken::Less:
Kind = MCBinaryExpr::LT;
return 3;
case AsmToken::LessEqual:
Kind = MCBinaryExpr::LTE;
return 3;
case AsmToken::Greater:
Kind = MCBinaryExpr::GT;
return 3;
case AsmToken::GreaterEqual:
Kind = MCBinaryExpr::GTE;
return 3;
// Intermediate Precedence: <<, >>
case AsmToken::LessLess:
Kind = MCBinaryExpr::Shl;
return 4;
case AsmToken::GreaterGreater:
Kind = MAI.shouldUseLogicalShr() ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
return 4;
// High Intermediate Precedence: +, -
case AsmToken::Plus:
Kind = MCBinaryExpr::Add;
return 5;
case AsmToken::Minus:
Kind = MCBinaryExpr::Sub;
return 5;
// Highest Precedence: *, /, %
case AsmToken::Star:
Kind = MCBinaryExpr::Mul;
return 6;
case AsmToken::Slash:
Kind = MCBinaryExpr::Div;
return 6;
case AsmToken::Percent:
Kind = MCBinaryExpr::Mod;
return 6;
}
}
/// \brief Parse all binary operators with precedence >= 'Precedence'.
/// Res contains the LHS of the expression on input.
bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
SMLoc &EndLoc) {
while (1) {
MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
// If the next token is lower precedence than we are allowed to eat, return
// successfully with what we ate already.
if (TokPrec < Precedence)
return false;
Lex();
// Eat the next primary expression.
const MCExpr *RHS;
if (parsePrimaryExpr(RHS, EndLoc))
return true;
// If BinOp binds less tightly with RHS than the operator after RHS, let
// the pending operator take RHS as its LHS.
MCBinaryExpr::Opcode Dummy;
unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
return true;
// Merge LHS and RHS according to operator.
Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
}
}
/// ParseStatement:
/// ::= EndOfStatement
/// ::= Label* Directive ...Operands... EndOfStatement
/// ::= Label* Identifier OperandList* EndOfStatement
bool AsmParser::parseStatement(ParseStatementInfo &Info,
MCAsmParserSemaCallback *SI) {
if (Lexer.is(AsmToken::EndOfStatement)) {
Out.AddBlankLine();
Lex();
return false;
}
// Statements always start with an identifier or are a full line comment.
AsmToken ID = getTok();
SMLoc IDLoc = ID.getLoc();
StringRef IDVal;
int64_t LocalLabelVal = -1;
// A full line comment is a '#' as the first token.
if (Lexer.is(AsmToken::Hash))
return parseCppHashLineFilenameComment(IDLoc);
// Allow an integer followed by a ':' as a directional local label.
if (Lexer.is(AsmToken::Integer)) {
LocalLabelVal = getTok().getIntVal();
if (LocalLabelVal < 0) {
if (!TheCondState.Ignore)
return TokError("unexpected token at start of statement");
IDVal = "";
} else {
IDVal = getTok().getString();
Lex(); // Consume the integer token to be used as an identifier token.
if (Lexer.getKind() != AsmToken::Colon) {
if (!TheCondState.Ignore)
return TokError("unexpected token at start of statement");
}
}
} else if (Lexer.is(AsmToken::Dot)) {
// Treat '.' as a valid identifier in this context.
Lex();
IDVal = ".";
} else if (parseIdentifier(IDVal)) {
if (!TheCondState.Ignore)
return TokError("unexpected token at start of statement");
IDVal = "";
}
// Handle conditional assembly here before checking for skipping. We
// have to do this so that .endif isn't skipped in a ".if 0" block for
// example.
StringMap<DirectiveKind>::const_iterator DirKindIt =
DirectiveKindMap.find(IDVal);
DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
? DK_NO_DIRECTIVE
: DirKindIt->getValue();
switch (DirKind) {
default:
break;
case DK_IF:
case DK_IFEQ:
case DK_IFGE:
case DK_IFGT:
case DK_IFLE:
case DK_IFLT:
case DK_IFNE:
return parseDirectiveIf(IDLoc, DirKind);
case DK_IFB:
return parseDirectiveIfb(IDLoc, true);
case DK_IFNB:
return parseDirectiveIfb(IDLoc, false);
case DK_IFC:
return parseDirectiveIfc(IDLoc, true);
case DK_IFEQS:
return parseDirectiveIfeqs(IDLoc, true);
case DK_IFNC:
return parseDirectiveIfc(IDLoc, false);
case DK_IFNES:
return parseDirectiveIfeqs(IDLoc, false);
case DK_IFDEF:
return parseDirectiveIfdef(IDLoc, true);
case DK_IFNDEF:
case DK_IFNOTDEF:
return parseDirectiveIfdef(IDLoc, false);
case DK_ELSEIF:
return parseDirectiveElseIf(IDLoc);
case DK_ELSE:
return parseDirectiveElse(IDLoc);
case DK_ENDIF:
return parseDirectiveEndIf(IDLoc);
}
// Ignore the statement if in the middle of inactive conditional
// (e.g. ".if 0").
if (TheCondState.Ignore) {
eatToEndOfStatement();
return false;
}
// FIXME: Recurse on local labels?
// See what kind of statement we have.
switch (Lexer.getKind()) {
case AsmToken::Colon: {
checkForValidSection();
// identifier ':' -> Label.
Lex();
// Diagnose attempt to use '.' as a label.
if (IDVal == ".")
return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
// Diagnose attempt to use a variable as a label.
//
// FIXME: Diagnostics. Note the location of the definition as a label.
// FIXME: This doesn't diagnose assignment to a symbol which has been
// implicitly marked as external.
MCSymbol *Sym;
if (LocalLabelVal == -1) {
if (ParsingInlineAsm && SI) {
StringRef RewrittenLabel =
SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
assert(RewrittenLabel.size() &&
"We should have an internal name here.");
Info.AsmRewrites->push_back(AsmRewrite(AOK_Label, IDLoc,
IDVal.size(), RewrittenLabel));
IDVal = RewrittenLabel;
}
Sym = getContext().getOrCreateSymbol(IDVal);
} else
Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Sym->redefineIfPossible();
if (!Sym->isUndefined() || Sym->isVariable())
return Error(IDLoc, "invalid symbol redefinition");
// Emit the label.
if (!ParsingInlineAsm)
Out.EmitLabel(Sym);
// If we are generating dwarf for assembly source files then gather the
// info to make a dwarf label entry for this label if needed.
if (getContext().getGenDwarfForAssembly())
MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
IDLoc);
getTargetParser().onLabelParsed(Sym);
// Consume any end of statement token, if present, to avoid spurious
// AddBlankLine calls().
if (Lexer.is(AsmToken::EndOfStatement)) {
Lex();
if (Lexer.is(AsmToken::Eof))
return false;
}
return false;
}
case AsmToken::Equal:
// identifier '=' ... -> assignment statement
Lex();
return parseAssignment(IDVal, true);
default: // Normal instruction or directive.
break;
}
// If macros are enabled, check to see if this is a macro instantiation.
if (areMacrosEnabled())
if (const MCAsmMacro *M = lookupMacro(IDVal)) {
return handleMacroEntry(M, IDLoc);
}
// Otherwise, we have a normal instruction or directive.
// Directives start with "."
if (IDVal[0] == '.' && IDVal != ".") {
// There are several entities interested in parsing directives:
//
// 1. The target-specific assembly parser. Some directives are target
// specific or may potentially behave differently on certain targets.
// 2. Asm parser extensions. For example, platform-specific parsers
// (like the ELF parser) register themselves as extensions.
// 3. The generic directive parser implemented by this class. These are
// all the directives that behave in a target and platform independent
// manner, or at least have a default behavior that's shared between
// all targets and platforms.
// First query the target-specific parser. It will return 'true' if it
// isn't interested in this directive.
if (!getTargetParser().ParseDirective(ID))
return false;
// Next, check the extension directive map to see if any extension has
// registered itself to parse this directive.
std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
ExtensionDirectiveMap.lookup(IDVal);
if (Handler.first)
return (*Handler.second)(Handler.first, IDVal, IDLoc);
// Finally, if no one else is interested in this directive, it must be
// generic and familiar to this class.
switch (DirKind) {
default:
break;
case DK_SET:
case DK_EQU:
return parseDirectiveSet(IDVal, true);
case DK_EQUIV:
return parseDirectiveSet(IDVal, false);
case DK_ASCII:
return parseDirectiveAscii(IDVal, false);
case DK_ASCIZ:
case DK_STRING:
return parseDirectiveAscii(IDVal, true);
case DK_BYTE:
return parseDirectiveValue(1);
case DK_SHORT:
case DK_VALUE:
case DK_2BYTE:
return parseDirectiveValue(2);
case DK_LONG:
case DK_INT:
case DK_4BYTE:
return parseDirectiveValue(4);
case DK_QUAD:
case DK_8BYTE:
return parseDirectiveValue(8);
case DK_OCTA:
return parseDirectiveOctaValue();
case DK_SINGLE:
case DK_FLOAT:
return parseDirectiveRealValue(APFloat::IEEEsingle);
case DK_DOUBLE:
return parseDirectiveRealValue(APFloat::IEEEdouble);
case DK_ALIGN: {
bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
}
case DK_ALIGN32: {
bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
}
case DK_BALIGN:
return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
case DK_BALIGNW:
return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
case DK_BALIGNL:
return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
case DK_P2ALIGN:
return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
case DK_P2ALIGNW:
return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
case DK_P2ALIGNL:
return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
case DK_ORG:
return parseDirectiveOrg();
case DK_FILL:
return parseDirectiveFill();
case DK_ZERO:
return parseDirectiveZero();
case DK_EXTERN:
eatToEndOfStatement(); // .extern is the default, ignore it.
return false;
case DK_GLOBL:
case DK_GLOBAL:
return parseDirectiveSymbolAttribute(MCSA_Global);
case DK_LAZY_REFERENCE:
return parseDirectiveSymbolAttribute(MCSA_LazyReference);
case DK_NO_DEAD_STRIP:
return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
case DK_SYMBOL_RESOLVER:
return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
case DK_PRIVATE_EXTERN:
return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
case DK_REFERENCE:
return parseDirectiveSymbolAttribute(MCSA_Reference);
case DK_WEAK_DEFINITION:
return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
case DK_WEAK_REFERENCE:
return parseDirectiveSymbolAttribute(MCSA_WeakReference);
case DK_WEAK_DEF_CAN_BE_HIDDEN:
return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
case DK_COMM:
case DK_COMMON:
return parseDirectiveComm(/*IsLocal=*/false);
case DK_LCOMM:
return parseDirectiveComm(/*IsLocal=*/true);
case DK_ABORT:
return parseDirectiveAbort();
case DK_INCLUDE:
return parseDirectiveInclude();
case DK_INCBIN:
return parseDirectiveIncbin();
case DK_CODE16:
case DK_CODE16GCC:
return TokError(Twine(IDVal) + " not supported yet");
case DK_REPT:
return parseDirectiveRept(IDLoc, IDVal);
case DK_IRP:
return parseDirectiveIrp(IDLoc);
case DK_IRPC:
return parseDirectiveIrpc(IDLoc);
case DK_ENDR:
return parseDirectiveEndr(IDLoc);
case DK_BUNDLE_ALIGN_MODE:
return parseDirectiveBundleAlignMode();
case DK_BUNDLE_LOCK:
return parseDirectiveBundleLock();
case DK_BUNDLE_UNLOCK:
return parseDirectiveBundleUnlock();
case DK_SLEB128:
return parseDirectiveLEB128(true);
case DK_ULEB128:
return parseDirectiveLEB128(false);
case DK_SPACE:
case DK_SKIP:
return parseDirectiveSpace(IDVal);
case DK_FILE:
return parseDirectiveFile(IDLoc);
case DK_LINE:
return parseDirectiveLine();
case DK_LOC:
return parseDirectiveLoc();
case DK_STABS:
return parseDirectiveStabs();
case DK_CFI_SECTIONS:
return parseDirectiveCFISections();
case DK_CFI_STARTPROC:
return parseDirectiveCFIStartProc();
case DK_CFI_ENDPROC:
return parseDirectiveCFIEndProc();
case DK_CFI_DEF_CFA:
return parseDirectiveCFIDefCfa(IDLoc);
case DK_CFI_DEF_CFA_OFFSET:
return parseDirectiveCFIDefCfaOffset();
case DK_CFI_ADJUST_CFA_OFFSET:
return parseDirectiveCFIAdjustCfaOffset();
case DK_CFI_DEF_CFA_REGISTER:
return parseDirectiveCFIDefCfaRegister(IDLoc);
case DK_CFI_OFFSET:
return parseDirectiveCFIOffset(IDLoc);
case DK_CFI_REL_OFFSET:
return parseDirectiveCFIRelOffset(IDLoc);
case DK_CFI_PERSONALITY:
return parseDirectiveCFIPersonalityOrLsda(true);
case DK_CFI_LSDA:
return parseDirectiveCFIPersonalityOrLsda(false);
case DK_CFI_REMEMBER_STATE:
return parseDirectiveCFIRememberState();
case DK_CFI_RESTORE_STATE:
return parseDirectiveCFIRestoreState();
case DK_CFI_SAME_VALUE:
return parseDirectiveCFISameValue(IDLoc);
case DK_CFI_RESTORE:
return parseDirectiveCFIRestore(IDLoc);
case DK_CFI_ESCAPE:
return parseDirectiveCFIEscape();
case DK_CFI_SIGNAL_FRAME:
return parseDirectiveCFISignalFrame();
case DK_CFI_UNDEFINED:
return parseDirectiveCFIUndefined(IDLoc);
case DK_CFI_REGISTER:
return parseDirectiveCFIRegister(IDLoc);
case DK_CFI_WINDOW_SAVE:
return parseDirectiveCFIWindowSave();
case DK_MACROS_ON:
case DK_MACROS_OFF:
return parseDirectiveMacrosOnOff(IDVal);
case DK_MACRO:
return parseDirectiveMacro(IDLoc);
case DK_EXITM:
return parseDirectiveExitMacro(IDVal);
case DK_ENDM:
case DK_ENDMACRO:
return parseDirectiveEndMacro(IDVal);
case DK_PURGEM:
return parseDirectivePurgeMacro(IDLoc);
case DK_END:
return parseDirectiveEnd(IDLoc);
case DK_ERR:
return parseDirectiveError(IDLoc, false);
case DK_ERROR:
return parseDirectiveError(IDLoc, true);
case DK_WARNING:
return parseDirectiveWarning(IDLoc);
}
return Error(IDLoc, "unknown directive");
}
// __asm _emit or __asm __emit
if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
IDVal == "_EMIT" || IDVal == "__EMIT"))
return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
// __asm align
if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
return parseDirectiveMSAlign(IDLoc, Info);
checkForValidSection();
// Canonicalize the opcode to lower case.
std::string OpcodeStr = IDVal.lower();
ParseInstructionInfo IInfo(Info.AsmRewrites);
bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
Info.ParsedOperands);
Info.ParseError = HadError;
// Dump the parsed representation, if requested.
if (getShowParsedOperands()) {
SmallString<256> Str;
raw_svector_ostream OS(Str);
OS << "parsed instruction: [";
for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
if (i != 0)
OS << ", ";
Info.ParsedOperands[i]->print(OS);
}
OS << "]";
printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
}
// If we are generating dwarf for the current section then generate a .loc
// directive for the instruction.
if (!HadError && getContext().getGenDwarfForAssembly() &&
getContext().getGenDwarfSectionSyms().count(
getStreamer().getCurrentSection().first)) {
unsigned Line;
if (ActiveMacros.empty())
Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
else
Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
ActiveMacros.front()->ExitBuffer);
// If we previously parsed a cpp hash file line comment then make sure the
// current Dwarf File is for the CppHashFilename if not then emit the
// Dwarf File table for it and adjust the line number for the .loc.
if (CppHashFilename.size()) {
unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
0, StringRef(), CppHashFilename);
getContext().setGenDwarfFileNumber(FileNumber);
// Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
// cache with the different Loc from the call above we save the last
// info we queried here with SrcMgr.FindLineNumber().
unsigned CppHashLocLineNo;
if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
CppHashLocLineNo = LastQueryLine;
else {
CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
LastQueryLine = CppHashLocLineNo;
LastQueryIDLoc = CppHashLoc;
LastQueryBuffer = CppHashBuf;
}
Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
}
getStreamer().EmitDwarfLocDirective(
getContext().getGenDwarfFileNumber(), Line, 0,
DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
StringRef());
}
// If parsing succeeded, match the instruction.
if (!HadError) {
uint64_t ErrorInfo;
getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
Info.ParsedOperands, Out,
ErrorInfo, ParsingInlineAsm);
}
// Don't skip the rest of the line, the instruction parser is responsible for
// that.
return false;
}
/// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
/// since they may not be able to be tokenized to get to the end of line token.
void AsmParser::eatToEndOfLine() {
if (!Lexer.is(AsmToken::EndOfStatement))
Lexer.LexUntilEndOfLine();
// Eat EOL.
Lex();
}
/// parseCppHashLineFilenameComment as this:
/// ::= # number "filename"
/// or just as a full line comment if it doesn't have a number and a string.
bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
Lex(); // Eat the hash token.
if (getLexer().isNot(AsmToken::Integer)) {
// Consume the line since in cases it is not a well-formed line directive,
// as if were simply a full line comment.
eatToEndOfLine();
return false;
}
int64_t LineNumber = getTok().getIntVal();
Lex();
if (getLexer().isNot(AsmToken::String)) {
eatToEndOfLine();
return false;
}
StringRef Filename = getTok().getString();
// Get rid of the enclosing quotes.
Filename = Filename.substr(1, Filename.size() - 2);
// Save the SMLoc, Filename and LineNumber for later use by diagnostics.
CppHashLoc = L;
CppHashFilename = Filename;
CppHashLineNumber = LineNumber;
CppHashBuf = CurBuffer;
// Ignore any trailing characters, they're just comment.
eatToEndOfLine();
return false;
}
/// \brief will use the last parsed cpp hash line filename comment
/// for the Filename and LineNo if any in the diagnostic.
void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
const AsmParser *Parser = static_cast<const AsmParser *>(Context);
raw_ostream &OS = errs();
const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
const SMLoc &DiagLoc = Diag.getLoc();
unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
unsigned CppHashBuf =
Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
// Like SourceMgr::printMessage() we need to print the include stack if any
// before printing the message.
unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
if (!Parser->SavedDiagHandler && DiagCurBuffer &&
DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
}
// If we have not parsed a cpp hash line filename comment or the source
// manager changed or buffer changed (like in a nested include) then just
// print the normal diagnostic using its Filename and LineNo.
if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
DiagBuf != CppHashBuf) {
if (Parser->SavedDiagHandler)
Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
else
Diag.print(nullptr, OS);
return;
}
// Use the CppHashFilename and calculate a line number based on the
// CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
// the diagnostic.
const std::string &Filename = Parser->CppHashFilename;
int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
int CppHashLocLineNo =
Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
int LineNo =
Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Diag.getLineContents(), Diag.getRanges());
if (Parser->SavedDiagHandler)
Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
else
NewDiag.print(nullptr, OS);
}
// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
// difference being that that function accepts '@' as part of identifiers and
// we can't do that. AsmLexer.cpp should probably be changed to handle
// '@' as a special case when needed.
static bool isIdentifierChar(char c) {
return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
c == '.';
}
bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
ArrayRef<MCAsmMacroParameter> Parameters,
ArrayRef<MCAsmMacroArgument> A,
bool EnableAtPseudoVariable, const SMLoc &L) {
unsigned NParameters = Parameters.size();
bool HasVararg = NParameters ? Parameters.back().Vararg : false;
if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
return Error(L, "Wrong number of arguments");
// A macro without parameters is handled differently on Darwin:
// gas accepts no arguments and does no substitutions
while (!Body.empty()) {
// Scan for the next substitution.
std::size_t End = Body.size(), Pos = 0;
for (; Pos != End; ++Pos) {
// Check for a substitution or escape.
if (IsDarwin && !NParameters) {
// This macro has no parameters, look for $0, $1, etc.
if (Body[Pos] != '$' || Pos + 1 == End)
continue;
char Next = Body[Pos + 1];
if (Next == '$' || Next == 'n' ||
isdigit(static_cast<unsigned char>(Next)))
break;
} else {
// This macro has parameters, look for \foo, \bar, etc.
if (Body[Pos] == '\\' && Pos + 1 != End)
break;
}
}
// Add the prefix.
OS << Body.slice(0, Pos);
// Check if we reached the end.
if (Pos == End)
break;
if (IsDarwin && !NParameters) {
switch (Body[Pos + 1]) {
// $$ => $
case '$':
OS << '$';
break;
// $n => number of arguments
case 'n':
OS << A.size();
break;
// $[0-9] => argument
default: {
// Missing arguments are ignored.
unsigned Index = Body[Pos + 1] - '0';
if (Index >= A.size())
break;
// Otherwise substitute with the token values, with spaces eliminated.
for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
ie = A[Index].end();
it != ie; ++it)
OS << it->getString();
break;
}
}
Pos += 2;
} else {
unsigned I = Pos + 1;
// Check for the \@ pseudo-variable.
if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
++I;
else
while (isIdentifierChar(Body[I]) && I + 1 != End)
++I;
const char *Begin = Body.data() + Pos + 1;
StringRef Argument(Begin, I - (Pos + 1));
unsigned Index = 0;
if (Argument == "@") {
OS << NumOfMacroInstantiations;
Pos += 2;
} else {
for (; Index < NParameters; ++Index)
if (Parameters[Index].Name == Argument)
break;
if (Index == NParameters) {
if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
Pos += 3;
else {
OS << '\\' << Argument;
Pos = I;
}
} else {
bool VarargParameter = HasVararg && Index == (NParameters - 1);
for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
ie = A[Index].end();
it != ie; ++it)
// We expect no quotes around the string's contents when
// parsing for varargs.
if (it->getKind() != AsmToken::String || VarargParameter)
OS << it->getString();
else
OS << it->getStringContents();
Pos += 1 + Argument.size();
}
}
}
// Update the scan point.
Body = Body.substr(Pos);
}
return false;
}
MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
size_t CondStackDepth)
: InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
CondStackDepth(CondStackDepth) {}
static bool isOperator(AsmToken::TokenKind kind) {
switch (kind) {
default:
return false;
case AsmToken::Plus:
case AsmToken::Minus:
case AsmToken::Tilde:
case AsmToken::Slash:
case AsmToken::Star:
case AsmToken::Dot:
case AsmToken::Equal:
case AsmToken::EqualEqual:
case AsmToken::Pipe:
case AsmToken::PipePipe:
case AsmToken::Caret:
case AsmToken::Amp:
case AsmToken::AmpAmp:
case AsmToken::Exclaim:
case AsmToken::ExclaimEqual:
case AsmToken::Percent:
case AsmToken::Less:
case AsmToken::LessEqual:
case AsmToken::LessLess:
case AsmToken::LessGreater:
case AsmToken::Greater:
case AsmToken::GreaterEqual:
case AsmToken::GreaterGreater:
return true;
}
}
namespace {
class AsmLexerSkipSpaceRAII {
public:
AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
Lexer.setSkipSpace(SkipSpace);
}
~AsmLexerSkipSpaceRAII() {
Lexer.setSkipSpace(true);
}
private:
AsmLexer &Lexer;
};
}
bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
if (Vararg) {
if (Lexer.isNot(AsmToken::EndOfStatement)) {
StringRef Str = parseStringToEndOfStatement();
MA.emplace_back(AsmToken::String, Str);
}
return false;
}
unsigned ParenLevel = 0;
unsigned AddTokens = 0;
// Darwin doesn't use spaces to delmit arguments.
AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
for (;;) {
if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
return TokError("unexpected token in macro instantiation");
if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
break;
if (Lexer.is(AsmToken::Space)) {
Lex(); // Eat spaces
// Spaces can delimit parameters, but could also be part an expression.
// If the token after a space is an operator, add the token and the next
// one into this argument
if (!IsDarwin) {
if (isOperator(Lexer.getKind())) {
// Check to see whether the token is used as an operator,
// or part of an identifier
const char *NextChar = getTok().getEndLoc().getPointer();
if (*NextChar == ' ')
AddTokens = 2;
}
if (!AddTokens && ParenLevel == 0) {
break;
}
}
}
// handleMacroEntry relies on not advancing the lexer here
// to be able to fill in the remaining default parameter values
if (Lexer.is(AsmToken::EndOfStatement))
break;
// Adjust the current parentheses level.
if (Lexer.is(AsmToken::LParen))
++ParenLevel;
else if (Lexer.is(AsmToken::RParen) && ParenLevel)
--ParenLevel;
// Append the token to the current argument list.
MA.push_back(getTok());
if (AddTokens)
AddTokens--;
Lex();
}
if (ParenLevel != 0)
return TokError("unbalanced parentheses in macro argument");
return false;
}
// Parse the macro instantiation arguments.
bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
MCAsmMacroArguments &A) {
const unsigned NParameters = M ? M->Parameters.size() : 0;
bool NamedParametersFound = false;
SmallVector<SMLoc, 4> FALocs;
A.resize(NParameters);
FALocs.resize(NParameters);
// Parse two kinds of macro invocations:
// - macros defined without any parameters accept an arbitrary number of them
// - macros defined with parameters accept at most that many of them
bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
++Parameter) {
SMLoc IDLoc = Lexer.getLoc();
MCAsmMacroParameter FA;
if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
if (parseIdentifier(FA.Name)) {
Error(IDLoc, "invalid argument identifier for formal argument");
eatToEndOfStatement();
return true;
}
if (!Lexer.is(AsmToken::Equal)) {
TokError("expected '=' after formal parameter identifier");
eatToEndOfStatement();
return true;
}
Lex();
NamedParametersFound = true;
}
if (NamedParametersFound && FA.Name.empty()) {
Error(IDLoc, "cannot mix positional and keyword arguments");
eatToEndOfStatement();
return true;
}
bool Vararg = HasVararg && Parameter == (NParameters - 1);
if (parseMacroArgument(FA.Value, Vararg))
return true;
unsigned PI = Parameter;
if (!FA.Name.empty()) {
unsigned FAI = 0;
for (FAI = 0; FAI < NParameters; ++FAI)
if (M->Parameters[FAI].Name == FA.Name)
break;
if (FAI >= NParameters) {
assert(M && "expected macro to be defined");
Error(IDLoc,
"parameter named '" + FA.Name + "' does not exist for macro '" +
M->Name + "'");
return true;
}
PI = FAI;
}
if (!FA.Value.empty()) {
if (A.size() <= PI)
A.resize(PI + 1);
A[PI] = FA.Value;
if (FALocs.size() <= PI)
FALocs.resize(PI + 1);
FALocs[PI] = Lexer.getLoc();
}
// At the end of the statement, fill in remaining arguments that have
// default values. If there aren't any, then the next argument is
// required but missing
if (Lexer.is(AsmToken::EndOfStatement)) {
bool Failure = false;
for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
if (A[FAI].empty()) {
if (M->Parameters[FAI].Required) {
Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
"missing value for required parameter "
"'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
Failure = true;
}
if (!M->Parameters[FAI].Value.empty())
A[FAI] = M->Parameters[FAI].Value;
}
}
return Failure;
}
if (Lexer.is(AsmToken::Comma))
Lex();
}
return TokError("too many positional arguments");
}
const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
return (I == MacroMap.end()) ? nullptr : &I->getValue();
}
void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
MacroMap.insert(std::make_pair(Name, std::move(Macro)));
}
void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
// Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
// this, although we should protect against infinite loops.
if (ActiveMacros.size() == 20)
return TokError("macros cannot be nested more than 20 levels deep");
MCAsmMacroArguments A;
if (parseMacroArguments(M, A))
return true;
// Macro instantiation is lexical, unfortunately. We construct a new buffer
// to hold the macro body with substitutions.
SmallString<256> Buf;
StringRef Body = M->Body;
raw_svector_ostream OS(Buf);
if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
return true;
// We include the .endmacro in the buffer as our cue to exit the macro
// instantiation.
OS << ".endmacro\n";
std::unique_ptr<MemoryBuffer> Instantiation =
MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
// Create the macro instantiation object and add to the current macro
// instantiation stack.
MacroInstantiation *MI = new MacroInstantiation(
NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
ActiveMacros.push_back(MI);
++NumOfMacroInstantiations;
// Jump to the macro instantiation and prime the lexer.
CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Lex();
return false;
}
void AsmParser::handleMacroExit() {
// Jump to the EndOfStatement we should return to, and consume it.
jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Lex();
// Pop the instantiation entry.
delete ActiveMacros.back();
ActiveMacros.pop_back();
}
bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
bool NoDeadStrip) {
MCSymbol *Sym;
const MCExpr *Value;
if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
Value))
return true;
if (!Sym) {
// In the case where we parse an expression starting with a '.', we will
// not generate an error, nor will we create a symbol. In this case we
// should just return out.
return false;
}
// Do the assignment.
Out.EmitAssignment(Sym, Value);
if (NoDeadStrip)
Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
return false;
}
/// parseIdentifier:
/// ::= identifier
/// ::= string
bool AsmParser::parseIdentifier(StringRef &Res) {
// The assembler has relaxed rules for accepting identifiers, in particular we
// allow things like '.globl $foo' and '.def @feat.00', which would normally be
// separate tokens. At this level, we have already lexed so we cannot (currently)
// handle this as a context dependent token, instead we detect adjacent tokens
// and return the combined identifier.
if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
SMLoc PrefixLoc = getLexer().getLoc();
// Consume the prefix character, and check for a following identifier.
Lex();
if (Lexer.isNot(AsmToken::Identifier))
return true;
// We have a '$' or '@' followed by an identifier, make sure they are adjacent.
if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
return true;
// Construct the joined identifier and consume the token.
Res =
StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Lex();
return false;
}
if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
return true;
Res = getTok().getIdentifier();
Lex(); // Consume the identifier token.
return false;
}
/// parseDirectiveSet:
/// ::= .equ identifier ',' expression
/// ::= .equiv identifier ',' expression
/// ::= .set identifier ',' expression
bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
StringRef Name;
if (parseIdentifier(Name))
return TokError("expected identifier after '" + Twine(IDVal) + "'");
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in '" + Twine(IDVal) + "'");
Lex();
return parseAssignment(Name, allow_redef, true);
}
bool AsmParser::parseEscapedString(std::string &Data) {
assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Data = "";
StringRef Str = getTok().getStringContents();
for (unsigned i = 0, e = Str.size(); i != e; ++i) {
if (Str[i] != '\\') {
Data += Str[i];
continue;
}
// Recognize escaped characters. Note that this escape semantics currently
// loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
++i;
if (i == e)
return TokError("unexpected backslash at end of string");
// Recognize octal sequences.
if ((unsigned)(Str[i] - '0') <= 7) {
// Consume up to three octal characters.
unsigned Value = Str[i] - '0';
if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
++i;
Value = Value * 8 + (Str[i] - '0');
if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
++i;
Value = Value * 8 + (Str[i] - '0');
}
}
if (Value > 255)
return TokError("invalid octal escape sequence (out of range)");
Data += (unsigned char)Value;
continue;
}
// Otherwise recognize individual escapes.
switch (Str[i]) {
default:
// Just reject invalid escape sequences for now.
return TokError("invalid escape sequence (unrecognized character)");
case 'b': Data += '\b'; break;
case 'f': Data += '\f'; break;
case 'n': Data += '\n'; break;
case 'r': Data += '\r'; break;
case 't': Data += '\t'; break;
case '"': Data += '"'; break;
case '\\': Data += '\\'; break;
}
}
return false;
}
/// parseDirectiveAscii:
/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
if (getLexer().isNot(AsmToken::EndOfStatement)) {
checkForValidSection();
for (;;) {
if (getLexer().isNot(AsmToken::String))
return TokError("expected string in '" + Twine(IDVal) + "' directive");
std::string Data;
if (parseEscapedString(Data))
return true;
getStreamer().EmitBytes(Data);
if (ZeroTerminated)
getStreamer().EmitBytes(StringRef("\0", 1));
Lex();
if (getLexer().is(AsmToken::EndOfStatement))
break;
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Lex();
}
}
Lex();
return false;
}
/// parseDirectiveValue
/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
bool AsmParser::parseDirectiveValue(unsigned Size) {
if (getLexer().isNot(AsmToken::EndOfStatement)) {
checkForValidSection();
for (;;) {
const MCExpr *Value;
SMLoc ExprLoc = getLexer().getLoc();
if (parseExpression(Value))
return true;
// Special case constant expressions to match code generator.
if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
assert(Size <= 8 && "Invalid size");
uint64_t IntValue = MCE->getValue();
if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
return Error(ExprLoc, "literal value out of range for directive");
getStreamer().EmitIntValue(IntValue, Size);
} else
getStreamer().EmitValue(Value, Size, ExprLoc);
if (getLexer().is(AsmToken::EndOfStatement))
break;
// FIXME: Improve diagnostic.
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
}
}
Lex();
return false;
}
/// ParseDirectiveOctaValue
/// ::= .octa [ hexconstant (, hexconstant)* ]
bool AsmParser::parseDirectiveOctaValue() {
if (getLexer().isNot(AsmToken::EndOfStatement)) {
checkForValidSection();
for (;;) {
if (Lexer.getKind() == AsmToken::Error)
return true;
if (Lexer.getKind() != AsmToken::Integer &&
Lexer.getKind() != AsmToken::BigNum)
return TokError("unknown token in expression");
SMLoc ExprLoc = getLexer().getLoc();
APInt IntValue = getTok().getAPIntVal();
Lex();
uint64_t hi, lo;
if (IntValue.isIntN(64)) {
hi = 0;
lo = IntValue.getZExtValue();
} else if (IntValue.isIntN(128)) {
// It might actually have more than 128 bits, but the top ones are zero.
hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
lo = IntValue.getLoBits(64).getZExtValue();
} else
return Error(ExprLoc, "literal value out of range for directive");
if (MAI.isLittleEndian()) {
getStreamer().EmitIntValue(lo, 8);
getStreamer().EmitIntValue(hi, 8);
} else {
getStreamer().EmitIntValue(hi, 8);
getStreamer().EmitIntValue(lo, 8);
}
if (getLexer().is(AsmToken::EndOfStatement))
break;
// FIXME: Improve diagnostic.
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
}
}
Lex();
return false;
}
/// parseDirectiveRealValue
/// ::= (.single | .double) [ expression (, expression)* ]
bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
if (getLexer().isNot(AsmToken::EndOfStatement)) {
checkForValidSection();
for (;;) {
// We don't truly support arithmetic on floating point expressions, so we
// have to manually parse unary prefixes.
bool IsNeg = false;
if (getLexer().is(AsmToken::Minus)) {
Lex();
IsNeg = true;
} else if (getLexer().is(AsmToken::Plus))
Lex();
if (getLexer().isNot(AsmToken::Integer) &&
getLexer().isNot(AsmToken::Real) &&
getLexer().isNot(AsmToken::Identifier))
return TokError("unexpected token in directive");
// Convert to an APFloat.
APFloat Value(Semantics);
StringRef IDVal = getTok().getString();
if (getLexer().is(AsmToken::Identifier)) {
if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
Value = APFloat::getInf(Semantics);
else if (!IDVal.compare_lower("nan"))
Value = APFloat::getNaN(Semantics, false, ~0);
else
return TokError("invalid floating point literal");
} else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
APFloat::opInvalidOp)
return TokError("invalid floating point literal");
if (IsNeg)
Value.changeSign();
// Consume the numeric token.
Lex();
// Emit the value as an integer.
APInt AsInt = Value.bitcastToAPInt();
getStreamer().EmitIntValue(AsInt.getLimitedValue(),
AsInt.getBitWidth() / 8);
if (getLexer().is(AsmToken::EndOfStatement))
break;
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
}
}
Lex();
return false;
}
/// parseDirectiveZero
/// ::= .zero expression
bool AsmParser::parseDirectiveZero() {
checkForValidSection();
int64_t NumBytes;
if (parseAbsoluteExpression(NumBytes))
return true;
int64_t Val = 0;
if (getLexer().is(AsmToken::Comma)) {
Lex();
if (parseAbsoluteExpression(Val))
return true;
}
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.zero' directive");
Lex();
getStreamer().EmitFill(NumBytes, Val);
return false;
}
/// parseDirectiveFill
/// ::= .fill expression [ , expression [ , expression ] ]
bool AsmParser::parseDirectiveFill() {
checkForValidSection();
SMLoc RepeatLoc = getLexer().getLoc();
int64_t NumValues;
if (parseAbsoluteExpression(NumValues))
return true;
if (NumValues < 0) {
Warning(RepeatLoc,
"'.fill' directive with negative repeat count has no effect");
NumValues = 0;
}
int64_t FillSize = 1;
int64_t FillExpr = 0;
SMLoc SizeLoc, ExprLoc;
if (getLexer().isNot(AsmToken::EndOfStatement)) {
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in '.fill' directive");
Lex();
SizeLoc = getLexer().getLoc();
if (parseAbsoluteExpression(FillSize))
return true;
if (getLexer().isNot(AsmToken::EndOfStatement)) {
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in '.fill' directive");
Lex();
ExprLoc = getLexer().getLoc();
if (parseAbsoluteExpression(FillExpr))
return true;
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.fill' directive");
Lex();
}
}
if (FillSize < 0) {
Warning(SizeLoc, "'.fill' directive with negative size has no effect");
NumValues = 0;
}
if (FillSize > 8) {
Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
FillSize = 8;
}
if (!isUInt<32>(FillExpr) && FillSize > 4)
Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
if (NumValues > 0) {
int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
for (uint64_t i = 0, e = NumValues; i != e; ++i) {
getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
if (NonZeroFillSize < FillSize)
getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
}
}
return false;
}
/// parseDirectiveOrg
/// ::= .org expression [ , expression ]
bool AsmParser::parseDirectiveOrg() {
checkForValidSection();
const MCExpr *Offset;
SMLoc Loc = getTok().getLoc();
if (parseExpression(Offset))
return true;
// Parse optional fill expression.
int64_t FillExpr = 0;
if (getLexer().isNot(AsmToken::EndOfStatement)) {
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in '.org' directive");
Lex();
if (parseAbsoluteExpression(FillExpr))
return true;
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.org' directive");
}
Lex();
// Only limited forms of relocatable expressions are accepted here, it
// has to be relative to the current section. The streamer will return
// 'true' if the expression wasn't evaluatable.
if (getStreamer().EmitValueToOffset(Offset, FillExpr))
return Error(Loc, "expected assembly-time absolute expression");
return false;
}
/// parseDirectiveAlign
/// ::= {.align, ...} expression [ , expression [ , expression ]]
bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
checkForValidSection();
SMLoc AlignmentLoc = getLexer().getLoc();
int64_t Alignment;
if (parseAbsoluteExpression(Alignment))
return true;
SMLoc MaxBytesLoc;
bool HasFillExpr = false;
int64_t FillExpr = 0;
int64_t MaxBytesToFill = 0;
if (getLexer().isNot(AsmToken::EndOfStatement)) {
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
// The fill expression can be omitted while specifying a maximum number of
// alignment bytes, e.g:
// .align 3,,4
if (getLexer().isNot(AsmToken::Comma)) {
HasFillExpr = true;
if (parseAbsoluteExpression(FillExpr))
return true;
}
if (getLexer().isNot(AsmToken::EndOfStatement)) {
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
MaxBytesLoc = getLexer().getLoc();
if (parseAbsoluteExpression(MaxBytesToFill))
return true;
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
}
}
Lex();
if (!HasFillExpr)
FillExpr = 0;
// Compute alignment in bytes.
if (IsPow2) {
// FIXME: Diagnose overflow.
if (Alignment >= 32) {
Error(AlignmentLoc, "invalid alignment value");
Alignment = 31;
}
Alignment = 1ULL << Alignment;
} else {
// Reject alignments that aren't a power of two, for gas compatibility.
if (!isPowerOf2_64(Alignment))
Error(AlignmentLoc, "alignment must be a power of 2");
}
// Diagnose non-sensical max bytes to align.
if (MaxBytesLoc.isValid()) {
if (MaxBytesToFill < 1) {
Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
"many bytes, ignoring maximum bytes expression");
MaxBytesToFill = 0;
}
if (MaxBytesToFill >= Alignment) {
Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
"has no effect");
MaxBytesToFill = 0;
}
}
// Check whether we should use optimal code alignment for this .align
// directive.
const MCSection *Section = getStreamer().getCurrentSection().first;
assert(Section && "must have section to emit alignment");
bool UseCodeAlign = Section->UseCodeAlign();
if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
ValueSize == 1 && UseCodeAlign) {
getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
} else {
// FIXME: Target specific behavior about how the "extra" bytes are filled.
getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
MaxBytesToFill);
}
return false;
}
/// parseDirectiveFile
/// ::= .file [number] filename
/// ::= .file number directory filename
bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
// FIXME: I'm not sure what this is.
int64_t FileNumber = -1;
SMLoc FileNumberLoc = getLexer().getLoc();
if (getLexer().is(AsmToken::Integer)) {
FileNumber = getTok().getIntVal();
Lex();
if (FileNumber < 1)
return TokError("file number less than one");
}
if (getLexer().isNot(AsmToken::String))
return TokError("unexpected token in '.file' directive");
// Usually the directory and filename together, otherwise just the directory.
// Allow the strings to have escaped octal character sequence.
std::string Path = getTok().getString();
if (parseEscapedString(Path))
return true;
Lex();
StringRef Directory;
StringRef Filename;
std::string FilenameData;
if (getLexer().is(AsmToken::String)) {
if (FileNumber == -1)
return TokError("explicit path specified, but no file number");
if (parseEscapedString(FilenameData))
return true;
Filename = FilenameData;
Directory = Path;
Lex();
} else {
Filename = Path;
}
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.file' directive");
if (FileNumber == -1)
getStreamer().EmitFileDirective(Filename);
else {
if (getContext().getGenDwarfForAssembly())
Error(DirectiveLoc,
"input can't have .file dwarf directives when -g is "
"used to generate dwarf debug info for assembly code");
if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
0)
Error(FileNumberLoc, "file number already allocated");
}
return false;
}
/// parseDirectiveLine
/// ::= .line [number]
bool AsmParser::parseDirectiveLine() {
if (getLexer().isNot(AsmToken::EndOfStatement)) {
if (getLexer().isNot(AsmToken::Integer))
return TokError("unexpected token in '.line' directive");
int64_t LineNumber = getTok().getIntVal();
(void)LineNumber;
Lex();
// FIXME: Do something with the .line.
}
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.line' directive");
return false;
}
/// parseDirectiveLoc
/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
/// The first number is a file number, must have been previously assigned with
/// a .file directive, the second number is the line number and optionally the
/// third number is a column position (zero if not specified). The remaining
/// optional items are .loc sub-directives.
bool AsmParser::parseDirectiveLoc() {
if (getLexer().isNot(AsmToken::Integer))
return TokError("unexpected token in '.loc' directive");
int64_t FileNumber = getTok().getIntVal();
if (FileNumber < 1)
return TokError("file number less than one in '.loc' directive");
if (!getContext().isValidDwarfFileNumber(FileNumber))
return TokError("unassigned file number in '.loc' directive");
Lex();
int64_t LineNumber = 0;
if (getLexer().is(AsmToken::Integer)) {
LineNumber = getTok().getIntVal();
if (LineNumber < 0)
return TokError("line number less than zero in '.loc' directive");
Lex();
}
int64_t ColumnPos = 0;
if (getLexer().is(AsmToken::Integer)) {
ColumnPos = getTok().getIntVal();
if (ColumnPos < 0)
return TokError("column position less than zero in '.loc' directive");
Lex();
}
unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
unsigned Isa = 0;
int64_t Discriminator = 0;
if (getLexer().isNot(AsmToken::EndOfStatement)) {
for (;;) {
if (getLexer().is(AsmToken::EndOfStatement))
break;
StringRef Name;
SMLoc Loc = getTok().getLoc();
if (parseIdentifier(Name))
return TokError("unexpected token in '.loc' directive");
if (Name == "basic_block")
Flags |= DWARF2_FLAG_BASIC_BLOCK;
else if (Name == "prologue_end")
Flags |= DWARF2_FLAG_PROLOGUE_END;
else if (Name == "epilogue_begin")
Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
else if (Name == "is_stmt") {
Loc = getTok().getLoc();
const MCExpr *Value;
if (parseExpression(Value))
return true;
// The expression must be the constant 0 or 1.
if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
int Value = MCE->getValue();
if (Value == 0)
Flags &= ~DWARF2_FLAG_IS_STMT;
else if (Value == 1)
Flags |= DWARF2_FLAG_IS_STMT;
else
return Error(Loc, "is_stmt value not 0 or 1");
} else {
return Error(Loc, "is_stmt value not the constant value of 0 or 1");
}
} else if (Name == "isa") {
Loc = getTok().getLoc();
const MCExpr *Value;
if (parseExpression(Value))
return true;
// The expression must be a constant greater or equal to 0.
if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
int Value = MCE->getValue();
if (Value < 0)
return Error(Loc, "isa number less than zero");
Isa = Value;
} else {
return Error(Loc, "isa number not a constant value");
}
} else if (Name == "discriminator") {
if (parseAbsoluteExpression(Discriminator))
return true;
} else {
return Error(Loc, "unknown sub-directive in '.loc' directive");
}
if (getLexer().is(AsmToken::EndOfStatement))
break;
}
}
getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Isa, Discriminator, StringRef());
return false;
}
/// parseDirectiveStabs
/// ::= .stabs string, number, number, number
bool AsmParser::parseDirectiveStabs() {
return TokError("unsupported directive '.stabs'");
}
/// parseDirectiveCFISections
/// ::= .cfi_sections section [, section]
bool AsmParser::parseDirectiveCFISections() {
StringRef Name;
bool EH = false;
bool Debug = false;
if (parseIdentifier(Name))
return TokError("Expected an identifier");
if (Name == ".eh_frame")
EH = true;
else if (Name == ".debug_frame")
Debug = true;
if (getLexer().is(AsmToken::Comma)) {
Lex();
if (parseIdentifier(Name))
return TokError("Expected an identifier");
if (Name == ".eh_frame")
EH = true;
else if (Name == ".debug_frame")
Debug = true;
}
getStreamer().EmitCFISections(EH, Debug);
return false;
}
/// parseDirectiveCFIStartProc
/// ::= .cfi_startproc [simple]
bool AsmParser::parseDirectiveCFIStartProc() {
StringRef Simple;
if (getLexer().isNot(AsmToken::EndOfStatement))
if (parseIdentifier(Simple) || Simple != "simple")
return TokError("unexpected token in .cfi_startproc directive");
getStreamer().EmitCFIStartProc(!Simple.empty());
return false;
}
/// parseDirectiveCFIEndProc
/// ::= .cfi_endproc
bool AsmParser::parseDirectiveCFIEndProc() {
getStreamer().EmitCFIEndProc();
return false;
}
/// \brief parse register name or number.
bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
SMLoc DirectiveLoc) {
unsigned RegNo;
if (getLexer().isNot(AsmToken::Integer)) {
if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
return true;
Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
} else
return parseAbsoluteExpression(Register);
return false;
}
/// parseDirectiveCFIDefCfa
/// ::= .cfi_def_cfa register, offset
bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
int64_t Register = 0;
if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
return true;
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
int64_t Offset = 0;
if (parseAbsoluteExpression(Offset))
return true;
getStreamer().EmitCFIDefCfa(Register, Offset);
return false;
}
/// parseDirectiveCFIDefCfaOffset
/// ::= .cfi_def_cfa_offset offset
bool AsmParser::parseDirectiveCFIDefCfaOffset() {
int64_t Offset = 0;
if (parseAbsoluteExpression(Offset))
return true;
getStreamer().EmitCFIDefCfaOffset(Offset);
return false;
}
/// parseDirectiveCFIRegister
/// ::= .cfi_register register, register
bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
int64_t Register1 = 0;
if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
return true;
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
int64_t Register2 = 0;
if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
return true;
getStreamer().EmitCFIRegister(Register1, Register2);
return false;
}
/// parseDirectiveCFIWindowSave
/// ::= .cfi_window_save
bool AsmParser::parseDirectiveCFIWindowSave() {
getStreamer().EmitCFIWindowSave();
return false;
}
/// parseDirectiveCFIAdjustCfaOffset
/// ::= .cfi_adjust_cfa_offset adjustment
bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
int64_t Adjustment = 0;
if (parseAbsoluteExpression(Adjustment))
return true;
getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
return false;
}
/// parseDirectiveCFIDefCfaRegister
/// ::= .cfi_def_cfa_register register
bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
int64_t Register = 0;
if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
return true;
getStreamer().EmitCFIDefCfaRegister(Register);
return false;
}
/// parseDirectiveCFIOffset
/// ::= .cfi_offset register, offset
bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
int64_t Register = 0;
int64_t Offset = 0;
if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
return true;
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
if (parseAbsoluteExpression(Offset))
return true;
getStreamer().EmitCFIOffset(Register, Offset);
return false;
}
/// parseDirectiveCFIRelOffset
/// ::= .cfi_rel_offset register, offset
bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
int64_t Register = 0;
if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
return true;
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
int64_t Offset = 0;
if (parseAbsoluteExpression(Offset))
return true;
getStreamer().EmitCFIRelOffset(Register, Offset);
return false;
}
static bool isValidEncoding(int64_t Encoding) {
if (Encoding & ~0xff)
return false;
if (Encoding == dwarf::DW_EH_PE_omit)
return true;
const unsigned Format = Encoding & 0xf;
if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
return false;
const unsigned Application = Encoding & 0x70;
if (Application != dwarf::DW_EH_PE_absptr &&
Application != dwarf::DW_EH_PE_pcrel)
return false;
return true;
}
/// parseDirectiveCFIPersonalityOrLsda
/// IsPersonality true for cfi_personality, false for cfi_lsda
/// ::= .cfi_personality encoding, [symbol_name]
/// ::= .cfi_lsda encoding, [symbol_name]
bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
int64_t Encoding = 0;
if (parseAbsoluteExpression(Encoding))
return true;
if (Encoding == dwarf::DW_EH_PE_omit)
return false;
if (!isValidEncoding(Encoding))
return TokError("unsupported encoding.");
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
StringRef Name;
if (parseIdentifier(Name))
return TokError("expected identifier in directive");
MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
if (IsPersonality)
getStreamer().EmitCFIPersonality(Sym, Encoding);
else
getStreamer().EmitCFILsda(Sym, Encoding);
return false;
}
/// parseDirectiveCFIRememberState
/// ::= .cfi_remember_state
bool AsmParser::parseDirectiveCFIRememberState() {
getStreamer().EmitCFIRememberState();
return false;
}
/// parseDirectiveCFIRestoreState
/// ::= .cfi_remember_state
bool AsmParser::parseDirectiveCFIRestoreState() {
getStreamer().EmitCFIRestoreState();
return false;
}
/// parseDirectiveCFISameValue
/// ::= .cfi_same_value register
bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
int64_t Register = 0;
if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
return true;
getStreamer().EmitCFISameValue(Register);
return false;
}
/// parseDirectiveCFIRestore
/// ::= .cfi_restore register
bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
int64_t Register = 0;
if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
return true;
getStreamer().EmitCFIRestore(Register);
return false;
}
/// parseDirectiveCFIEscape
/// ::= .cfi_escape expression[,...]
bool AsmParser::parseDirectiveCFIEscape() {
std::string Values;
int64_t CurrValue;
if (parseAbsoluteExpression(CurrValue))
return true;
Values.push_back((uint8_t)CurrValue);
while (getLexer().is(AsmToken::Comma)) {
Lex();
if (parseAbsoluteExpression(CurrValue))
return true;
Values.push_back((uint8_t)CurrValue);
}
getStreamer().EmitCFIEscape(Values);
return false;
}
/// parseDirectiveCFISignalFrame
/// ::= .cfi_signal_frame
bool AsmParser::parseDirectiveCFISignalFrame() {
if (getLexer().isNot(AsmToken::EndOfStatement))
return Error(getLexer().getLoc(),
"unexpected token in '.cfi_signal_frame'");
getStreamer().EmitCFISignalFrame();
return false;
}
/// parseDirectiveCFIUndefined
/// ::= .cfi_undefined register
bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
int64_t Register = 0;
if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
return true;
getStreamer().EmitCFIUndefined(Register);
return false;
}
/// parseDirectiveMacrosOnOff
/// ::= .macros_on
/// ::= .macros_off
bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
if (getLexer().isNot(AsmToken::EndOfStatement))
return Error(getLexer().getLoc(),
"unexpected token in '" + Directive + "' directive");
setMacrosEnabled(Directive == ".macros_on");
return false;
}
/// parseDirectiveMacro
/// ::= .macro name[,] [parameters]
bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
StringRef Name;
if (parseIdentifier(Name))
return TokError("expected identifier in '.macro' directive");
if (getLexer().is(AsmToken::Comma))
Lex();
MCAsmMacroParameters Parameters;
while (getLexer().isNot(AsmToken::EndOfStatement)) {
if (!Parameters.empty() && Parameters.back().Vararg)
return Error(Lexer.getLoc(),
"Vararg parameter '" + Parameters.back().Name +
"' should be last one in the list of parameters.");
MCAsmMacroParameter Parameter;
if (parseIdentifier(Parameter.Name))
return TokError("expected identifier in '.macro' directive");
if (Lexer.is(AsmToken::Colon)) {
Lex(); // consume ':'
SMLoc QualLoc;
StringRef Qualifier;
QualLoc = Lexer.getLoc();
if (parseIdentifier(Qualifier))
return Error(QualLoc, "missing parameter qualifier for "
"'" + Parameter.Name + "' in macro '" + Name + "'");
if (Qualifier == "req")
Parameter.Required = true;
else if (Qualifier == "vararg")
Parameter.Vararg = true;
else
return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
"for '" + Parameter.Name + "' in macro '" + Name + "'");
}
if (getLexer().is(AsmToken::Equal)) {
Lex();
SMLoc ParamLoc;
ParamLoc = Lexer.getLoc();
if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
return true;
if (Parameter.Required)
Warning(ParamLoc, "pointless default value for required parameter "
"'" + Parameter.Name + "' in macro '" + Name + "'");
}
Parameters.push_back(std::move(Parameter));
if (getLexer().is(AsmToken::Comma))
Lex();
}
// Eat the end of statement.
Lex();
AsmToken EndToken, StartToken = getTok();
unsigned MacroDepth = 0;
// Lex the macro definition.
for (;;) {
// Check whether we have reached the end of the file.
if (getLexer().is(AsmToken::Eof))
return Error(DirectiveLoc, "no matching '.endmacro' in definition");
// Otherwise, check whether we have reach the .endmacro.
if (getLexer().is(AsmToken::Identifier)) {
if (getTok().getIdentifier() == ".endm" ||
getTok().getIdentifier() == ".endmacro") {
if (MacroDepth == 0) { // Outermost macro.
EndToken = getTok();
Lex();
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '" + EndToken.getIdentifier() +
"' directive");
break;
} else {
// Otherwise we just found the end of an inner macro.
--MacroDepth;
}
} else if (getTok().getIdentifier() == ".macro") {
// We allow nested macros. Those aren't instantiated until the outermost
// macro is expanded so just ignore them for now.
++MacroDepth;
}
}
// Otherwise, scan til the end of the statement.
eatToEndOfStatement();
}
if (lookupMacro(Name)) {
return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
}
const char *BodyStart = StartToken.getLoc().getPointer();
const char *BodyEnd = EndToken.getLoc().getPointer();
StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
return false;
}
/// checkForBadMacro
///
/// With the support added for named parameters there may be code out there that
/// is transitioning from positional parameters. In versions of gas that did
/// not support named parameters they would be ignored on the macro definition.
/// But to support both styles of parameters this is not possible so if a macro
/// definition has named parameters but does not use them and has what appears
/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
/// warning that the positional parameter found in body which have no effect.
/// Hoping the developer will either remove the named parameters from the macro
/// definition so the positional parameters get used if that was what was
/// intended or change the macro to use the named parameters. It is possible
/// this warning will trigger when the none of the named parameters are used
/// and the strings like $1 are infact to simply to be passed trough unchanged.
void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
StringRef Body,
ArrayRef<MCAsmMacroParameter> Parameters) {
// If this macro is not defined with named parameters the warning we are
// checking for here doesn't apply.
unsigned NParameters = Parameters.size();
if (NParameters == 0)
return;
bool NamedParametersFound = false;
bool PositionalParametersFound = false;
// Look at the body of the macro for use of both the named parameters and what
// are likely to be positional parameters. This is what expandMacro() is
// doing when it finds the parameters in the body.
while (!Body.empty()) {
// Scan for the next possible parameter.
std::size_t End = Body.size(), Pos = 0;
for (; Pos != End; ++Pos) {
// Check for a substitution or escape.
// This macro is defined with parameters, look for \foo, \bar, etc.
if (Body[Pos] == '\\' && Pos + 1 != End)
break;
// This macro should have parameters, but look for $0, $1, ..., $n too.
if (Body[Pos] != '$' || Pos + 1 == End)
continue;
char Next = Body[Pos + 1];
if (Next == '$' || Next == 'n' ||
isdigit(static_cast<unsigned char>(Next)))
break;
}
// Check if we reached the end.
if (Pos == End)
break;
if (Body[Pos] == '$') {
switch (Body[Pos + 1]) {
// $$ => $
case '$':
break;
// $n => number of arguments
case 'n':
PositionalParametersFound = true;
break;
// $[0-9] => argument
default: {
PositionalParametersFound = true;
break;
}
}
Pos += 2;
} else {
unsigned I = Pos + 1;
while (isIdentifierChar(Body[I]) && I + 1 != End)
++I;
const char *Begin = Body.data() + Pos + 1;
StringRef Argument(Begin, I - (Pos + 1));
unsigned Index = 0;
for (; Index < NParameters; ++Index)
if (Parameters[Index].Name == Argument)
break;
if (Index == NParameters) {
if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
Pos += 3;
else {
Pos = I;
}
} else {
NamedParametersFound = true;
Pos += 1 + Argument.size();
}
}
// Update the scan point.
Body = Body.substr(Pos);
}
if (!NamedParametersFound && PositionalParametersFound)
Warning(DirectiveLoc, "macro defined with named parameters which are not "
"used in macro body, possible positional parameter "
"found in body which will have no effect");
}
/// parseDirectiveExitMacro
/// ::= .exitm
bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '" + Directive + "' directive");
if (!isInsideMacroInstantiation())
return TokError("unexpected '" + Directive + "' in file, "
"no current macro definition");
// Exit all conditionals that are active in the current macro.
while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
TheCondState = TheCondStack.back();
TheCondStack.pop_back();
}
handleMacroExit();
return false;
}
/// parseDirectiveEndMacro
/// ::= .endm
/// ::= .endmacro
bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '" + Directive + "' directive");
// If we are inside a macro instantiation, terminate the current
// instantiation.
if (isInsideMacroInstantiation()) {
handleMacroExit();
return false;
}
// Otherwise, this .endmacro is a stray entry in the file; well formed
// .endmacro directives are handled during the macro definition parsing.
return TokError("unexpected '" + Directive + "' in file, "
"no current macro definition");
}
/// parseDirectivePurgeMacro
/// ::= .purgem
bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
StringRef Name;
if (parseIdentifier(Name))
return TokError("expected identifier in '.purgem' directive");
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.purgem' directive");
if (!lookupMacro(Name))
return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
undefineMacro(Name);
return false;
}
/// parseDirectiveBundleAlignMode
/// ::= {.bundle_align_mode} expression
bool AsmParser::parseDirectiveBundleAlignMode() {
checkForValidSection();
// Expect a single argument: an expression that evaluates to a constant
// in the inclusive range 0-30.
SMLoc ExprLoc = getLexer().getLoc();
int64_t AlignSizePow2;
if (parseAbsoluteExpression(AlignSizePow2))
return true;
else if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token after expression in"
" '.bundle_align_mode' directive");
else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
return Error(ExprLoc,
"invalid bundle alignment size (expected between 0 and 30)");
Lex();
// Because of AlignSizePow2's verified range we can safely truncate it to
// unsigned.
getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
return false;
}
/// parseDirectiveBundleLock
/// ::= {.bundle_lock} [align_to_end]
bool AsmParser::parseDirectiveBundleLock() {
checkForValidSection();
bool AlignToEnd = false;
if (getLexer().isNot(AsmToken::EndOfStatement)) {
StringRef Option;
SMLoc Loc = getTok().getLoc();
const char *kInvalidOptionError =
"invalid option for '.bundle_lock' directive";
if (parseIdentifier(Option))
return Error(Loc, kInvalidOptionError);
if (Option != "align_to_end")
return Error(Loc, kInvalidOptionError);
else if (getLexer().isNot(AsmToken::EndOfStatement))
return Error(Loc,
"unexpected token after '.bundle_lock' directive option");
AlignToEnd = true;
}
Lex();
getStreamer().EmitBundleLock(AlignToEnd);
return false;
}
/// parseDirectiveBundleLock
/// ::= {.bundle_lock}
bool AsmParser::parseDirectiveBundleUnlock() {
checkForValidSection();
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.bundle_unlock' directive");
Lex();
getStreamer().EmitBundleUnlock();
return false;
}
/// parseDirectiveSpace
/// ::= (.skip | .space) expression [ , expression ]
bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
checkForValidSection();
int64_t NumBytes;
if (parseAbsoluteExpression(NumBytes))
return true;
int64_t FillExpr = 0;
if (getLexer().isNot(AsmToken::EndOfStatement)) {
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Lex();
if (parseAbsoluteExpression(FillExpr))
return true;
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
}
Lex();
if (NumBytes <= 0)
return TokError("invalid number of bytes in '" + Twine(IDVal) +
"' directive");
// FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
getStreamer().EmitFill(NumBytes, FillExpr);
return false;
}
/// parseDirectiveLEB128
/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
bool AsmParser::parseDirectiveLEB128(bool Signed) {
checkForValidSection();
const MCExpr *Value;
for (;;) {
if (parseExpression(Value))
return true;
if (Signed)
getStreamer().EmitSLEB128Value(Value);
else
getStreamer().EmitULEB128Value(Value);
if (getLexer().is(AsmToken::EndOfStatement))
break;
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
}
return false;
}
/// parseDirectiveSymbolAttribute
/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
if (getLexer().isNot(AsmToken::EndOfStatement)) {
for (;;) {
StringRef Name;
SMLoc Loc = getTok().getLoc();
if (parseIdentifier(Name))
return Error(Loc, "expected identifier in directive");
MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
// Assembler local symbols don't make any sense here. Complain loudly.
if (Sym->isTemporary())
return Error(Loc, "non-local symbol required in directive");
if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
return Error(Loc, "unable to emit symbol attribute");
if (getLexer().is(AsmToken::EndOfStatement))
break;
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
}
}
Lex();
return false;
}
/// parseDirectiveComm
/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
bool AsmParser::parseDirectiveComm(bool IsLocal) {
checkForValidSection();
SMLoc IDLoc = getLexer().getLoc();
StringRef Name;
if (parseIdentifier(Name))
return TokError("expected identifier in directive");
// Handle the identifier as the key symbol.
MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
int64_t Size;
SMLoc SizeLoc = getLexer().getLoc();
if (parseAbsoluteExpression(Size))
return true;
int64_t Pow2Alignment = 0;
SMLoc Pow2AlignmentLoc;
if (getLexer().is(AsmToken::Comma)) {
Lex();
Pow2AlignmentLoc = getLexer().getLoc();
if (parseAbsoluteExpression(Pow2Alignment))
return true;
LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
if (IsLocal && LCOMM == LCOMM::NoAlignment)
return Error(Pow2AlignmentLoc, "alignment not supported on this target");
// If this target takes alignments in bytes (not log) validate and convert.
if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
(IsLocal && LCOMM == LCOMM::ByteAlignment)) {
if (!isPowerOf2_64(Pow2Alignment))
return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
Pow2Alignment = Log2_64(Pow2Alignment);
}
}
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.comm' or '.lcomm' directive");
Lex();
// NOTE: a size of zero for a .comm should create a undefined symbol
// but a size of .lcomm creates a bss symbol of size zero.
if (Size < 0)
return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
"be less than zero");
// NOTE: The alignment in the directive is a power of 2 value, the assembler
// may internally end up wanting an alignment in bytes.
// FIXME: Diagnose overflow.
if (Pow2Alignment < 0)
return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
"alignment, can't be less than zero");
if (!Sym->isUndefined())
return Error(IDLoc, "invalid symbol redefinition");
// Create the Symbol as a common or local common with Size and Pow2Alignment
if (IsLocal) {
getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
return false;
}
getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
return false;
}
/// parseDirectiveAbort
/// ::= .abort [... message ...]
bool AsmParser::parseDirectiveAbort() {
// FIXME: Use loc from directive.
SMLoc Loc = getLexer().getLoc();
StringRef Str = parseStringToEndOfStatement();
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.abort' directive");
Lex();
if (Str.empty())
Error(Loc, ".abort detected. Assembly stopping.");
else
Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
// FIXME: Actually abort assembly here.
return false;
}
/// parseDirectiveInclude
/// ::= .include "filename"
bool AsmParser::parseDirectiveInclude() {
if (getLexer().isNot(AsmToken::String))
return TokError("expected string in '.include' directive");
// Allow the strings to have escaped octal character sequence.
std::string Filename;
if (parseEscapedString(Filename))
return true;
SMLoc IncludeLoc = getLexer().getLoc();
Lex();
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.include' directive");
// Attempt to switch the lexer to the included file before consuming the end
// of statement to avoid losing it when we switch.
if (enterIncludeFile(Filename)) {
Error(IncludeLoc, "Could not find include file '" + Filename + "'");
return true;
}
return false;
}
/// parseDirectiveIncbin
/// ::= .incbin "filename"
bool AsmParser::parseDirectiveIncbin() {
if (getLexer().isNot(AsmToken::String))
return TokError("expected string in '.incbin' directive");
// Allow the strings to have escaped octal character sequence.
std::string Filename;
if (parseEscapedString(Filename))
return true;
SMLoc IncbinLoc = getLexer().getLoc();
Lex();
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.incbin' directive");
// Attempt to process the included file.
if (processIncbinFile(Filename)) {
Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
return true;
}
return false;
}
/// parseDirectiveIf
/// ::= .if{,eq,ge,gt,le,lt,ne} expression
bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
TheCondStack.push_back(TheCondState);
TheCondState.TheCond = AsmCond::IfCond;
if (TheCondState.Ignore) {
eatToEndOfStatement();
} else {
int64_t ExprValue;
if (parseAbsoluteExpression(ExprValue))
return true;
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.if' directive");
Lex();
switch (DirKind) {
default:
llvm_unreachable("unsupported directive");
case DK_IF:
case DK_IFNE:
break;
case DK_IFEQ:
ExprValue = ExprValue == 0;
break;
case DK_IFGE:
ExprValue = ExprValue >= 0;
break;
case DK_IFGT:
ExprValue = ExprValue > 0;
break;
case DK_IFLE:
ExprValue = ExprValue <= 0;
break;
case DK_IFLT:
ExprValue = ExprValue < 0;
break;
}
TheCondState.CondMet = ExprValue;
TheCondState.Ignore = !TheCondState.CondMet;
}
return false;
}
/// parseDirectiveIfb
/// ::= .ifb string
bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
TheCondStack.push_back(TheCondState);
TheCondState.TheCond = AsmCond::IfCond;
if (TheCondState.Ignore) {
eatToEndOfStatement();
} else {
StringRef Str = parseStringToEndOfStatement();
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.ifb' directive");
Lex();
TheCondState.CondMet = ExpectBlank == Str.empty();
TheCondState.Ignore = !TheCondState.CondMet;
}
return false;
}
/// parseDirectiveIfc
/// ::= .ifc string1, string2
/// ::= .ifnc string1, string2
bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
TheCondStack.push_back(TheCondState);
TheCondState.TheCond = AsmCond::IfCond;
if (TheCondState.Ignore) {
eatToEndOfStatement();
} else {
StringRef Str1 = parseStringToComma();
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in '.ifc' directive");
Lex();
StringRef Str2 = parseStringToEndOfStatement();
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.ifc' directive");
Lex();
TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
TheCondState.Ignore = !TheCondState.CondMet;
}
return false;
}
/// parseDirectiveIfeqs
/// ::= .ifeqs string1, string2
bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
if (Lexer.isNot(AsmToken::String)) {
if (ExpectEqual)
TokError("expected string parameter for '.ifeqs' directive");
else
TokError("expected string parameter for '.ifnes' directive");
eatToEndOfStatement();
return true;
}
StringRef String1 = getTok().getStringContents();
Lex();
if (Lexer.isNot(AsmToken::Comma)) {
if (ExpectEqual)
TokError("expected comma after first string for '.ifeqs' directive");
else
TokError("expected comma after first string for '.ifnes' directive");
eatToEndOfStatement();
return true;
}
Lex();
if (Lexer.isNot(AsmToken::String)) {
if (ExpectEqual)
TokError("expected string parameter for '.ifeqs' directive");
else
TokError("expected string parameter for '.ifnes' directive");
eatToEndOfStatement();
return true;
}
StringRef String2 = getTok().getStringContents();
Lex();
TheCondStack.push_back(TheCondState);
TheCondState.TheCond = AsmCond::IfCond;
TheCondState.CondMet = ExpectEqual == (String1 == String2);
TheCondState.Ignore = !TheCondState.CondMet;
return false;
}
/// parseDirectiveIfdef
/// ::= .ifdef symbol
bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
StringRef Name;
TheCondStack.push_back(TheCondState);
TheCondState.TheCond = AsmCond::IfCond;
if (TheCondState.Ignore) {
eatToEndOfStatement();
} else {
if (parseIdentifier(Name))
return TokError("expected identifier after '.ifdef'");
Lex();
MCSymbol *Sym = getContext().lookupSymbol(Name);
if (expect_defined)
TheCondState.CondMet = (Sym && !Sym->isUndefined());
else
TheCondState.CondMet = (!Sym || Sym->isUndefined());
TheCondState.Ignore = !TheCondState.CondMet;
}
return false;
}
/// parseDirectiveElseIf
/// ::= .elseif expression
bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
if (TheCondState.TheCond != AsmCond::IfCond &&
TheCondState.TheCond != AsmCond::ElseIfCond)
Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
" an .elseif");
TheCondState.TheCond = AsmCond::ElseIfCond;
bool LastIgnoreState = false;
if (!TheCondStack.empty())
LastIgnoreState = TheCondStack.back().Ignore;
if (LastIgnoreState || TheCondState.CondMet) {
TheCondState.Ignore = true;
eatToEndOfStatement();
} else {
int64_t ExprValue;
if (parseAbsoluteExpression(ExprValue))
return true;
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.elseif' directive");
Lex();
TheCondState.CondMet = ExprValue;
TheCondState.Ignore = !TheCondState.CondMet;
}
return false;
}
/// parseDirectiveElse
/// ::= .else
bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.else' directive");
Lex();
if (TheCondState.TheCond != AsmCond::IfCond &&
TheCondState.TheCond != AsmCond::ElseIfCond)
Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
".elseif");
TheCondState.TheCond = AsmCond::ElseCond;
bool LastIgnoreState = false;
if (!TheCondStack.empty())
LastIgnoreState = TheCondStack.back().Ignore;
if (LastIgnoreState || TheCondState.CondMet)
TheCondState.Ignore = true;
else
TheCondState.Ignore = false;
return false;
}
/// parseDirectiveEnd
/// ::= .end
bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.end' directive");
Lex();
while (Lexer.isNot(AsmToken::Eof))
Lex();
return false;
}
/// parseDirectiveError
/// ::= .err
/// ::= .error [string]
bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
if (!TheCondStack.empty()) {
if (TheCondStack.back().Ignore) {
eatToEndOfStatement();
return false;
}
}
if (!WithMessage)
return Error(L, ".err encountered");
StringRef Message = ".error directive invoked in source file";
if (Lexer.isNot(AsmToken::EndOfStatement)) {
if (Lexer.isNot(AsmToken::String)) {
TokError(".error argument must be a string");
eatToEndOfStatement();
return true;
}
Message = getTok().getStringContents();
Lex();
}
Error(L, Message);
return true;
}
/// parseDirectiveWarning
/// ::= .warning [string]
bool AsmParser::parseDirectiveWarning(SMLoc L) {
if (!TheCondStack.empty()) {
if (TheCondStack.back().Ignore) {
eatToEndOfStatement();
return false;
}
}
StringRef Message = ".warning directive invoked in source file";
if (Lexer.isNot(AsmToken::EndOfStatement)) {
if (Lexer.isNot(AsmToken::String)) {
TokError(".warning argument must be a string");
eatToEndOfStatement();
return true;
}
Message = getTok().getStringContents();
Lex();
}
Warning(L, Message);
return false;
}
/// parseDirectiveEndIf
/// ::= .endif
bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.endif' directive");
Lex();
if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
".else");
if (!TheCondStack.empty()) {
TheCondState = TheCondStack.back();
TheCondStack.pop_back();
}
return false;
}
void AsmParser::initializeDirectiveKindMap() {
DirectiveKindMap[".set"] = DK_SET;
DirectiveKindMap[".equ"] = DK_EQU;
DirectiveKindMap[".equiv"] = DK_EQUIV;
DirectiveKindMap[".ascii"] = DK_ASCII;
DirectiveKindMap[".asciz"] = DK_ASCIZ;
DirectiveKindMap[".string"] = DK_STRING;
DirectiveKindMap[".byte"] = DK_BYTE;
DirectiveKindMap[".short"] = DK_SHORT;
DirectiveKindMap[".value"] = DK_VALUE;
DirectiveKindMap[".2byte"] = DK_2BYTE;
DirectiveKindMap[".long"] = DK_LONG;
DirectiveKindMap[".int"] = DK_INT;
DirectiveKindMap[".4byte"] = DK_4BYTE;
DirectiveKindMap[".quad"] = DK_QUAD;
DirectiveKindMap[".8byte"] = DK_8BYTE;
DirectiveKindMap[".octa"] = DK_OCTA;
DirectiveKindMap[".single"] = DK_SINGLE;
DirectiveKindMap[".float"] = DK_FLOAT;
DirectiveKindMap[".double"] = DK_DOUBLE;
DirectiveKindMap[".align"] = DK_ALIGN;
DirectiveKindMap[".align32"] = DK_ALIGN32;
DirectiveKindMap[".balign"] = DK_BALIGN;
DirectiveKindMap[".balignw"] = DK_BALIGNW;
DirectiveKindMap[".balignl"] = DK_BALIGNL;
DirectiveKindMap[".p2align"] = DK_P2ALIGN;
DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
DirectiveKindMap[".org"] = DK_ORG;
DirectiveKindMap[".fill"] = DK_FILL;
DirectiveKindMap[".zero"] = DK_ZERO;
DirectiveKindMap[".extern"] = DK_EXTERN;
DirectiveKindMap[".globl"] = DK_GLOBL;
DirectiveKindMap[".global"] = DK_GLOBAL;
DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
DirectiveKindMap[".reference"] = DK_REFERENCE;
DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
DirectiveKindMap[".comm"] = DK_COMM;
DirectiveKindMap[".common"] = DK_COMMON;
DirectiveKindMap[".lcomm"] = DK_LCOMM;
DirectiveKindMap[".abort"] = DK_ABORT;
DirectiveKindMap[".include"] = DK_INCLUDE;
DirectiveKindMap[".incbin"] = DK_INCBIN;
DirectiveKindMap[".code16"] = DK_CODE16;
DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
DirectiveKindMap[".rept"] = DK_REPT;
DirectiveKindMap[".rep"] = DK_REPT;
DirectiveKindMap[".irp"] = DK_IRP;
DirectiveKindMap[".irpc"] = DK_IRPC;
DirectiveKindMap[".endr"] = DK_ENDR;
DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
DirectiveKindMap[".if"] = DK_IF;
DirectiveKindMap[".ifeq"] = DK_IFEQ;
DirectiveKindMap[".ifge"] = DK_IFGE;
DirectiveKindMap[".ifgt"] = DK_IFGT;
DirectiveKindMap[".ifle"] = DK_IFLE;
DirectiveKindMap[".iflt"] = DK_IFLT;
DirectiveKindMap[".ifne"] = DK_IFNE;
DirectiveKindMap[".ifb"] = DK_IFB;
DirectiveKindMap[".ifnb"] = DK_IFNB;
DirectiveKindMap[".ifc"] = DK_IFC;
DirectiveKindMap[".ifeqs"] = DK_IFEQS;
DirectiveKindMap[".ifnc"] = DK_IFNC;
DirectiveKindMap[".ifnes"] = DK_IFNES;
DirectiveKindMap[".ifdef"] = DK_IFDEF;
DirectiveKindMap[".ifndef"] = DK_IFNDEF;
DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
DirectiveKindMap[".elseif"] = DK_ELSEIF;
DirectiveKindMap[".else"] = DK_ELSE;
DirectiveKindMap[".end"] = DK_END;
DirectiveKindMap[".endif"] = DK_ENDIF;
DirectiveKindMap[".skip"] = DK_SKIP;
DirectiveKindMap[".space"] = DK_SPACE;
DirectiveKindMap[".file"] = DK_FILE;
DirectiveKindMap[".line"] = DK_LINE;
DirectiveKindMap[".loc"] = DK_LOC;
DirectiveKindMap[".stabs"] = DK_STABS;
DirectiveKindMap[".sleb128"] = DK_SLEB128;
DirectiveKindMap[".uleb128"] = DK_ULEB128;
DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
DirectiveKindMap[".macro"] = DK_MACRO;
DirectiveKindMap[".exitm"] = DK_EXITM;
DirectiveKindMap[".endm"] = DK_ENDM;
DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
DirectiveKindMap[".purgem"] = DK_PURGEM;
DirectiveKindMap[".err"] = DK_ERR;
DirectiveKindMap[".error"] = DK_ERROR;
DirectiveKindMap[".warning"] = DK_WARNING;
}
MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
AsmToken EndToken, StartToken = getTok();
unsigned NestLevel = 0;
for (;;) {
// Check whether we have reached the end of the file.
if (getLexer().is(AsmToken::Eof)) {
Error(DirectiveLoc, "no matching '.endr' in definition");
return nullptr;
}
if (Lexer.is(AsmToken::Identifier) &&
(getTok().getIdentifier() == ".rept")) {
++NestLevel;
}
// Otherwise, check whether we have reached the .endr.
if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
if (NestLevel == 0) {
EndToken = getTok();
Lex();
if (Lexer.isNot(AsmToken::EndOfStatement)) {
TokError("unexpected token in '.endr' directive");
return nullptr;
}
break;
}
--NestLevel;
}
// Otherwise, scan till the end of the statement.
eatToEndOfStatement();
}
const char *BodyStart = StartToken.getLoc().getPointer();
const char *BodyEnd = EndToken.getLoc().getPointer();
StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
// We Are Anonymous.
MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
return &MacroLikeBodies.back();
}
void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
raw_svector_ostream &OS) {
OS << ".endr\n";
std::unique_ptr<MemoryBuffer> Instantiation =
MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
// Create the macro instantiation object and add to the current macro
// instantiation stack.
MacroInstantiation *MI = new MacroInstantiation(
DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
ActiveMacros.push_back(MI);
// Jump to the macro instantiation and prime the lexer.
CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Lex();
}
/// parseDirectiveRept
/// ::= .rep | .rept count
bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
const MCExpr *CountExpr;
SMLoc CountLoc = getTok().getLoc();
if (parseExpression(CountExpr))
return true;
int64_t Count;
if (!CountExpr->evaluateAsAbsolute(Count)) {
eatToEndOfStatement();
return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
}
if (Count < 0)
return Error(CountLoc, "Count is negative");
if (Lexer.isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '" + Dir + "' directive");
// Eat the end of statement.
Lex();
// Lex the rept definition.
MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
if (!M)
return true;
// Macro instantiation is lexical, unfortunately. We construct a new buffer
// to hold the macro body with substitutions.
SmallString<256> Buf;
raw_svector_ostream OS(Buf);
while (Count--) {
// Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
return true;
}
instantiateMacroLikeBody(M, DirectiveLoc, OS);
return false;
}
/// parseDirectiveIrp
/// ::= .irp symbol,values
bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
MCAsmMacroParameter Parameter;
if (parseIdentifier(Parameter.Name))
return TokError("expected identifier in '.irp' directive");
if (Lexer.isNot(AsmToken::Comma))
return TokError("expected comma in '.irp' directive");
Lex();
MCAsmMacroArguments A;
if (parseMacroArguments(nullptr, A))
return true;
// Eat the end of statement.
Lex();
// Lex the irp definition.
MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
if (!M)
return true;
// Macro instantiation is lexical, unfortunately. We construct a new buffer
// to hold the macro body with substitutions.
SmallString<256> Buf;
raw_svector_ostream OS(Buf);
for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
// Note that the AtPseudoVariable is enabled for instantiations of .irp.
// This is undocumented, but GAS seems to support it.
if (expandMacro(OS, M->Body, Parameter, *i, true, getTok().getLoc()))
return true;
}
instantiateMacroLikeBody(M, DirectiveLoc, OS);
return false;
}
/// parseDirectiveIrpc
/// ::= .irpc symbol,values
bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
MCAsmMacroParameter Parameter;
if (parseIdentifier(Parameter.Name))
return TokError("expected identifier in '.irpc' directive");
if (Lexer.isNot(AsmToken::Comma))
return TokError("expected comma in '.irpc' directive");
Lex();
MCAsmMacroArguments A;
if (parseMacroArguments(nullptr, A))
return true;
if (A.size() != 1 || A.front().size() != 1)
return TokError("unexpected token in '.irpc' directive");
// Eat the end of statement.
Lex();
// Lex the irpc definition.
MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
if (!M)
return true;
// Macro instantiation is lexical, unfortunately. We construct a new buffer
// to hold the macro body with substitutions.
SmallString<256> Buf;
raw_svector_ostream OS(Buf);
StringRef Values = A.front().front().getString();
for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
MCAsmMacroArgument Arg;
Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
// Note that the AtPseudoVariable is enabled for instantiations of .irpc.
// This is undocumented, but GAS seems to support it.
if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
return true;
}
instantiateMacroLikeBody(M, DirectiveLoc, OS);
return false;
}
bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
if (ActiveMacros.empty())
return TokError("unmatched '.endr' directive");
// The only .repl that should get here are the ones created by
// instantiateMacroLikeBody.
assert(getLexer().is(AsmToken::EndOfStatement));
handleMacroExit();
return false;
}
bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
size_t Len) {
const MCExpr *Value;
SMLoc ExprLoc = getLexer().getLoc();
if (parseExpression(Value))
return true;
const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
if (!MCE)
return Error(ExprLoc, "unexpected expression in _emit");
uint64_t IntValue = MCE->getValue();
if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
return Error(ExprLoc, "literal value out of range for directive");
Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
return false;
}
bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
const MCExpr *Value;
SMLoc ExprLoc = getLexer().getLoc();
if (parseExpression(Value))
return true;
const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
if (!MCE)
return Error(ExprLoc, "unexpected expression in align");
uint64_t IntValue = MCE->getValue();
if (!isPowerOf2_64(IntValue))
return Error(ExprLoc, "literal value not a power of two greater then zero");
Info.AsmRewrites->push_back(
AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
return false;
}
// We are comparing pointers, but the pointers are relative to a single string.
// Thus, this should always be deterministic.
// HLSL Change: changed calling convention to __cdecl
static int __cdecl rewritesSort(const AsmRewrite *AsmRewriteA,
const AsmRewrite *AsmRewriteB) {
if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
return -1;
if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
return 1;
// It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
// rewrite to the same location. Make sure the SizeDirective rewrite is
// performed first, then the Imm/ImmPrefix and finally the Input/Output. This
// ensures the sort algorithm is stable.
if (AsmRewritePrecedence[AsmRewriteA->Kind] >
AsmRewritePrecedence[AsmRewriteB->Kind])
return -1;
if (AsmRewritePrecedence[AsmRewriteA->Kind] <
AsmRewritePrecedence[AsmRewriteB->Kind])
return 1;
llvm_unreachable("Unstable rewrite sort.");
}
bool AsmParser::parseMSInlineAsm(
void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
SmallVectorImpl<std::string> &Constraints,
SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
SmallVector<void *, 4> InputDecls;
SmallVector<void *, 4> OutputDecls;
SmallVector<bool, 4> InputDeclsAddressOf;
SmallVector<bool, 4> OutputDeclsAddressOf;
SmallVector<std::string, 4> InputConstraints;
SmallVector<std::string, 4> OutputConstraints;
SmallVector<unsigned, 4> ClobberRegs;
SmallVector<AsmRewrite, 4> AsmStrRewrites;
// Prime the lexer.
Lex();
// While we have input, parse each statement.
unsigned InputIdx = 0;
unsigned OutputIdx = 0;
while (getLexer().isNot(AsmToken::Eof)) {
ParseStatementInfo Info(&AsmStrRewrites);
if (parseStatement(Info, &SI))
return true;
if (Info.ParseError)
return true;
if (Info.Opcode == ~0U)
continue;
const MCInstrDesc &Desc = MII->get(Info.Opcode);
// Build the list of clobbers, outputs and inputs.
for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
// Immediate.
if (Operand.isImm())
continue;
// Register operand.
if (Operand.isReg() && !Operand.needAddressOf() &&
!getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
unsigned NumDefs = Desc.getNumDefs();
// Clobber.
if (NumDefs && Operand.getMCOperandNum() < NumDefs)
ClobberRegs.push_back(Operand.getReg());
continue;
}
// Expr/Input or Output.
StringRef SymName = Operand.getSymName();
if (SymName.empty())
continue;
void *OpDecl = Operand.getOpDecl();
if (!OpDecl)
continue;
bool isOutput = (i == 1) && Desc.mayStore();
SMLoc Start = SMLoc::getFromPointer(SymName.data());
if (isOutput) {
++InputIdx;
OutputDecls.push_back(OpDecl);
OutputDeclsAddressOf.push_back(Operand.needAddressOf());
OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
} else {
InputDecls.push_back(OpDecl);
InputDeclsAddressOf.push_back(Operand.needAddressOf());
InputConstraints.push_back(Operand.getConstraint().str());
AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
}
}
// Consider implicit defs to be clobbers. Think of cpuid and push.
ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
Desc.getNumImplicitDefs());
ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
}
// Set the number of Outputs and Inputs.
NumOutputs = OutputDecls.size();
NumInputs = InputDecls.size();
// Set the unique clobbers.
array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
ClobberRegs.end());
Clobbers.assign(ClobberRegs.size(), std::string());
for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
raw_string_ostream OS(Clobbers[I]);
IP->printRegName(OS, ClobberRegs[I]);
}
// Merge the various outputs and inputs. Output are expected first.
if (NumOutputs || NumInputs) {
unsigned NumExprs = NumOutputs + NumInputs;
OpDecls.resize(NumExprs);
Constraints.resize(NumExprs);
for (unsigned i = 0; i < NumOutputs; ++i) {
OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Constraints[i] = OutputConstraints[i];
}
for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Constraints[j] = InputConstraints[i];
}
}
// Build the IR assembly string.
std::string AsmStringIR;
raw_string_ostream OS(AsmStringIR);
StringRef ASMString =
SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
const char *AsmStart = ASMString.begin();
const char *AsmEnd = ASMString.end();
array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
for (const AsmRewrite &AR : AsmStrRewrites) {
AsmRewriteKind Kind = AR.Kind;
if (Kind == AOK_Delete)
continue;
const char *Loc = AR.Loc.getPointer();
assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
// Emit everything up to the immediate/expression.
if (unsigned Len = Loc - AsmStart)
OS << StringRef(AsmStart, Len);
// Skip the original expression.
if (Kind == AOK_Skip) {
AsmStart = Loc + AR.Len;
continue;
}
unsigned AdditionalSkip = 0;
// Rewrite expressions in $N notation.
switch (Kind) {
default:
break;
case AOK_Imm:
OS << "$$" << AR.Val;
break;
case AOK_ImmPrefix:
OS << "$$";
break;
case AOK_Label:
OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
break;
case AOK_Input:
OS << '$' << InputIdx++;
break;
case AOK_Output:
OS << '$' << OutputIdx++;
break;
case AOK_SizeDirective:
switch (AR.Val) {
default: break;
case 8: OS << "byte ptr "; break;
case 16: OS << "word ptr "; break;
case 32: OS << "dword ptr "; break;
case 64: OS << "qword ptr "; break;
case 80: OS << "xword ptr "; break;
case 128: OS << "xmmword ptr "; break;
case 256: OS << "ymmword ptr "; break;
}
break;
case AOK_Emit:
OS << ".byte";
break;
case AOK_Align: {
unsigned Val = AR.Val;
OS << ".align " << Val;
// Skip the original immediate.
assert(Val < 10 && "Expected alignment less then 2^10.");
AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
break;
}
case AOK_DotOperator:
// Insert the dot if the user omitted it.
OS.flush();
if (AsmStringIR.back() != '.')
OS << '.';
OS << AR.Val;
break;
}
// Skip the original expression.
AsmStart = Loc + AR.Len + AdditionalSkip;
}
// Emit the remainder of the asm string.
if (AsmStart != AsmEnd)
OS << StringRef(AsmStart, AsmEnd - AsmStart);
AsmString = OS.str();
return false;
}
namespace llvm {
namespace MCParserUtils {
/// Returns whether the given symbol is used anywhere in the given expression,
/// or subexpressions.
static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
switch (Value->getKind()) {
case MCExpr::Binary: {
const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
isSymbolUsedInExpression(Sym, BE->getRHS());
}
case MCExpr::Target:
case MCExpr::Constant:
return false;
case MCExpr::SymbolRef: {
const MCSymbol &S =
static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
if (S.isVariable())
return isSymbolUsedInExpression(Sym, S.getVariableValue());
return &S == Sym;
}
case MCExpr::Unary:
return isSymbolUsedInExpression(
Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
}
llvm_unreachable("Unknown expr kind!");
}
bool parseAssignmentExpression(StringRef Name, bool allow_redef,
MCAsmParser &Parser, MCSymbol *&Sym,
const MCExpr *&Value) {
MCAsmLexer &Lexer = Parser.getLexer();
// FIXME: Use better location, we should use proper tokens.
SMLoc EqualLoc = Lexer.getLoc();
if (Parser.parseExpression(Value)) {
Parser.TokError("missing expression");
Parser.eatToEndOfStatement();
return true;
}
// Note: we don't count b as used in "a = b". This is to allow
// a = b
// b = c
if (Lexer.isNot(AsmToken::EndOfStatement))
return Parser.TokError("unexpected token in assignment");
// Eat the end of statement marker.
Parser.Lex();
// Validate that the LHS is allowed to be a variable (either it has not been
// used as a symbol, or it is an absolute symbol).
Sym = Parser.getContext().lookupSymbol(Name);
if (Sym) {
// Diagnose assignment to a label.
//
// FIXME: Diagnostics. Note the location of the definition as a label.
// FIXME: Diagnose assignment to protected identifier (e.g., register name).
if (isSymbolUsedInExpression(Sym, Value))
return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
; // Allow redefinitions of undefined symbols only used in directives.
else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
; // Allow redefinitions of variables that haven't yet been used.
else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
else if (!Sym->isVariable())
return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
return Parser.Error(EqualLoc,
"invalid reassignment of non-absolute variable '" +
Name + "'");
// Don't count these checks as uses.
Sym->setUsed(false);
} else if (Name == ".") {
if (Parser.getStreamer().EmitValueToOffset(Value, 0)) {
Parser.Error(EqualLoc, "expected absolute expression");
Parser.eatToEndOfStatement();
return true;
}
return false;
} else
Sym = Parser.getContext().getOrCreateSymbol(Name);
Sym->setRedefinable(allow_redef);
return false;
}
} // namespace MCParserUtils
} // namespace llvm
/// \brief Create an MCAsmParser instance.
MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
MCStreamer &Out, const MCAsmInfo &MAI) {
return new AsmParser(SM, C, Out, MAI);
}
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCParser/CMakeLists.txt | add_llvm_library(LLVMMCParser
AsmLexer.cpp
AsmParser.cpp
COFFAsmParser.cpp
DarwinAsmParser.cpp
ELFAsmParser.cpp
MCAsmLexer.cpp
MCAsmParser.cpp
MCAsmParserExtension.cpp
MCTargetAsmParser.cpp
ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/MC/MCParser
)
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCParser/MCAsmParserExtension.cpp | //===-- MCAsmParserExtension.cpp - Asm Parser Hooks -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCParser/MCAsmParserExtension.h"
using namespace llvm;
MCAsmParserExtension::MCAsmParserExtension() :
BracketExpressionsSupported(false) {
}
MCAsmParserExtension::~MCAsmParserExtension() {
}
void MCAsmParserExtension::Initialize(MCAsmParser &Parser) {
this->Parser = &Parser;
}
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCParser/MCAsmParser.cpp | //===-- MCAsmParser.cpp - Abstract Asm Parser Interface -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCParser/MCAsmParser.h"
#include "llvm/ADT/Twine.h"
#include "llvm/MC/MCParser/MCAsmLexer.h"
#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
#include "llvm/MC/MCTargetAsmParser.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
MCAsmParser::MCAsmParser() : TargetParser(nullptr), ShowParsedOperands(0) {
}
MCAsmParser::~MCAsmParser() {
}
void MCAsmParser::setTargetParser(MCTargetAsmParser &P) {
assert(!TargetParser && "Target parser is already initialized!");
TargetParser = &P;
TargetParser->Initialize(*this);
}
const AsmToken &MCAsmParser::getTok() const {
return getLexer().getTok();
}
bool MCAsmParser::TokError(const Twine &Msg, ArrayRef<SMRange> Ranges) {
Error(getLexer().getLoc(), Msg, Ranges);
return true;
}
bool MCAsmParser::parseExpression(const MCExpr *&Res) {
SMLoc L;
return parseExpression(Res, L);
}
void MCParsedAsmOperand::dump() const {
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dbgs() << " " << *this;
#endif
}
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCParser/MCAsmLexer.cpp | //===-- MCAsmLexer.cpp - Abstract Asm Lexer Interface ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCParser/MCAsmLexer.h"
#include "llvm/Support/SourceMgr.h"
using namespace llvm;
MCAsmLexer::MCAsmLexer() : CurTok(AsmToken::Error, StringRef()),
TokStart(nullptr), SkipSpace(true) {
}
MCAsmLexer::~MCAsmLexer() {
}
SMLoc MCAsmLexer::getLoc() const {
return SMLoc::getFromPointer(TokStart);
}
SMLoc AsmToken::getLoc() const {
return SMLoc::getFromPointer(Str.data());
}
SMLoc AsmToken::getEndLoc() const {
return SMLoc::getFromPointer(Str.data() + Str.size());
}
SMRange AsmToken::getLocRange() const {
return SMRange(getLoc(), getEndLoc());
}
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCParser/LLVMBuild.txt | ;===- ./lib/MC/MCParser/LLVMBuild.txt --------------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Library
name = MCParser
parent = MC
required_libraries = MC Support
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCParser/DarwinAsmParser.cpp | //===- DarwinAsmParser.cpp - Darwin (Mach-O) Assembly Parser --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCParser/MCAsmParserExtension.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Twine.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCParser/MCAsmLexer.h"
#include "llvm/MC/MCParser/MCAsmParser.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SourceMgr.h"
using namespace llvm;
namespace {
/// \brief Implementation of directive handling which is shared across all
/// Darwin targets.
class DarwinAsmParser : public MCAsmParserExtension {
template<bool (DarwinAsmParser::*HandlerMethod)(StringRef, SMLoc)>
void addDirectiveHandler(StringRef Directive) {
MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair(
this, HandleDirective<DarwinAsmParser, HandlerMethod>);
getParser().addDirectiveHandler(Directive, Handler);
}
bool parseSectionSwitch(const char *Segment, const char *Section,
unsigned TAA = 0, unsigned ImplicitAlign = 0,
unsigned StubSize = 0);
public:
DarwinAsmParser() {}
void Initialize(MCAsmParser &Parser) override {
// Call the base implementation.
this->MCAsmParserExtension::Initialize(Parser);
addDirectiveHandler<&DarwinAsmParser::parseDirectiveDesc>(".desc");
addDirectiveHandler<&DarwinAsmParser::parseDirectiveIndirectSymbol>(
".indirect_symbol");
addDirectiveHandler<&DarwinAsmParser::parseDirectiveLsym>(".lsym");
addDirectiveHandler<&DarwinAsmParser::parseDirectiveSubsectionsViaSymbols>(
".subsections_via_symbols");
addDirectiveHandler<&DarwinAsmParser::parseDirectiveDumpOrLoad>(".dump");
addDirectiveHandler<&DarwinAsmParser::parseDirectiveDumpOrLoad>(".load");
addDirectiveHandler<&DarwinAsmParser::parseDirectiveSection>(".section");
addDirectiveHandler<&DarwinAsmParser::parseDirectivePushSection>(
".pushsection");
addDirectiveHandler<&DarwinAsmParser::parseDirectivePopSection>(
".popsection");
addDirectiveHandler<&DarwinAsmParser::parseDirectivePrevious>(".previous");
addDirectiveHandler<&DarwinAsmParser::parseDirectiveSecureLogUnique>(
".secure_log_unique");
addDirectiveHandler<&DarwinAsmParser::parseDirectiveSecureLogReset>(
".secure_log_reset");
addDirectiveHandler<&DarwinAsmParser::parseDirectiveTBSS>(".tbss");
addDirectiveHandler<&DarwinAsmParser::parseDirectiveZerofill>(".zerofill");
addDirectiveHandler<&DarwinAsmParser::parseDirectiveDataRegion>(
".data_region");
addDirectiveHandler<&DarwinAsmParser::parseDirectiveDataRegionEnd>(
".end_data_region");
// Special section directives.
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveBss>(".bss");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveConst>(".const");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveConstData>(
".const_data");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveConstructor>(
".constructor");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveCString>(
".cstring");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveData>(".data");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveDestructor>(
".destructor");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveDyld>(".dyld");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveFVMLibInit0>(
".fvmlib_init0");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveFVMLibInit1>(
".fvmlib_init1");
addDirectiveHandler<
&DarwinAsmParser::parseSectionDirectiveLazySymbolPointers>(
".lazy_symbol_pointer");
addDirectiveHandler<&DarwinAsmParser::parseDirectiveLinkerOption>(
".linker_option");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveLiteral16>(
".literal16");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveLiteral4>(
".literal4");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveLiteral8>(
".literal8");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveModInitFunc>(
".mod_init_func");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveModTermFunc>(
".mod_term_func");
addDirectiveHandler<
&DarwinAsmParser::parseSectionDirectiveNonLazySymbolPointers>(
".non_lazy_symbol_pointer");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCCatClsMeth>(
".objc_cat_cls_meth");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCCatInstMeth>(
".objc_cat_inst_meth");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCCategory>(
".objc_category");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClass>(
".objc_class");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClassNames>(
".objc_class_names");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClassVars>(
".objc_class_vars");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClsMeth>(
".objc_cls_meth");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClsRefs>(
".objc_cls_refs");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCInstMeth>(
".objc_inst_meth");
addDirectiveHandler<
&DarwinAsmParser::parseSectionDirectiveObjCInstanceVars>(
".objc_instance_vars");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCMessageRefs>(
".objc_message_refs");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCMetaClass>(
".objc_meta_class");
addDirectiveHandler<
&DarwinAsmParser::parseSectionDirectiveObjCMethVarNames>(
".objc_meth_var_names");
addDirectiveHandler<
&DarwinAsmParser::parseSectionDirectiveObjCMethVarTypes>(
".objc_meth_var_types");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCModuleInfo>(
".objc_module_info");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCProtocol>(
".objc_protocol");
addDirectiveHandler<
&DarwinAsmParser::parseSectionDirectiveObjCSelectorStrs>(
".objc_selector_strs");
addDirectiveHandler<
&DarwinAsmParser::parseSectionDirectiveObjCStringObject>(
".objc_string_object");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCSymbols>(
".objc_symbols");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectivePICSymbolStub>(
".picsymbol_stub");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveStaticConst>(
".static_const");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveStaticData>(
".static_data");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveSymbolStub>(
".symbol_stub");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveTData>(".tdata");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveText>(".text");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveThreadInitFunc>(
".thread_init_func");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveTLV>(".tlv");
addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveIdent>(".ident");
addDirectiveHandler<&DarwinAsmParser::parseVersionMin>(".ios_version_min");
addDirectiveHandler<&DarwinAsmParser::parseVersionMin>(
".macosx_version_min");
}
bool parseDirectiveDesc(StringRef, SMLoc);
bool parseDirectiveIndirectSymbol(StringRef, SMLoc);
bool parseDirectiveDumpOrLoad(StringRef, SMLoc);
bool parseDirectiveLsym(StringRef, SMLoc);
bool parseDirectiveLinkerOption(StringRef, SMLoc);
bool parseDirectiveSection(StringRef, SMLoc);
bool parseDirectivePushSection(StringRef, SMLoc);
bool parseDirectivePopSection(StringRef, SMLoc);
bool parseDirectivePrevious(StringRef, SMLoc);
bool parseDirectiveSecureLogReset(StringRef, SMLoc);
bool parseDirectiveSecureLogUnique(StringRef, SMLoc);
bool parseDirectiveSubsectionsViaSymbols(StringRef, SMLoc);
bool parseDirectiveTBSS(StringRef, SMLoc);
bool parseDirectiveZerofill(StringRef, SMLoc);
bool parseDirectiveDataRegion(StringRef, SMLoc);
bool parseDirectiveDataRegionEnd(StringRef, SMLoc);
// Named Section Directive
bool parseSectionDirectiveBss(StringRef, SMLoc) {
return parseSectionSwitch("__DATA", "__bss");
}
bool parseSectionDirectiveConst(StringRef, SMLoc) {
return parseSectionSwitch("__TEXT", "__const");
}
bool parseSectionDirectiveStaticConst(StringRef, SMLoc) {
return parseSectionSwitch("__TEXT", "__static_const");
}
bool parseSectionDirectiveCString(StringRef, SMLoc) {
return parseSectionSwitch("__TEXT","__cstring",
MachO::S_CSTRING_LITERALS);
}
bool parseSectionDirectiveLiteral4(StringRef, SMLoc) {
return parseSectionSwitch("__TEXT", "__literal4",
MachO::S_4BYTE_LITERALS, 4);
}
bool parseSectionDirectiveLiteral8(StringRef, SMLoc) {
return parseSectionSwitch("__TEXT", "__literal8",
MachO::S_8BYTE_LITERALS, 8);
}
bool parseSectionDirectiveLiteral16(StringRef, SMLoc) {
return parseSectionSwitch("__TEXT","__literal16",
MachO::S_16BYTE_LITERALS, 16);
}
bool parseSectionDirectiveConstructor(StringRef, SMLoc) {
return parseSectionSwitch("__TEXT","__constructor");
}
bool parseSectionDirectiveDestructor(StringRef, SMLoc) {
return parseSectionSwitch("__TEXT","__destructor");
}
bool parseSectionDirectiveFVMLibInit0(StringRef, SMLoc) {
return parseSectionSwitch("__TEXT","__fvmlib_init0");
}
bool parseSectionDirectiveFVMLibInit1(StringRef, SMLoc) {
return parseSectionSwitch("__TEXT","__fvmlib_init1");
}
bool parseSectionDirectiveSymbolStub(StringRef, SMLoc) {
return parseSectionSwitch("__TEXT","__symbol_stub",
MachO::S_SYMBOL_STUBS |
MachO::S_ATTR_PURE_INSTRUCTIONS,
// FIXME: Different on PPC and ARM.
0, 16);
}
bool parseSectionDirectivePICSymbolStub(StringRef, SMLoc) {
return parseSectionSwitch("__TEXT","__picsymbol_stub",
MachO::S_SYMBOL_STUBS |
MachO::S_ATTR_PURE_INSTRUCTIONS, 0, 26);
}
bool parseSectionDirectiveData(StringRef, SMLoc) {
return parseSectionSwitch("__DATA", "__data");
}
bool parseSectionDirectiveStaticData(StringRef, SMLoc) {
return parseSectionSwitch("__DATA", "__static_data");
}
bool parseSectionDirectiveNonLazySymbolPointers(StringRef, SMLoc) {
return parseSectionSwitch("__DATA", "__nl_symbol_ptr",
MachO::S_NON_LAZY_SYMBOL_POINTERS, 4);
}
bool parseSectionDirectiveLazySymbolPointers(StringRef, SMLoc) {
return parseSectionSwitch("__DATA", "__la_symbol_ptr",
MachO::S_LAZY_SYMBOL_POINTERS, 4);
}
bool parseSectionDirectiveDyld(StringRef, SMLoc) {
return parseSectionSwitch("__DATA", "__dyld");
}
bool parseSectionDirectiveModInitFunc(StringRef, SMLoc) {
return parseSectionSwitch("__DATA", "__mod_init_func",
MachO::S_MOD_INIT_FUNC_POINTERS, 4);
}
bool parseSectionDirectiveModTermFunc(StringRef, SMLoc) {
return parseSectionSwitch("__DATA", "__mod_term_func",
MachO::S_MOD_TERM_FUNC_POINTERS, 4);
}
bool parseSectionDirectiveConstData(StringRef, SMLoc) {
return parseSectionSwitch("__DATA", "__const");
}
bool parseSectionDirectiveObjCClass(StringRef, SMLoc) {
return parseSectionSwitch("__OBJC", "__class",
MachO::S_ATTR_NO_DEAD_STRIP);
}
bool parseSectionDirectiveObjCMetaClass(StringRef, SMLoc) {
return parseSectionSwitch("__OBJC", "__meta_class",
MachO::S_ATTR_NO_DEAD_STRIP);
}
bool parseSectionDirectiveObjCCatClsMeth(StringRef, SMLoc) {
return parseSectionSwitch("__OBJC", "__cat_cls_meth",
MachO::S_ATTR_NO_DEAD_STRIP);
}
bool parseSectionDirectiveObjCCatInstMeth(StringRef, SMLoc) {
return parseSectionSwitch("__OBJC", "__cat_inst_meth",
MachO::S_ATTR_NO_DEAD_STRIP);
}
bool parseSectionDirectiveObjCProtocol(StringRef, SMLoc) {
return parseSectionSwitch("__OBJC", "__protocol",
MachO::S_ATTR_NO_DEAD_STRIP);
}
bool parseSectionDirectiveObjCStringObject(StringRef, SMLoc) {
return parseSectionSwitch("__OBJC", "__string_object",
MachO::S_ATTR_NO_DEAD_STRIP);
}
bool parseSectionDirectiveObjCClsMeth(StringRef, SMLoc) {
return parseSectionSwitch("__OBJC", "__cls_meth",
MachO::S_ATTR_NO_DEAD_STRIP);
}
bool parseSectionDirectiveObjCInstMeth(StringRef, SMLoc) {
return parseSectionSwitch("__OBJC", "__inst_meth",
MachO::S_ATTR_NO_DEAD_STRIP);
}
bool parseSectionDirectiveObjCClsRefs(StringRef, SMLoc) {
return parseSectionSwitch("__OBJC", "__cls_refs",
MachO::S_ATTR_NO_DEAD_STRIP |
MachO::S_LITERAL_POINTERS, 4);
}
bool parseSectionDirectiveObjCMessageRefs(StringRef, SMLoc) {
return parseSectionSwitch("__OBJC", "__message_refs",
MachO::S_ATTR_NO_DEAD_STRIP |
MachO::S_LITERAL_POINTERS, 4);
}
bool parseSectionDirectiveObjCSymbols(StringRef, SMLoc) {
return parseSectionSwitch("__OBJC", "__symbols",
MachO::S_ATTR_NO_DEAD_STRIP);
}
bool parseSectionDirectiveObjCCategory(StringRef, SMLoc) {
return parseSectionSwitch("__OBJC", "__category",
MachO::S_ATTR_NO_DEAD_STRIP);
}
bool parseSectionDirectiveObjCClassVars(StringRef, SMLoc) {
return parseSectionSwitch("__OBJC", "__class_vars",
MachO::S_ATTR_NO_DEAD_STRIP);
}
bool parseSectionDirectiveObjCInstanceVars(StringRef, SMLoc) {
return parseSectionSwitch("__OBJC", "__instance_vars",
MachO::S_ATTR_NO_DEAD_STRIP);
}
bool parseSectionDirectiveObjCModuleInfo(StringRef, SMLoc) {
return parseSectionSwitch("__OBJC", "__module_info",
MachO::S_ATTR_NO_DEAD_STRIP);
}
bool parseSectionDirectiveObjCClassNames(StringRef, SMLoc) {
return parseSectionSwitch("__TEXT", "__cstring",
MachO::S_CSTRING_LITERALS);
}
bool parseSectionDirectiveObjCMethVarTypes(StringRef, SMLoc) {
return parseSectionSwitch("__TEXT", "__cstring",
MachO::S_CSTRING_LITERALS);
}
bool parseSectionDirectiveObjCMethVarNames(StringRef, SMLoc) {
return parseSectionSwitch("__TEXT", "__cstring",
MachO::S_CSTRING_LITERALS);
}
bool parseSectionDirectiveObjCSelectorStrs(StringRef, SMLoc) {
return parseSectionSwitch("__OBJC", "__selector_strs",
MachO::S_CSTRING_LITERALS);
}
bool parseSectionDirectiveTData(StringRef, SMLoc) {
return parseSectionSwitch("__DATA", "__thread_data",
MachO::S_THREAD_LOCAL_REGULAR);
}
bool parseSectionDirectiveText(StringRef, SMLoc) {
return parseSectionSwitch("__TEXT", "__text",
MachO::S_ATTR_PURE_INSTRUCTIONS);
}
bool parseSectionDirectiveTLV(StringRef, SMLoc) {
return parseSectionSwitch("__DATA", "__thread_vars",
MachO::S_THREAD_LOCAL_VARIABLES);
}
bool parseSectionDirectiveIdent(StringRef, SMLoc) {
// Darwin silently ignores the .ident directive.
getParser().eatToEndOfStatement();
return false;
}
bool parseSectionDirectiveThreadInitFunc(StringRef, SMLoc) {
return parseSectionSwitch("__DATA", "__thread_init",
MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS);
}
bool parseVersionMin(StringRef, SMLoc);
};
} // end anonymous namespace
bool DarwinAsmParser::parseSectionSwitch(const char *Segment,
const char *Section,
unsigned TAA, unsigned Align,
unsigned StubSize) {
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in section switching directive");
Lex();
// FIXME: Arch specific.
bool isText = TAA & MachO::S_ATTR_PURE_INSTRUCTIONS;
getStreamer().SwitchSection(getContext().getMachOSection(
Segment, Section, TAA, StubSize,
isText ? SectionKind::getText()
: SectionKind::getDataRel()));
// Set the implicit alignment, if any.
//
// FIXME: This isn't really what 'as' does; I think it just uses the implicit
// alignment on the section (e.g., if one manually inserts bytes into the
// section, then just issuing the section switch directive will not realign
// the section. However, this is arguably more reasonable behavior, and there
// is no good reason for someone to intentionally emit incorrectly sized
// values into the implicitly aligned sections.
if (Align)
getStreamer().EmitValueToAlignment(Align);
return false;
}
/// parseDirectiveDesc
/// ::= .desc identifier , expression
bool DarwinAsmParser::parseDirectiveDesc(StringRef, SMLoc) {
StringRef Name;
if (getParser().parseIdentifier(Name))
return TokError("expected identifier in directive");
// Handle the identifier as the key symbol.
MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in '.desc' directive");
Lex();
int64_t DescValue;
if (getParser().parseAbsoluteExpression(DescValue))
return true;
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.desc' directive");
Lex();
// Set the n_desc field of this Symbol to this DescValue
getStreamer().EmitSymbolDesc(Sym, DescValue);
return false;
}
/// parseDirectiveIndirectSymbol
/// ::= .indirect_symbol identifier
bool DarwinAsmParser::parseDirectiveIndirectSymbol(StringRef, SMLoc Loc) {
const MCSectionMachO *Current = static_cast<const MCSectionMachO*>(
getStreamer().getCurrentSection().first);
MachO::SectionType SectionType = Current->getType();
if (SectionType != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
SectionType != MachO::S_LAZY_SYMBOL_POINTERS &&
SectionType != MachO::S_SYMBOL_STUBS)
return Error(Loc, "indirect symbol not in a symbol pointer or stub "
"section");
StringRef Name;
if (getParser().parseIdentifier(Name))
return TokError("expected identifier in .indirect_symbol directive");
MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
// Assembler local symbols don't make any sense here. Complain loudly.
if (Sym->isTemporary())
return TokError("non-local symbol required in directive");
if (!getStreamer().EmitSymbolAttribute(Sym, MCSA_IndirectSymbol))
return TokError("unable to emit indirect symbol attribute for: " + Name);
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.indirect_symbol' directive");
Lex();
return false;
}
/// parseDirectiveDumpOrLoad
/// ::= ( .dump | .load ) "filename"
bool DarwinAsmParser::parseDirectiveDumpOrLoad(StringRef Directive,
SMLoc IDLoc) {
bool IsDump = Directive == ".dump";
if (getLexer().isNot(AsmToken::String))
return TokError("expected string in '.dump' or '.load' directive");
Lex();
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.dump' or '.load' directive");
Lex();
// FIXME: If/when .dump and .load are implemented they will be done in the
// the assembly parser and not have any need for an MCStreamer API.
if (IsDump)
return Warning(IDLoc, "ignoring directive .dump for now");
else
return Warning(IDLoc, "ignoring directive .load for now");
}
/// ParseDirectiveLinkerOption
/// ::= .linker_option "string" ( , "string" )*
bool DarwinAsmParser::parseDirectiveLinkerOption(StringRef IDVal, SMLoc) {
SmallVector<std::string, 4> Args;
for (;;) {
if (getLexer().isNot(AsmToken::String))
return TokError("expected string in '" + Twine(IDVal) + "' directive");
std::string Data;
if (getParser().parseEscapedString(Data))
return true;
Args.push_back(Data);
Lex();
if (getLexer().is(AsmToken::EndOfStatement))
break;
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Lex();
}
getStreamer().EmitLinkerOptions(Args);
return false;
}
/// parseDirectiveLsym
/// ::= .lsym identifier , expression
bool DarwinAsmParser::parseDirectiveLsym(StringRef, SMLoc) {
StringRef Name;
if (getParser().parseIdentifier(Name))
return TokError("expected identifier in directive");
// Handle the identifier as the key symbol.
MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in '.lsym' directive");
Lex();
const MCExpr *Value;
if (getParser().parseExpression(Value))
return true;
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.lsym' directive");
Lex();
// We don't currently support this directive.
//
// FIXME: Diagnostic location!
(void) Sym;
return TokError("directive '.lsym' is unsupported");
}
/// parseDirectiveSection:
/// ::= .section identifier (',' identifier)*
bool DarwinAsmParser::parseDirectiveSection(StringRef, SMLoc) {
SMLoc Loc = getLexer().getLoc();
StringRef SectionName;
if (getParser().parseIdentifier(SectionName))
return Error(Loc, "expected identifier after '.section' directive");
// Verify there is a following comma.
if (!getLexer().is(AsmToken::Comma))
return TokError("unexpected token in '.section' directive");
std::string SectionSpec = SectionName;
SectionSpec += ",";
// Add all the tokens until the end of the line, ParseSectionSpecifier will
// handle this.
StringRef EOL = getLexer().LexUntilEndOfStatement();
SectionSpec.append(EOL.begin(), EOL.end());
Lex();
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.section' directive");
Lex();
StringRef Segment, Section;
unsigned StubSize;
unsigned TAA;
bool TAAParsed;
std::string ErrorStr =
MCSectionMachO::ParseSectionSpecifier(SectionSpec, Segment, Section,
TAA, TAAParsed, StubSize);
if (!ErrorStr.empty())
return Error(Loc, ErrorStr.c_str());
// FIXME: Arch specific.
bool isText = Segment == "__TEXT"; // FIXME: Hack.
getStreamer().SwitchSection(getContext().getMachOSection(
Segment, Section, TAA, StubSize,
isText ? SectionKind::getText()
: SectionKind::getDataRel()));
return false;
}
/// ParseDirectivePushSection:
/// ::= .pushsection identifier (',' identifier)*
bool DarwinAsmParser::parseDirectivePushSection(StringRef S, SMLoc Loc) {
getStreamer().PushSection();
if (parseDirectiveSection(S, Loc)) {
getStreamer().PopSection();
return true;
}
return false;
}
/// ParseDirectivePopSection:
/// ::= .popsection
bool DarwinAsmParser::parseDirectivePopSection(StringRef, SMLoc) {
if (!getStreamer().PopSection())
return TokError(".popsection without corresponding .pushsection");
return false;
}
/// ParseDirectivePrevious:
/// ::= .previous
bool DarwinAsmParser::parseDirectivePrevious(StringRef DirName, SMLoc) {
MCSectionSubPair PreviousSection = getStreamer().getPreviousSection();
if (!PreviousSection.first)
return TokError(".previous without corresponding .section");
getStreamer().SwitchSection(PreviousSection.first, PreviousSection.second);
return false;
}
/// ParseDirectiveSecureLogUnique
/// ::= .secure_log_unique ... message ...
bool DarwinAsmParser::parseDirectiveSecureLogUnique(StringRef, SMLoc IDLoc) {
StringRef LogMessage = getParser().parseStringToEndOfStatement();
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.secure_log_unique' directive");
if (getContext().getSecureLogUsed())
return Error(IDLoc, ".secure_log_unique specified multiple times");
// Get the secure log path.
const char *SecureLogFile = getContext().getSecureLogFile();
if (!SecureLogFile)
return Error(IDLoc, ".secure_log_unique used but AS_SECURE_LOG_FILE "
"environment variable unset.");
// Open the secure log file if we haven't already.
raw_ostream *OS = getContext().getSecureLog();
if (!OS) {
std::error_code EC;
OS = new raw_fd_ostream(SecureLogFile, EC,
sys::fs::F_Append | sys::fs::F_Text);
if (EC) {
delete OS;
return Error(IDLoc, Twine("can't open secure log file: ") +
SecureLogFile + " (" + EC.message() + ")");
}
getContext().setSecureLog(OS);
}
// Write the message.
unsigned CurBuf = getSourceManager().FindBufferContainingLoc(IDLoc);
*OS << getSourceManager().getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
<< ":" << getSourceManager().FindLineNumber(IDLoc, CurBuf) << ":"
<< LogMessage + "\n";
getContext().setSecureLogUsed(true);
return false;
}
/// ParseDirectiveSecureLogReset
/// ::= .secure_log_reset
bool DarwinAsmParser::parseDirectiveSecureLogReset(StringRef, SMLoc IDLoc) {
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.secure_log_reset' directive");
Lex();
getContext().setSecureLogUsed(false);
return false;
}
/// parseDirectiveSubsectionsViaSymbols
/// ::= .subsections_via_symbols
bool DarwinAsmParser::parseDirectiveSubsectionsViaSymbols(StringRef, SMLoc) {
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.subsections_via_symbols' directive");
Lex();
getStreamer().EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
return false;
}
/// ParseDirectiveTBSS
/// ::= .tbss identifier, size, align
bool DarwinAsmParser::parseDirectiveTBSS(StringRef, SMLoc) {
SMLoc IDLoc = getLexer().getLoc();
StringRef Name;
if (getParser().parseIdentifier(Name))
return TokError("expected identifier in directive");
// Handle the identifier as the key symbol.
MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
int64_t Size;
SMLoc SizeLoc = getLexer().getLoc();
if (getParser().parseAbsoluteExpression(Size))
return true;
int64_t Pow2Alignment = 0;
SMLoc Pow2AlignmentLoc;
if (getLexer().is(AsmToken::Comma)) {
Lex();
Pow2AlignmentLoc = getLexer().getLoc();
if (getParser().parseAbsoluteExpression(Pow2Alignment))
return true;
}
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.tbss' directive");
Lex();
if (Size < 0)
return Error(SizeLoc, "invalid '.tbss' directive size, can't be less than"
"zero");
// FIXME: Diagnose overflow.
if (Pow2Alignment < 0)
return Error(Pow2AlignmentLoc, "invalid '.tbss' alignment, can't be less"
"than zero");
if (!Sym->isUndefined())
return Error(IDLoc, "invalid symbol redefinition");
getStreamer().EmitTBSSSymbol(getContext().getMachOSection(
"__DATA", "__thread_bss",
MachO::S_THREAD_LOCAL_ZEROFILL,
0, SectionKind::getThreadBSS()),
Sym, Size, 1 << Pow2Alignment);
return false;
}
/// ParseDirectiveZerofill
/// ::= .zerofill segname , sectname [, identifier , size_expression [
/// , align_expression ]]
bool DarwinAsmParser::parseDirectiveZerofill(StringRef, SMLoc) {
StringRef Segment;
if (getParser().parseIdentifier(Segment))
return TokError("expected segment name after '.zerofill' directive");
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
StringRef Section;
if (getParser().parseIdentifier(Section))
return TokError("expected section name after comma in '.zerofill' "
"directive");
// If this is the end of the line all that was wanted was to create the
// the section but with no symbol.
if (getLexer().is(AsmToken::EndOfStatement)) {
// Create the zerofill section but no symbol
getStreamer().EmitZerofill(getContext().getMachOSection(
Segment, Section, MachO::S_ZEROFILL,
0, SectionKind::getBSS()));
return false;
}
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
SMLoc IDLoc = getLexer().getLoc();
StringRef IDStr;
if (getParser().parseIdentifier(IDStr))
return TokError("expected identifier in directive");
// handle the identifier as the key symbol.
MCSymbol *Sym = getContext().getOrCreateSymbol(IDStr);
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
int64_t Size;
SMLoc SizeLoc = getLexer().getLoc();
if (getParser().parseAbsoluteExpression(Size))
return true;
int64_t Pow2Alignment = 0;
SMLoc Pow2AlignmentLoc;
if (getLexer().is(AsmToken::Comma)) {
Lex();
Pow2AlignmentLoc = getLexer().getLoc();
if (getParser().parseAbsoluteExpression(Pow2Alignment))
return true;
}
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.zerofill' directive");
Lex();
if (Size < 0)
return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
"than zero");
// NOTE: The alignment in the directive is a power of 2 value, the assembler
// may internally end up wanting an alignment in bytes.
// FIXME: Diagnose overflow.
if (Pow2Alignment < 0)
return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
"can't be less than zero");
if (!Sym->isUndefined())
return Error(IDLoc, "invalid symbol redefinition");
// Create the zerofill Symbol with Size and Pow2Alignment
//
// FIXME: Arch specific.
getStreamer().EmitZerofill(getContext().getMachOSection(
Segment, Section, MachO::S_ZEROFILL,
0, SectionKind::getBSS()),
Sym, Size, 1 << Pow2Alignment);
return false;
}
/// ParseDirectiveDataRegion
/// ::= .data_region [ ( jt8 | jt16 | jt32 ) ]
bool DarwinAsmParser::parseDirectiveDataRegion(StringRef, SMLoc) {
if (getLexer().is(AsmToken::EndOfStatement)) {
Lex();
getStreamer().EmitDataRegion(MCDR_DataRegion);
return false;
}
StringRef RegionType;
SMLoc Loc = getParser().getTok().getLoc();
if (getParser().parseIdentifier(RegionType))
return TokError("expected region type after '.data_region' directive");
int Kind = StringSwitch<int>(RegionType)
.Case("jt8", MCDR_DataRegionJT8)
.Case("jt16", MCDR_DataRegionJT16)
.Case("jt32", MCDR_DataRegionJT32)
.Default(-1);
if (Kind == -1)
return Error(Loc, "unknown region type in '.data_region' directive");
Lex();
getStreamer().EmitDataRegion((MCDataRegionType)Kind);
return false;
}
/// ParseDirectiveDataRegionEnd
/// ::= .end_data_region
bool DarwinAsmParser::parseDirectiveDataRegionEnd(StringRef, SMLoc) {
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.end_data_region' directive");
Lex();
getStreamer().EmitDataRegion(MCDR_DataRegionEnd);
return false;
}
/// parseVersionMin
/// ::= .ios_version_min major,minor[,update]
/// ::= .macosx_version_min major,minor[,update]
bool DarwinAsmParser::parseVersionMin(StringRef Directive, SMLoc) {
int64_t Major = 0, Minor = 0, Update = 0;
int Kind = StringSwitch<int>(Directive)
.Case(".ios_version_min", MCVM_IOSVersionMin)
.Case(".macosx_version_min", MCVM_OSXVersionMin);
// Get the major version number.
if (getLexer().isNot(AsmToken::Integer))
return TokError("invalid OS major version number");
Major = getLexer().getTok().getIntVal();
if (Major > 65535 || Major <= 0)
return TokError("invalid OS major version number");
Lex();
if (getLexer().isNot(AsmToken::Comma))
return TokError("minor OS version number required, comma expected");
Lex();
// Get the minor version number.
if (getLexer().isNot(AsmToken::Integer))
return TokError("invalid OS minor version number");
Minor = getLexer().getTok().getIntVal();
if (Minor > 255 || Minor < 0)
return TokError("invalid OS minor version number");
Lex();
// Get the update level, if specified
if (getLexer().isNot(AsmToken::EndOfStatement)) {
if (getLexer().isNot(AsmToken::Comma))
return TokError("invalid update specifier, comma expected");
Lex();
if (getLexer().isNot(AsmToken::Integer))
return TokError("invalid OS update number");
Update = getLexer().getTok().getIntVal();
if (Update > 255 || Update < 0)
return TokError("invalid OS update number");
Lex();
}
// We've parsed a correct version specifier, so send it to the streamer.
getStreamer().EmitVersionMin((MCVersionMinType)Kind, Major, Minor, Update);
return false;
}
namespace llvm {
MCAsmParserExtension *createDarwinAsmParser() {
return new DarwinAsmParser;
}
} // end llvm namespace
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCParser/MCTargetAsmParser.cpp | //===-- MCTargetAsmParser.cpp - Target Assembly Parser ---------------------==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCTargetAsmParser.h"
using namespace llvm;
MCTargetAsmParser::MCTargetAsmParser()
: AvailableFeatures(0), ParsingInlineAsm(false)
{
}
MCTargetAsmParser::~MCTargetAsmParser() {
}
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCParser/COFFAsmParser.cpp | //===- COFFAsmParser.cpp - COFF Assembly Parser ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCParser/MCAsmParserExtension.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Twine.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCParser/MCAsmLexer.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSectionCOFF.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCTargetAsmParser.h"
#include "llvm/Support/COFF.h"
using namespace llvm;
namespace {
class COFFAsmParser : public MCAsmParserExtension {
template<bool (COFFAsmParser::*HandlerMethod)(StringRef, SMLoc)>
void addDirectiveHandler(StringRef Directive) {
MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair(
this, HandleDirective<COFFAsmParser, HandlerMethod>);
getParser().addDirectiveHandler(Directive, Handler);
}
bool ParseSectionSwitch(StringRef Section,
unsigned Characteristics,
SectionKind Kind);
bool ParseSectionSwitch(StringRef Section, unsigned Characteristics,
SectionKind Kind, StringRef COMDATSymName,
COFF::COMDATType Type);
bool ParseSectionName(StringRef &SectionName);
bool ParseSectionFlags(StringRef FlagsString, unsigned* Flags);
void Initialize(MCAsmParser &Parser) override {
// Call the base implementation.
MCAsmParserExtension::Initialize(Parser);
addDirectiveHandler<&COFFAsmParser::ParseSectionDirectiveText>(".text");
addDirectiveHandler<&COFFAsmParser::ParseSectionDirectiveData>(".data");
addDirectiveHandler<&COFFAsmParser::ParseSectionDirectiveBSS>(".bss");
addDirectiveHandler<&COFFAsmParser::ParseDirectiveSection>(".section");
addDirectiveHandler<&COFFAsmParser::ParseDirectiveDef>(".def");
addDirectiveHandler<&COFFAsmParser::ParseDirectiveScl>(".scl");
addDirectiveHandler<&COFFAsmParser::ParseDirectiveType>(".type");
addDirectiveHandler<&COFFAsmParser::ParseDirectiveEndef>(".endef");
addDirectiveHandler<&COFFAsmParser::ParseDirectiveSecRel32>(".secrel32");
addDirectiveHandler<&COFFAsmParser::ParseDirectiveSecIdx>(".secidx");
addDirectiveHandler<&COFFAsmParser::ParseDirectiveSafeSEH>(".safeseh");
addDirectiveHandler<&COFFAsmParser::ParseDirectiveLinkOnce>(".linkonce");
// Win64 EH directives.
addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveStartProc>(
".seh_proc");
addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveEndProc>(
".seh_endproc");
addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveStartChained>(
".seh_startchained");
addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveEndChained>(
".seh_endchained");
addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveHandler>(
".seh_handler");
addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveHandlerData>(
".seh_handlerdata");
addDirectiveHandler<&COFFAsmParser::ParseSEHDirectivePushReg>(
".seh_pushreg");
addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveSetFrame>(
".seh_setframe");
addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveAllocStack>(
".seh_stackalloc");
addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveSaveReg>(
".seh_savereg");
addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveSaveXMM>(
".seh_savexmm");
addDirectiveHandler<&COFFAsmParser::ParseSEHDirectivePushFrame>(
".seh_pushframe");
addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveEndProlog>(
".seh_endprologue");
addDirectiveHandler<&COFFAsmParser::ParseDirectiveSymbolAttribute>(".weak");
}
bool ParseSectionDirectiveText(StringRef, SMLoc) {
return ParseSectionSwitch(".text",
COFF::IMAGE_SCN_CNT_CODE
| COFF::IMAGE_SCN_MEM_EXECUTE
| COFF::IMAGE_SCN_MEM_READ,
SectionKind::getText());
}
bool ParseSectionDirectiveData(StringRef, SMLoc) {
return ParseSectionSwitch(".data",
COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
| COFF::IMAGE_SCN_MEM_READ
| COFF::IMAGE_SCN_MEM_WRITE,
SectionKind::getDataRel());
}
bool ParseSectionDirectiveBSS(StringRef, SMLoc) {
return ParseSectionSwitch(".bss",
COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA
| COFF::IMAGE_SCN_MEM_READ
| COFF::IMAGE_SCN_MEM_WRITE,
SectionKind::getBSS());
}
bool ParseDirectiveSection(StringRef, SMLoc);
bool ParseDirectiveDef(StringRef, SMLoc);
bool ParseDirectiveScl(StringRef, SMLoc);
bool ParseDirectiveType(StringRef, SMLoc);
bool ParseDirectiveEndef(StringRef, SMLoc);
bool ParseDirectiveSecRel32(StringRef, SMLoc);
bool ParseDirectiveSecIdx(StringRef, SMLoc);
bool ParseDirectiveSafeSEH(StringRef, SMLoc);
bool parseCOMDATType(COFF::COMDATType &Type);
bool ParseDirectiveLinkOnce(StringRef, SMLoc);
// Win64 EH directives.
bool ParseSEHDirectiveStartProc(StringRef, SMLoc);
bool ParseSEHDirectiveEndProc(StringRef, SMLoc);
bool ParseSEHDirectiveStartChained(StringRef, SMLoc);
bool ParseSEHDirectiveEndChained(StringRef, SMLoc);
bool ParseSEHDirectiveHandler(StringRef, SMLoc);
bool ParseSEHDirectiveHandlerData(StringRef, SMLoc);
bool ParseSEHDirectivePushReg(StringRef, SMLoc);
bool ParseSEHDirectiveSetFrame(StringRef, SMLoc);
bool ParseSEHDirectiveAllocStack(StringRef, SMLoc);
bool ParseSEHDirectiveSaveReg(StringRef, SMLoc);
bool ParseSEHDirectiveSaveXMM(StringRef, SMLoc);
bool ParseSEHDirectivePushFrame(StringRef, SMLoc);
bool ParseSEHDirectiveEndProlog(StringRef, SMLoc);
bool ParseAtUnwindOrAtExcept(bool &unwind, bool &except);
bool ParseSEHRegisterNumber(unsigned &RegNo);
bool ParseDirectiveSymbolAttribute(StringRef Directive, SMLoc);
public:
COFFAsmParser() {}
};
} // end annonomous namespace.
static SectionKind computeSectionKind(unsigned Flags) {
if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
return SectionKind::getText();
if (Flags & COFF::IMAGE_SCN_MEM_READ &&
(Flags & COFF::IMAGE_SCN_MEM_WRITE) == 0)
return SectionKind::getReadOnly();
return SectionKind::getDataRel();
}
bool COFFAsmParser::ParseSectionFlags(StringRef FlagsString, unsigned* Flags) {
enum {
None = 0,
Alloc = 1 << 0,
Code = 1 << 1,
Load = 1 << 2,
InitData = 1 << 3,
Shared = 1 << 4,
NoLoad = 1 << 5,
NoRead = 1 << 6,
NoWrite = 1 << 7
};
bool ReadOnlyRemoved = false;
unsigned SecFlags = None;
for (char FlagChar : FlagsString) {
switch (FlagChar) {
case 'a':
// Ignored.
break;
case 'b': // bss section
SecFlags |= Alloc;
if (SecFlags & InitData)
return TokError("conflicting section flags 'b' and 'd'.");
SecFlags &= ~Load;
break;
case 'd': // data section
SecFlags |= InitData;
if (SecFlags & Alloc)
return TokError("conflicting section flags 'b' and 'd'.");
SecFlags &= ~NoWrite;
if ((SecFlags & NoLoad) == 0)
SecFlags |= Load;
break;
case 'n': // section is not loaded
SecFlags |= NoLoad;
SecFlags &= ~Load;
break;
case 'r': // read-only
ReadOnlyRemoved = false;
SecFlags |= NoWrite;
if ((SecFlags & Code) == 0)
SecFlags |= InitData;
if ((SecFlags & NoLoad) == 0)
SecFlags |= Load;
break;
case 's': // shared section
SecFlags |= Shared | InitData;
SecFlags &= ~NoWrite;
if ((SecFlags & NoLoad) == 0)
SecFlags |= Load;
break;
case 'w': // writable
SecFlags &= ~NoWrite;
ReadOnlyRemoved = true;
break;
case 'x': // executable section
SecFlags |= Code;
if ((SecFlags & NoLoad) == 0)
SecFlags |= Load;
if (!ReadOnlyRemoved)
SecFlags |= NoWrite;
break;
case 'y': // not readable
SecFlags |= NoRead | NoWrite;
break;
default:
return TokError("unknown flag");
}
}
*Flags = 0;
if (SecFlags == None)
SecFlags = InitData;
if (SecFlags & Code)
*Flags |= COFF::IMAGE_SCN_CNT_CODE | COFF::IMAGE_SCN_MEM_EXECUTE;
if (SecFlags & InitData)
*Flags |= COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
if ((SecFlags & Alloc) && (SecFlags & Load) == 0)
*Flags |= COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
if (SecFlags & NoLoad)
*Flags |= COFF::IMAGE_SCN_LNK_REMOVE;
if ((SecFlags & NoRead) == 0)
*Flags |= COFF::IMAGE_SCN_MEM_READ;
if ((SecFlags & NoWrite) == 0)
*Flags |= COFF::IMAGE_SCN_MEM_WRITE;
if (SecFlags & Shared)
*Flags |= COFF::IMAGE_SCN_MEM_SHARED;
return false;
}
/// ParseDirectiveSymbolAttribute
/// ::= { ".weak", ... } [ identifier ( , identifier )* ]
bool COFFAsmParser::ParseDirectiveSymbolAttribute(StringRef Directive, SMLoc) {
MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Directive)
.Case(".weak", MCSA_Weak)
.Default(MCSA_Invalid);
assert(Attr != MCSA_Invalid && "unexpected symbol attribute directive!");
if (getLexer().isNot(AsmToken::EndOfStatement)) {
for (;;) {
StringRef Name;
if (getParser().parseIdentifier(Name))
return TokError("expected identifier in directive");
MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
getStreamer().EmitSymbolAttribute(Sym, Attr);
if (getLexer().is(AsmToken::EndOfStatement))
break;
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
}
}
Lex();
return false;
}
bool COFFAsmParser::ParseSectionSwitch(StringRef Section,
unsigned Characteristics,
SectionKind Kind) {
return ParseSectionSwitch(Section, Characteristics, Kind, "", (COFF::COMDATType)0);
}
bool COFFAsmParser::ParseSectionSwitch(StringRef Section,
unsigned Characteristics,
SectionKind Kind,
StringRef COMDATSymName,
COFF::COMDATType Type) {
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in section switching directive");
Lex();
getStreamer().SwitchSection(getContext().getCOFFSection(
Section, Characteristics, Kind, COMDATSymName, Type));
return false;
}
bool COFFAsmParser::ParseSectionName(StringRef &SectionName) {
if (!getLexer().is(AsmToken::Identifier))
return true;
SectionName = getTok().getIdentifier();
Lex();
return false;
}
// .section name [, "flags"] [, identifier [ identifier ], identifier]
//
// Supported flags:
// a: Ignored.
// b: BSS section (uninitialized data)
// d: data section (initialized data)
// n: Discardable section
// r: Readable section
// s: Shared section
// w: Writable section
// x: Executable section
// y: Not-readable section (clears 'r')
//
// Subsections are not supported.
bool COFFAsmParser::ParseDirectiveSection(StringRef, SMLoc) {
StringRef SectionName;
if (ParseSectionName(SectionName))
return TokError("expected identifier in directive");
unsigned Flags = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
COFF::IMAGE_SCN_MEM_READ |
COFF::IMAGE_SCN_MEM_WRITE;
if (getLexer().is(AsmToken::Comma)) {
Lex();
if (getLexer().isNot(AsmToken::String))
return TokError("expected string in directive");
StringRef FlagsStr = getTok().getStringContents();
Lex();
if (ParseSectionFlags(FlagsStr, &Flags))
return true;
}
COFF::COMDATType Type = (COFF::COMDATType)0;
StringRef COMDATSymName;
if (getLexer().is(AsmToken::Comma)) {
Type = COFF::IMAGE_COMDAT_SELECT_ANY;
Lex();
Flags |= COFF::IMAGE_SCN_LNK_COMDAT;
if (!getLexer().is(AsmToken::Identifier))
return TokError("expected comdat type such as 'discard' or 'largest' "
"after protection bits");
if (parseCOMDATType(Type))
return true;
if (getLexer().isNot(AsmToken::Comma))
return TokError("expected comma in directive");
Lex();
if (getParser().parseIdentifier(COMDATSymName))
return TokError("expected identifier in directive");
}
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
SectionKind Kind = computeSectionKind(Flags);
if (Kind.isText()) {
const Triple &T = getContext().getObjectFileInfo()->getTargetTriple();
if (T.getArch() == Triple::arm || T.getArch() == Triple::thumb)
Flags |= COFF::IMAGE_SCN_MEM_16BIT;
}
ParseSectionSwitch(SectionName, Flags, Kind, COMDATSymName, Type);
return false;
}
bool COFFAsmParser::ParseDirectiveDef(StringRef, SMLoc) {
StringRef SymbolName;
if (getParser().parseIdentifier(SymbolName))
return TokError("expected identifier in directive");
MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
getStreamer().BeginCOFFSymbolDef(Sym);
Lex();
return false;
}
bool COFFAsmParser::ParseDirectiveScl(StringRef, SMLoc) {
int64_t SymbolStorageClass;
if (getParser().parseAbsoluteExpression(SymbolStorageClass))
return true;
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
Lex();
getStreamer().EmitCOFFSymbolStorageClass(SymbolStorageClass);
return false;
}
bool COFFAsmParser::ParseDirectiveType(StringRef, SMLoc) {
int64_t Type;
if (getParser().parseAbsoluteExpression(Type))
return true;
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
Lex();
getStreamer().EmitCOFFSymbolType(Type);
return false;
}
bool COFFAsmParser::ParseDirectiveEndef(StringRef, SMLoc) {
Lex();
getStreamer().EndCOFFSymbolDef();
return false;
}
bool COFFAsmParser::ParseDirectiveSecRel32(StringRef, SMLoc) {
StringRef SymbolID;
if (getParser().parseIdentifier(SymbolID))
return TokError("expected identifier in directive");
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
MCSymbol *Symbol = getContext().getOrCreateSymbol(SymbolID);
Lex();
getStreamer().EmitCOFFSecRel32(Symbol);
return false;
}
bool COFFAsmParser::ParseDirectiveSafeSEH(StringRef, SMLoc) {
StringRef SymbolID;
if (getParser().parseIdentifier(SymbolID))
return TokError("expected identifier in directive");
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
MCSymbol *Symbol = getContext().getOrCreateSymbol(SymbolID);
Lex();
getStreamer().EmitCOFFSafeSEH(Symbol);
return false;
}
bool COFFAsmParser::ParseDirectiveSecIdx(StringRef, SMLoc) {
StringRef SymbolID;
if (getParser().parseIdentifier(SymbolID))
return TokError("expected identifier in directive");
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
MCSymbol *Symbol = getContext().getOrCreateSymbol(SymbolID);
Lex();
getStreamer().EmitCOFFSectionIndex(Symbol);
return false;
}
/// ::= [ identifier ]
bool COFFAsmParser::parseCOMDATType(COFF::COMDATType &Type) {
StringRef TypeId = getTok().getIdentifier();
Type = StringSwitch<COFF::COMDATType>(TypeId)
.Case("one_only", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES)
.Case("discard", COFF::IMAGE_COMDAT_SELECT_ANY)
.Case("same_size", COFF::IMAGE_COMDAT_SELECT_SAME_SIZE)
.Case("same_contents", COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH)
.Case("associative", COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
.Case("largest", COFF::IMAGE_COMDAT_SELECT_LARGEST)
.Case("newest", COFF::IMAGE_COMDAT_SELECT_NEWEST)
.Default((COFF::COMDATType)0);
if (Type == 0)
return TokError(Twine("unrecognized COMDAT type '" + TypeId + "'"));
Lex();
return false;
}
/// ParseDirectiveLinkOnce
/// ::= .linkonce [ identifier ]
bool COFFAsmParser::ParseDirectiveLinkOnce(StringRef, SMLoc Loc) {
COFF::COMDATType Type = COFF::IMAGE_COMDAT_SELECT_ANY;
if (getLexer().is(AsmToken::Identifier))
if (parseCOMDATType(Type))
return true;
const MCSectionCOFF *Current = static_cast<const MCSectionCOFF*>(
getStreamer().getCurrentSection().first);
if (Type == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
return Error(Loc, "cannot make section associative with .linkonce");
if (Current->getCharacteristics() & COFF::IMAGE_SCN_LNK_COMDAT)
return Error(Loc, Twine("section '") + Current->getSectionName() +
"' is already linkonce");
Current->setSelection(Type);
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
return false;
}
bool COFFAsmParser::ParseSEHDirectiveStartProc(StringRef, SMLoc) {
StringRef SymbolID;
if (getParser().parseIdentifier(SymbolID))
return true;
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
MCSymbol *Symbol = getContext().getOrCreateSymbol(SymbolID);
Lex();
getStreamer().EmitWinCFIStartProc(Symbol);
return false;
}
bool COFFAsmParser::ParseSEHDirectiveEndProc(StringRef, SMLoc) {
Lex();
getStreamer().EmitWinCFIEndProc();
return false;
}
bool COFFAsmParser::ParseSEHDirectiveStartChained(StringRef, SMLoc) {
Lex();
getStreamer().EmitWinCFIStartChained();
return false;
}
bool COFFAsmParser::ParseSEHDirectiveEndChained(StringRef, SMLoc) {
Lex();
getStreamer().EmitWinCFIEndChained();
return false;
}
bool COFFAsmParser::ParseSEHDirectiveHandler(StringRef, SMLoc) {
StringRef SymbolID;
if (getParser().parseIdentifier(SymbolID))
return true;
if (getLexer().isNot(AsmToken::Comma))
return TokError("you must specify one or both of @unwind or @except");
Lex();
bool unwind = false, except = false;
if (ParseAtUnwindOrAtExcept(unwind, except))
return true;
if (getLexer().is(AsmToken::Comma)) {
Lex();
if (ParseAtUnwindOrAtExcept(unwind, except))
return true;
}
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
MCSymbol *handler = getContext().getOrCreateSymbol(SymbolID);
Lex();
getStreamer().EmitWinEHHandler(handler, unwind, except);
return false;
}
bool COFFAsmParser::ParseSEHDirectiveHandlerData(StringRef, SMLoc) {
Lex();
getStreamer().EmitWinEHHandlerData();
return false;
}
bool COFFAsmParser::ParseSEHDirectivePushReg(StringRef, SMLoc L) {
unsigned Reg = 0;
if (ParseSEHRegisterNumber(Reg))
return true;
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
Lex();
getStreamer().EmitWinCFIPushReg(Reg);
return false;
}
bool COFFAsmParser::ParseSEHDirectiveSetFrame(StringRef, SMLoc L) {
unsigned Reg = 0;
int64_t Off;
if (ParseSEHRegisterNumber(Reg))
return true;
if (getLexer().isNot(AsmToken::Comma))
return TokError("you must specify a stack pointer offset");
Lex();
SMLoc startLoc = getLexer().getLoc();
if (getParser().parseAbsoluteExpression(Off))
return true;
if (Off & 0x0F)
return Error(startLoc, "offset is not a multiple of 16");
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
Lex();
getStreamer().EmitWinCFISetFrame(Reg, Off);
return false;
}
bool COFFAsmParser::ParseSEHDirectiveAllocStack(StringRef, SMLoc) {
int64_t Size;
SMLoc startLoc = getLexer().getLoc();
if (getParser().parseAbsoluteExpression(Size))
return true;
if (Size & 7)
return Error(startLoc, "size is not a multiple of 8");
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
Lex();
getStreamer().EmitWinCFIAllocStack(Size);
return false;
}
bool COFFAsmParser::ParseSEHDirectiveSaveReg(StringRef, SMLoc L) {
unsigned Reg = 0;
int64_t Off;
if (ParseSEHRegisterNumber(Reg))
return true;
if (getLexer().isNot(AsmToken::Comma))
return TokError("you must specify an offset on the stack");
Lex();
SMLoc startLoc = getLexer().getLoc();
if (getParser().parseAbsoluteExpression(Off))
return true;
if (Off & 7)
return Error(startLoc, "size is not a multiple of 8");
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
Lex();
// FIXME: Err on %xmm* registers
getStreamer().EmitWinCFISaveReg(Reg, Off);
return false;
}
// FIXME: This method is inherently x86-specific. It should really be in the
// x86 backend.
bool COFFAsmParser::ParseSEHDirectiveSaveXMM(StringRef, SMLoc L) {
unsigned Reg = 0;
int64_t Off;
if (ParseSEHRegisterNumber(Reg))
return true;
if (getLexer().isNot(AsmToken::Comma))
return TokError("you must specify an offset on the stack");
Lex();
SMLoc startLoc = getLexer().getLoc();
if (getParser().parseAbsoluteExpression(Off))
return true;
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
if (Off & 0x0F)
return Error(startLoc, "offset is not a multiple of 16");
Lex();
// FIXME: Err on non-%xmm* registers
getStreamer().EmitWinCFISaveXMM(Reg, Off);
return false;
}
bool COFFAsmParser::ParseSEHDirectivePushFrame(StringRef, SMLoc) {
bool Code = false;
StringRef CodeID;
if (getLexer().is(AsmToken::At)) {
SMLoc startLoc = getLexer().getLoc();
Lex();
if (!getParser().parseIdentifier(CodeID)) {
if (CodeID != "code")
return Error(startLoc, "expected @code");
Code = true;
}
}
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
Lex();
getStreamer().EmitWinCFIPushFrame(Code);
return false;
}
bool COFFAsmParser::ParseSEHDirectiveEndProlog(StringRef, SMLoc) {
Lex();
getStreamer().EmitWinCFIEndProlog();
return false;
}
bool COFFAsmParser::ParseAtUnwindOrAtExcept(bool &unwind, bool &except) {
StringRef identifier;
if (getLexer().isNot(AsmToken::At))
return TokError("a handler attribute must begin with '@'");
SMLoc startLoc = getLexer().getLoc();
Lex();
if (getParser().parseIdentifier(identifier))
return Error(startLoc, "expected @unwind or @except");
if (identifier == "unwind")
unwind = true;
else if (identifier == "except")
except = true;
else
return Error(startLoc, "expected @unwind or @except");
return false;
}
bool COFFAsmParser::ParseSEHRegisterNumber(unsigned &RegNo) {
SMLoc startLoc = getLexer().getLoc();
if (getLexer().is(AsmToken::Percent)) {
const MCRegisterInfo *MRI = getContext().getRegisterInfo();
SMLoc endLoc;
unsigned LLVMRegNo;
if (getParser().getTargetParser().ParseRegister(LLVMRegNo,startLoc,endLoc))
return true;
#if 0
// FIXME: TargetAsmInfo::getCalleeSavedRegs() commits a serious layering
// violation so this validation code is disabled.
// Check that this is a non-volatile register.
const unsigned *NVRegs = TAI.getCalleeSavedRegs();
unsigned i;
for (i = 0; NVRegs[i] != 0; ++i)
if (NVRegs[i] == LLVMRegNo)
break;
if (NVRegs[i] == 0)
return Error(startLoc, "expected non-volatile register");
#endif
int SEHRegNo = MRI->getSEHRegNum(LLVMRegNo);
if (SEHRegNo < 0)
return Error(startLoc,"register can't be represented in SEH unwind info");
RegNo = SEHRegNo;
}
else {
int64_t n;
if (getParser().parseAbsoluteExpression(n))
return true;
if (n > 15)
return Error(startLoc, "register number is too high");
RegNo = n;
}
return false;
}
namespace llvm {
MCAsmParserExtension *createCOFFAsmParser() {
return new COFFAsmParser;
}
}
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCParser/AsmLexer.cpp | //===- AsmLexer.cpp - Lexer for Assembly Files ----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class implements the lexer for assembly files.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCParser/AsmLexer.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SMLoc.h"
#include <cctype>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
using namespace llvm;
AsmLexer::AsmLexer(const MCAsmInfo &MAI) : MAI(MAI) {
CurPtr = nullptr;
isAtStartOfLine = true;
AllowAtInIdentifier = !StringRef(MAI.getCommentString()).startswith("@");
}
AsmLexer::~AsmLexer() {
}
void AsmLexer::setBuffer(StringRef Buf, const char *ptr) {
CurBuf = Buf;
if (ptr)
CurPtr = ptr;
else
CurPtr = CurBuf.begin();
TokStart = nullptr;
}
/// ReturnError - Set the error to the specified string at the specified
/// location. This is defined to always return AsmToken::Error.
AsmToken AsmLexer::ReturnError(const char *Loc, const std::string &Msg) {
SetError(SMLoc::getFromPointer(Loc), Msg);
return AsmToken(AsmToken::Error, StringRef(Loc, 0));
}
int AsmLexer::getNextChar() {
char CurChar = *CurPtr++;
switch (CurChar) {
default:
return (unsigned char)CurChar;
case 0:
// A nul character in the stream is either the end of the current buffer or
// a random nul in the file. Disambiguate that here.
if (CurPtr - 1 != CurBuf.end())
return 0; // Just whitespace.
// Otherwise, return end of file.
--CurPtr; // Another call to lex will return EOF again.
return EOF;
}
}
/// LexFloatLiteral: [0-9]*[.][0-9]*([eE][+-]?[0-9]*)?
///
/// The leading integral digit sequence and dot should have already been
/// consumed, some or all of the fractional digit sequence *can* have been
/// consumed.
AsmToken AsmLexer::LexFloatLiteral() {
// Skip the fractional digit sequence.
while (isdigit(*CurPtr))
++CurPtr;
// Check for exponent; we intentionally accept a slighlty wider set of
// literals here and rely on the upstream client to reject invalid ones (e.g.,
// "1e+").
if (*CurPtr == 'e' || *CurPtr == 'E') {
++CurPtr;
if (*CurPtr == '-' || *CurPtr == '+')
++CurPtr;
while (isdigit(*CurPtr))
++CurPtr;
}
return AsmToken(AsmToken::Real,
StringRef(TokStart, CurPtr - TokStart));
}
/// LexHexFloatLiteral matches essentially (.[0-9a-fA-F]*)?[pP][+-]?[0-9a-fA-F]+
/// while making sure there are enough actual digits around for the constant to
/// be valid.
///
/// The leading "0x[0-9a-fA-F]*" (i.e. integer part) has already been consumed
/// before we get here.
AsmToken AsmLexer::LexHexFloatLiteral(bool NoIntDigits) {
assert((*CurPtr == 'p' || *CurPtr == 'P' || *CurPtr == '.') &&
"unexpected parse state in floating hex");
bool NoFracDigits = true;
// Skip the fractional part if there is one
if (*CurPtr == '.') {
++CurPtr;
const char *FracStart = CurPtr;
while (isxdigit(*CurPtr))
++CurPtr;
NoFracDigits = CurPtr == FracStart;
}
if (NoIntDigits && NoFracDigits)
return ReturnError(TokStart, "invalid hexadecimal floating-point constant: "
"expected at least one significand digit");
// Make sure we do have some kind of proper exponent part
if (*CurPtr != 'p' && *CurPtr != 'P')
return ReturnError(TokStart, "invalid hexadecimal floating-point constant: "
"expected exponent part 'p'");
++CurPtr;
if (*CurPtr == '+' || *CurPtr == '-')
++CurPtr;
// N.b. exponent digits are *not* hex
const char *ExpStart = CurPtr;
while (isdigit(*CurPtr))
++CurPtr;
if (CurPtr == ExpStart)
return ReturnError(TokStart, "invalid hexadecimal floating-point constant: "
"expected at least one exponent digit");
return AsmToken(AsmToken::Real, StringRef(TokStart, CurPtr - TokStart));
}
/// LexIdentifier: [a-zA-Z_.][a-zA-Z0-9_$.@?]*
static bool IsIdentifierChar(char c, bool AllowAt) {
return isalnum(c) || c == '_' || c == '$' || c == '.' ||
(c == '@' && AllowAt) || c == '?';
}
AsmToken AsmLexer::LexIdentifier() {
// Check for floating point literals.
if (CurPtr[-1] == '.' && isdigit(*CurPtr)) {
// Disambiguate a .1243foo identifier from a floating literal.
while (isdigit(*CurPtr))
++CurPtr;
if (*CurPtr == 'e' || *CurPtr == 'E' ||
!IsIdentifierChar(*CurPtr, AllowAtInIdentifier))
return LexFloatLiteral();
}
while (IsIdentifierChar(*CurPtr, AllowAtInIdentifier))
++CurPtr;
// Handle . as a special case.
if (CurPtr == TokStart+1 && TokStart[0] == '.')
return AsmToken(AsmToken::Dot, StringRef(TokStart, 1));
return AsmToken(AsmToken::Identifier, StringRef(TokStart, CurPtr - TokStart));
}
/// LexSlash: Slash: /
/// C-Style Comment: /* ... */
AsmToken AsmLexer::LexSlash() {
switch (*CurPtr) {
case '*': break; // C style comment.
case '/': return ++CurPtr, LexLineComment();
default: return AsmToken(AsmToken::Slash, StringRef(CurPtr-1, 1));
}
// C Style comment.
++CurPtr; // skip the star.
while (1) {
int CurChar = getNextChar();
switch (CurChar) {
case EOF:
return ReturnError(TokStart, "unterminated comment");
case '*':
// End of the comment?
if (CurPtr[0] != '/') break;
++CurPtr; // End the */.
return LexToken();
}
}
}
/// LexLineComment: Comment: #[^\n]*
/// : //[^\n]*
AsmToken AsmLexer::LexLineComment() {
// FIXME: This is broken if we happen to a comment at the end of a file, which
// was .included, and which doesn't end with a newline.
int CurChar = getNextChar();
while (CurChar != '\n' && CurChar != '\r' && CurChar != EOF)
CurChar = getNextChar();
if (CurChar == EOF)
return AsmToken(AsmToken::Eof, StringRef(TokStart, 0));
return AsmToken(AsmToken::EndOfStatement, StringRef(TokStart, 0));
}
static void SkipIgnoredIntegerSuffix(const char *&CurPtr) {
// Skip ULL, UL, U, L and LL suffices.
if (CurPtr[0] == 'U')
++CurPtr;
if (CurPtr[0] == 'L')
++CurPtr;
if (CurPtr[0] == 'L')
++CurPtr;
}
// Look ahead to search for first non-hex digit, if it's [hH], then we treat the
// integer as a hexadecimal, possibly with leading zeroes.
static unsigned doLookAhead(const char *&CurPtr, unsigned DefaultRadix) {
const char *FirstHex = nullptr;
const char *LookAhead = CurPtr;
while (1) {
if (isdigit(*LookAhead)) {
++LookAhead;
} else if (isxdigit(*LookAhead)) {
if (!FirstHex)
FirstHex = LookAhead;
++LookAhead;
} else {
break;
}
}
bool isHex = *LookAhead == 'h' || *LookAhead == 'H';
CurPtr = isHex || !FirstHex ? LookAhead : FirstHex;
if (isHex)
return 16;
return DefaultRadix;
}
static AsmToken intToken(StringRef Ref, APInt &Value)
{
if (Value.isIntN(64))
return AsmToken(AsmToken::Integer, Ref, Value);
return AsmToken(AsmToken::BigNum, Ref, Value);
}
/// LexDigit: First character is [0-9].
/// Local Label: [0-9][:]
/// Forward/Backward Label: [0-9][fb]
/// Binary integer: 0b[01]+
/// Octal integer: 0[0-7]+
/// Hex integer: 0x[0-9a-fA-F]+ or [0x]?[0-9][0-9a-fA-F]*[hH]
/// Decimal integer: [1-9][0-9]*
AsmToken AsmLexer::LexDigit() {
// Decimal integer: [1-9][0-9]*
if (CurPtr[-1] != '0' || CurPtr[0] == '.') {
unsigned Radix = doLookAhead(CurPtr, 10);
bool isHex = Radix == 16;
// Check for floating point literals.
if (!isHex && (*CurPtr == '.' || *CurPtr == 'e')) {
++CurPtr;
return LexFloatLiteral();
}
StringRef Result(TokStart, CurPtr - TokStart);
APInt Value(128, 0, true);
if (Result.getAsInteger(Radix, Value))
return ReturnError(TokStart, !isHex ? "invalid decimal number" :
"invalid hexdecimal number");
// Consume the [bB][hH].
if (Radix == 2 || Radix == 16)
++CurPtr;
// The darwin/x86 (and x86-64) assembler accepts and ignores type
// suffices on integer literals.
SkipIgnoredIntegerSuffix(CurPtr);
return intToken(Result, Value);
}
if (*CurPtr == 'b') {
++CurPtr;
// See if we actually have "0b" as part of something like "jmp 0b\n"
if (!isdigit(CurPtr[0])) {
--CurPtr;
StringRef Result(TokStart, CurPtr - TokStart);
return AsmToken(AsmToken::Integer, Result, 0);
}
const char *NumStart = CurPtr;
while (CurPtr[0] == '0' || CurPtr[0] == '1')
++CurPtr;
// Requires at least one binary digit.
if (CurPtr == NumStart)
return ReturnError(TokStart, "invalid binary number");
StringRef Result(TokStart, CurPtr - TokStart);
APInt Value(128, 0, true);
if (Result.substr(2).getAsInteger(2, Value))
return ReturnError(TokStart, "invalid binary number");
// The darwin/x86 (and x86-64) assembler accepts and ignores ULL and LL
// suffixes on integer literals.
SkipIgnoredIntegerSuffix(CurPtr);
return intToken(Result, Value);
}
if (*CurPtr == 'x') {
++CurPtr;
const char *NumStart = CurPtr;
while (isxdigit(CurPtr[0]))
++CurPtr;
// "0x.0p0" is valid, and "0x0p0" (but not "0xp0" for example, which will be
// diagnosed by LexHexFloatLiteral).
if (CurPtr[0] == '.' || CurPtr[0] == 'p' || CurPtr[0] == 'P')
return LexHexFloatLiteral(NumStart == CurPtr);
// Otherwise requires at least one hex digit.
if (CurPtr == NumStart)
return ReturnError(CurPtr-2, "invalid hexadecimal number");
APInt Result(128, 0);
if (StringRef(TokStart, CurPtr - TokStart).getAsInteger(0, Result))
return ReturnError(TokStart, "invalid hexadecimal number");
// Consume the optional [hH].
if (*CurPtr == 'h' || *CurPtr == 'H')
++CurPtr;
// The darwin/x86 (and x86-64) assembler accepts and ignores ULL and LL
// suffixes on integer literals.
SkipIgnoredIntegerSuffix(CurPtr);
return intToken(StringRef(TokStart, CurPtr - TokStart), Result);
}
// Either octal or hexadecimal.
APInt Value(128, 0, true);
unsigned Radix = doLookAhead(CurPtr, 8);
bool isHex = Radix == 16;
StringRef Result(TokStart, CurPtr - TokStart);
if (Result.getAsInteger(Radix, Value))
return ReturnError(TokStart, !isHex ? "invalid octal number" :
"invalid hexdecimal number");
// Consume the [hH].
if (Radix == 16)
++CurPtr;
// The darwin/x86 (and x86-64) assembler accepts and ignores ULL and LL
// suffixes on integer literals.
SkipIgnoredIntegerSuffix(CurPtr);
return intToken(Result, Value);
}
/// LexSingleQuote: Integer: 'b'
AsmToken AsmLexer::LexSingleQuote() {
int CurChar = getNextChar();
if (CurChar == '\\')
CurChar = getNextChar();
if (CurChar == EOF)
return ReturnError(TokStart, "unterminated single quote");
CurChar = getNextChar();
if (CurChar != '\'')
return ReturnError(TokStart, "single quote way too long");
// The idea here being that 'c' is basically just an integral
// constant.
StringRef Res = StringRef(TokStart,CurPtr - TokStart);
long long Value;
if (Res.startswith("\'\\")) {
char theChar = Res[2];
switch (theChar) {
default: Value = theChar; break;
case '\'': Value = '\''; break;
case 't': Value = '\t'; break;
case 'n': Value = '\n'; break;
case 'b': Value = '\b'; break;
}
} else
Value = TokStart[1];
return AsmToken(AsmToken::Integer, Res, Value);
}
/// LexQuote: String: "..."
AsmToken AsmLexer::LexQuote() {
int CurChar = getNextChar();
// TODO: does gas allow multiline string constants?
while (CurChar != '"') {
if (CurChar == '\\') {
// Allow \", etc.
CurChar = getNextChar();
}
if (CurChar == EOF)
return ReturnError(TokStart, "unterminated string constant");
CurChar = getNextChar();
}
return AsmToken(AsmToken::String, StringRef(TokStart, CurPtr - TokStart));
}
StringRef AsmLexer::LexUntilEndOfStatement() {
TokStart = CurPtr;
while (!isAtStartOfComment(CurPtr) && // Start of line comment.
!isAtStatementSeparator(CurPtr) && // End of statement marker.
*CurPtr != '\n' && *CurPtr != '\r' &&
(*CurPtr != 0 || CurPtr != CurBuf.end())) {
++CurPtr;
}
return StringRef(TokStart, CurPtr-TokStart);
}
StringRef AsmLexer::LexUntilEndOfLine() {
TokStart = CurPtr;
while (*CurPtr != '\n' && *CurPtr != '\r' &&
(*CurPtr != 0 || CurPtr != CurBuf.end())) {
++CurPtr;
}
return StringRef(TokStart, CurPtr-TokStart);
}
const AsmToken AsmLexer::peekTok(bool ShouldSkipSpace) {
const char *SavedTokStart = TokStart;
const char *SavedCurPtr = CurPtr;
bool SavedAtStartOfLine = isAtStartOfLine;
bool SavedSkipSpace = SkipSpace;
std::string SavedErr = getErr();
SMLoc SavedErrLoc = getErrLoc();
SkipSpace = ShouldSkipSpace;
AsmToken Token = LexToken();
SetError(SavedErrLoc, SavedErr);
SkipSpace = SavedSkipSpace;
isAtStartOfLine = SavedAtStartOfLine;
CurPtr = SavedCurPtr;
TokStart = SavedTokStart;
return Token;
}
bool AsmLexer::isAtStartOfComment(const char *Ptr) {
const char *CommentString = MAI.getCommentString();
if (CommentString[1] == '\0')
return CommentString[0] == Ptr[0];
// FIXME: special case for the bogus "##" comment string in X86MCAsmInfoDarwin
if (CommentString[1] == '#')
return CommentString[0] == Ptr[0];
return strncmp(Ptr, CommentString, strlen(CommentString)) == 0;
}
bool AsmLexer::isAtStatementSeparator(const char *Ptr) {
return strncmp(Ptr, MAI.getSeparatorString(),
strlen(MAI.getSeparatorString())) == 0;
}
AsmToken AsmLexer::LexToken() {
TokStart = CurPtr;
// This always consumes at least one character.
int CurChar = getNextChar();
if (isAtStartOfComment(TokStart)) {
// If this comment starts with a '#', then return the Hash token and let
// the assembler parser see if it can be parsed as a cpp line filename
// comment. We do this only if we are at the start of a line.
if (CurChar == '#' && isAtStartOfLine)
return AsmToken(AsmToken::Hash, StringRef(TokStart, 1));
isAtStartOfLine = true;
return LexLineComment();
}
if (isAtStatementSeparator(TokStart)) {
CurPtr += strlen(MAI.getSeparatorString()) - 1;
return AsmToken(AsmToken::EndOfStatement,
StringRef(TokStart, strlen(MAI.getSeparatorString())));
}
// If we're missing a newline at EOF, make sure we still get an
// EndOfStatement token before the Eof token.
if (CurChar == EOF && !isAtStartOfLine) {
isAtStartOfLine = true;
return AsmToken(AsmToken::EndOfStatement, StringRef(TokStart, 1));
}
isAtStartOfLine = false;
switch (CurChar) {
default:
// Handle identifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*
if (isalpha(CurChar) || CurChar == '_' || CurChar == '.')
return LexIdentifier();
// Unknown character, emit an error.
return ReturnError(TokStart, "invalid character in input");
case EOF: return AsmToken(AsmToken::Eof, StringRef(TokStart, 0));
case 0:
case ' ':
case '\t':
if (SkipSpace) {
// Ignore whitespace.
return LexToken();
} else {
int len = 1;
while (*CurPtr==' ' || *CurPtr=='\t') {
CurPtr++;
len++;
}
return AsmToken(AsmToken::Space, StringRef(TokStart, len));
}
case '\n': // FALL THROUGH.
case '\r':
isAtStartOfLine = true;
return AsmToken(AsmToken::EndOfStatement, StringRef(TokStart, 1));
case ':': return AsmToken(AsmToken::Colon, StringRef(TokStart, 1));
case '+': return AsmToken(AsmToken::Plus, StringRef(TokStart, 1));
case '-': return AsmToken(AsmToken::Minus, StringRef(TokStart, 1));
case '~': return AsmToken(AsmToken::Tilde, StringRef(TokStart, 1));
case '(': return AsmToken(AsmToken::LParen, StringRef(TokStart, 1));
case ')': return AsmToken(AsmToken::RParen, StringRef(TokStart, 1));
case '[': return AsmToken(AsmToken::LBrac, StringRef(TokStart, 1));
case ']': return AsmToken(AsmToken::RBrac, StringRef(TokStart, 1));
case '{': return AsmToken(AsmToken::LCurly, StringRef(TokStart, 1));
case '}': return AsmToken(AsmToken::RCurly, StringRef(TokStart, 1));
case '*': return AsmToken(AsmToken::Star, StringRef(TokStart, 1));
case ',': return AsmToken(AsmToken::Comma, StringRef(TokStart, 1));
case '$': return AsmToken(AsmToken::Dollar, StringRef(TokStart, 1));
case '@': return AsmToken(AsmToken::At, StringRef(TokStart, 1));
case '\\': return AsmToken(AsmToken::BackSlash, StringRef(TokStart, 1));
case '=':
if (*CurPtr == '=')
return ++CurPtr, AsmToken(AsmToken::EqualEqual, StringRef(TokStart, 2));
return AsmToken(AsmToken::Equal, StringRef(TokStart, 1));
case '|':
if (*CurPtr == '|')
return ++CurPtr, AsmToken(AsmToken::PipePipe, StringRef(TokStart, 2));
return AsmToken(AsmToken::Pipe, StringRef(TokStart, 1));
case '^': return AsmToken(AsmToken::Caret, StringRef(TokStart, 1));
case '&':
if (*CurPtr == '&')
return ++CurPtr, AsmToken(AsmToken::AmpAmp, StringRef(TokStart, 2));
return AsmToken(AsmToken::Amp, StringRef(TokStart, 1));
case '!':
if (*CurPtr == '=')
return ++CurPtr, AsmToken(AsmToken::ExclaimEqual, StringRef(TokStart, 2));
return AsmToken(AsmToken::Exclaim, StringRef(TokStart, 1));
case '%': return AsmToken(AsmToken::Percent, StringRef(TokStart, 1));
case '/': return LexSlash();
case '#': return AsmToken(AsmToken::Hash, StringRef(TokStart, 1));
case '\'': return LexSingleQuote();
case '"': return LexQuote();
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
return LexDigit();
case '<':
switch (*CurPtr) {
case '<': return ++CurPtr, AsmToken(AsmToken::LessLess,
StringRef(TokStart, 2));
case '=': return ++CurPtr, AsmToken(AsmToken::LessEqual,
StringRef(TokStart, 2));
case '>': return ++CurPtr, AsmToken(AsmToken::LessGreater,
StringRef(TokStart, 2));
default: return AsmToken(AsmToken::Less, StringRef(TokStart, 1));
}
case '>':
switch (*CurPtr) {
case '>': return ++CurPtr, AsmToken(AsmToken::GreaterGreater,
StringRef(TokStart, 2));
case '=': return ++CurPtr, AsmToken(AsmToken::GreaterEqual,
StringRef(TokStart, 2));
default: return AsmToken(AsmToken::Greater, StringRef(TokStart, 1));
}
// TODO: Quoted identifiers (objc methods etc)
// local labels: [0-9][:]
// Forward/backward labels: [0-9][fb]
// Integers, fp constants, character constants.
}
}
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCParser/ELFAsmParser.cpp | //===- ELFAsmParser.cpp - ELF Assembly Parser -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCParser/MCAsmParserExtension.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Twine.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCParser/MCAsmLexer.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbolELF.h"
#include "llvm/Support/ELF.h"
using namespace llvm;
namespace {
class ELFAsmParser : public MCAsmParserExtension {
template<bool (ELFAsmParser::*HandlerMethod)(StringRef, SMLoc)>
void addDirectiveHandler(StringRef Directive) {
MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair(
this, HandleDirective<ELFAsmParser, HandlerMethod>);
getParser().addDirectiveHandler(Directive, Handler);
}
bool ParseSectionSwitch(StringRef Section, unsigned Type, unsigned Flags,
SectionKind Kind);
public:
ELFAsmParser() { BracketExpressionsSupported = true; }
void Initialize(MCAsmParser &Parser) override {
// Call the base implementation.
this->MCAsmParserExtension::Initialize(Parser);
addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveData>(".data");
addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveText>(".text");
addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveBSS>(".bss");
addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveRoData>(".rodata");
addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveTData>(".tdata");
addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveTBSS>(".tbss");
addDirectiveHandler<
&ELFAsmParser::ParseSectionDirectiveDataRel>(".data.rel");
addDirectiveHandler<
&ELFAsmParser::ParseSectionDirectiveDataRelRo>(".data.rel.ro");
addDirectiveHandler<
&ELFAsmParser::ParseSectionDirectiveDataRelRoLocal>(".data.rel.ro.local");
addDirectiveHandler<
&ELFAsmParser::ParseSectionDirectiveEhFrame>(".eh_frame");
addDirectiveHandler<&ELFAsmParser::ParseDirectiveSection>(".section");
addDirectiveHandler<
&ELFAsmParser::ParseDirectivePushSection>(".pushsection");
addDirectiveHandler<&ELFAsmParser::ParseDirectivePopSection>(".popsection");
addDirectiveHandler<&ELFAsmParser::ParseDirectiveSize>(".size");
addDirectiveHandler<&ELFAsmParser::ParseDirectivePrevious>(".previous");
addDirectiveHandler<&ELFAsmParser::ParseDirectiveType>(".type");
addDirectiveHandler<&ELFAsmParser::ParseDirectiveIdent>(".ident");
addDirectiveHandler<&ELFAsmParser::ParseDirectiveSymver>(".symver");
addDirectiveHandler<&ELFAsmParser::ParseDirectiveVersion>(".version");
addDirectiveHandler<&ELFAsmParser::ParseDirectiveWeakref>(".weakref");
addDirectiveHandler<&ELFAsmParser::ParseDirectiveSymbolAttribute>(".weak");
addDirectiveHandler<&ELFAsmParser::ParseDirectiveSymbolAttribute>(".local");
addDirectiveHandler<
&ELFAsmParser::ParseDirectiveSymbolAttribute>(".protected");
addDirectiveHandler<
&ELFAsmParser::ParseDirectiveSymbolAttribute>(".internal");
addDirectiveHandler<
&ELFAsmParser::ParseDirectiveSymbolAttribute>(".hidden");
addDirectiveHandler<&ELFAsmParser::ParseDirectiveSubsection>(".subsection");
}
// FIXME: Part of this logic is duplicated in the MCELFStreamer. What is
// the best way for us to get access to it?
bool ParseSectionDirectiveData(StringRef, SMLoc) {
return ParseSectionSwitch(".data", ELF::SHT_PROGBITS,
ELF::SHF_WRITE |ELF::SHF_ALLOC,
SectionKind::getDataRel());
}
bool ParseSectionDirectiveText(StringRef, SMLoc) {
return ParseSectionSwitch(".text", ELF::SHT_PROGBITS,
ELF::SHF_EXECINSTR |
ELF::SHF_ALLOC, SectionKind::getText());
}
bool ParseSectionDirectiveBSS(StringRef, SMLoc) {
return ParseSectionSwitch(".bss", ELF::SHT_NOBITS,
ELF::SHF_WRITE |
ELF::SHF_ALLOC, SectionKind::getBSS());
}
bool ParseSectionDirectiveRoData(StringRef, SMLoc) {
return ParseSectionSwitch(".rodata", ELF::SHT_PROGBITS,
ELF::SHF_ALLOC,
SectionKind::getReadOnly());
}
bool ParseSectionDirectiveTData(StringRef, SMLoc) {
return ParseSectionSwitch(".tdata", ELF::SHT_PROGBITS,
ELF::SHF_ALLOC |
ELF::SHF_TLS | ELF::SHF_WRITE,
SectionKind::getThreadData());
}
bool ParseSectionDirectiveTBSS(StringRef, SMLoc) {
return ParseSectionSwitch(".tbss", ELF::SHT_NOBITS,
ELF::SHF_ALLOC |
ELF::SHF_TLS | ELF::SHF_WRITE,
SectionKind::getThreadBSS());
}
bool ParseSectionDirectiveDataRel(StringRef, SMLoc) {
return ParseSectionSwitch(".data.rel", ELF::SHT_PROGBITS,
ELF::SHF_ALLOC |
ELF::SHF_WRITE,
SectionKind::getDataRel());
}
bool ParseSectionDirectiveDataRelRo(StringRef, SMLoc) {
return ParseSectionSwitch(".data.rel.ro", ELF::SHT_PROGBITS,
ELF::SHF_ALLOC |
ELF::SHF_WRITE,
SectionKind::getReadOnlyWithRel());
}
bool ParseSectionDirectiveDataRelRoLocal(StringRef, SMLoc) {
return ParseSectionSwitch(".data.rel.ro.local", ELF::SHT_PROGBITS,
ELF::SHF_ALLOC |
ELF::SHF_WRITE,
SectionKind::getReadOnlyWithRelLocal());
}
bool ParseSectionDirectiveEhFrame(StringRef, SMLoc) {
return ParseSectionSwitch(".eh_frame", ELF::SHT_PROGBITS,
ELF::SHF_ALLOC |
ELF::SHF_WRITE,
SectionKind::getDataRel());
}
bool ParseDirectivePushSection(StringRef, SMLoc);
bool ParseDirectivePopSection(StringRef, SMLoc);
bool ParseDirectiveSection(StringRef, SMLoc);
bool ParseDirectiveSize(StringRef, SMLoc);
bool ParseDirectivePrevious(StringRef, SMLoc);
bool ParseDirectiveType(StringRef, SMLoc);
bool ParseDirectiveIdent(StringRef, SMLoc);
bool ParseDirectiveSymver(StringRef, SMLoc);
bool ParseDirectiveVersion(StringRef, SMLoc);
bool ParseDirectiveWeakref(StringRef, SMLoc);
bool ParseDirectiveSymbolAttribute(StringRef, SMLoc);
bool ParseDirectiveSubsection(StringRef, SMLoc);
private:
bool ParseSectionName(StringRef &SectionName);
bool ParseSectionArguments(bool IsPush, SMLoc loc);
unsigned parseSunStyleSectionFlags();
};
}
/// ParseDirectiveSymbolAttribute
/// ::= { ".local", ".weak", ... } [ identifier ( , identifier )* ]
bool ELFAsmParser::ParseDirectiveSymbolAttribute(StringRef Directive, SMLoc) {
MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Directive)
.Case(".weak", MCSA_Weak)
.Case(".local", MCSA_Local)
.Case(".hidden", MCSA_Hidden)
.Case(".internal", MCSA_Internal)
.Case(".protected", MCSA_Protected)
.Default(MCSA_Invalid);
assert(Attr != MCSA_Invalid && "unexpected symbol attribute directive!");
if (getLexer().isNot(AsmToken::EndOfStatement)) {
for (;;) {
StringRef Name;
if (getParser().parseIdentifier(Name))
return TokError("expected identifier in directive");
MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
getStreamer().EmitSymbolAttribute(Sym, Attr);
if (getLexer().is(AsmToken::EndOfStatement))
break;
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
}
}
Lex();
return false;
}
bool ELFAsmParser::ParseSectionSwitch(StringRef Section, unsigned Type,
unsigned Flags, SectionKind Kind) {
const MCExpr *Subsection = nullptr;
if (getLexer().isNot(AsmToken::EndOfStatement)) {
if (getParser().parseExpression(Subsection))
return true;
}
getStreamer().SwitchSection(getContext().getELFSection(Section, Type, Flags),
Subsection);
return false;
}
bool ELFAsmParser::ParseDirectiveSize(StringRef, SMLoc) {
StringRef Name;
if (getParser().parseIdentifier(Name))
return TokError("expected identifier in directive");
MCSymbolELF *Sym = cast<MCSymbolELF>(getContext().getOrCreateSymbol(Name));
if (getLexer().isNot(AsmToken::Comma))
return TokError("unexpected token in directive");
Lex();
const MCExpr *Expr;
if (getParser().parseExpression(Expr))
return true;
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
getStreamer().emitELFSize(Sym, Expr);
return false;
}
bool ELFAsmParser::ParseSectionName(StringRef &SectionName) {
// A section name can contain -, so we cannot just use
// parseIdentifier.
SMLoc FirstLoc = getLexer().getLoc();
unsigned Size = 0;
if (getLexer().is(AsmToken::String)) {
SectionName = getTok().getIdentifier();
Lex();
return false;
}
for (;;) {
unsigned CurSize;
SMLoc PrevLoc = getLexer().getLoc();
if (getLexer().is(AsmToken::Minus)) {
CurSize = 1;
Lex(); // Consume the "-".
} else if (getLexer().is(AsmToken::String)) {
CurSize = getTok().getIdentifier().size() + 2;
Lex();
} else if (getLexer().is(AsmToken::Identifier)) {
CurSize = getTok().getIdentifier().size();
Lex();
} else {
break;
}
Size += CurSize;
SectionName = StringRef(FirstLoc.getPointer(), Size);
// Make sure the following token is adjacent.
if (PrevLoc.getPointer() + CurSize != getTok().getLoc().getPointer())
break;
}
if (Size == 0)
return true;
return false;
}
static unsigned parseSectionFlags(StringRef flagsStr, bool *UseLastGroup) {
unsigned flags = 0;
for (unsigned i = 0; i < flagsStr.size(); i++) {
switch (flagsStr[i]) {
case 'a':
flags |= ELF::SHF_ALLOC;
break;
case 'e':
flags |= ELF::SHF_EXCLUDE;
break;
case 'x':
flags |= ELF::SHF_EXECINSTR;
break;
case 'w':
flags |= ELF::SHF_WRITE;
break;
case 'M':
flags |= ELF::SHF_MERGE;
break;
case 'S':
flags |= ELF::SHF_STRINGS;
break;
case 'T':
flags |= ELF::SHF_TLS;
break;
case 'c':
flags |= ELF::XCORE_SHF_CP_SECTION;
break;
case 'd':
flags |= ELF::XCORE_SHF_DP_SECTION;
break;
case 'G':
flags |= ELF::SHF_GROUP;
break;
case '?':
*UseLastGroup = true;
break;
default:
return -1U;
}
}
return flags;
}
unsigned ELFAsmParser::parseSunStyleSectionFlags() {
unsigned flags = 0;
while (getLexer().is(AsmToken::Hash)) {
Lex(); // Eat the #.
if (!getLexer().is(AsmToken::Identifier))
return -1U;
StringRef flagId = getTok().getIdentifier();
if (flagId == "alloc")
flags |= ELF::SHF_ALLOC;
else if (flagId == "execinstr")
flags |= ELF::SHF_EXECINSTR;
else if (flagId == "write")
flags |= ELF::SHF_WRITE;
else if (flagId == "tls")
flags |= ELF::SHF_TLS;
else
return -1U;
Lex(); // Eat the flag.
if (!getLexer().is(AsmToken::Comma))
break;
Lex(); // Eat the comma.
}
return flags;
}
bool ELFAsmParser::ParseDirectivePushSection(StringRef s, SMLoc loc) {
getStreamer().PushSection();
if (ParseSectionArguments(/*IsPush=*/true, loc)) {
getStreamer().PopSection();
return true;
}
return false;
}
bool ELFAsmParser::ParseDirectivePopSection(StringRef, SMLoc) {
if (!getStreamer().PopSection())
return TokError(".popsection without corresponding .pushsection");
return false;
}
// FIXME: This is a work in progress.
bool ELFAsmParser::ParseDirectiveSection(StringRef, SMLoc loc) {
return ParseSectionArguments(/*IsPush=*/false, loc);
}
bool ELFAsmParser::ParseSectionArguments(bool IsPush, SMLoc loc) {
StringRef SectionName;
if (ParseSectionName(SectionName))
return TokError("expected identifier in directive");
StringRef TypeName;
int64_t Size = 0;
StringRef GroupName;
unsigned Flags = 0;
const MCExpr *Subsection = nullptr;
bool UseLastGroup = false;
StringRef UniqueStr;
int64_t UniqueID = ~0;
// Set the defaults first.
if (SectionName == ".fini" || SectionName == ".init" ||
SectionName == ".rodata")
Flags |= ELF::SHF_ALLOC;
if (SectionName == ".fini" || SectionName == ".init")
Flags |= ELF::SHF_EXECINSTR;
if (getLexer().is(AsmToken::Comma)) {
Lex();
if (IsPush && getLexer().isNot(AsmToken::String)) {
if (getParser().parseExpression(Subsection))
return true;
if (getLexer().isNot(AsmToken::Comma))
goto EndStmt;
Lex();
}
unsigned extraFlags;
if (getLexer().isNot(AsmToken::String)) {
if (!getContext().getAsmInfo()->usesSunStyleELFSectionSwitchSyntax()
|| getLexer().isNot(AsmToken::Hash))
return TokError("expected string in directive");
extraFlags = parseSunStyleSectionFlags();
} else {
StringRef FlagsStr = getTok().getStringContents();
Lex();
extraFlags = parseSectionFlags(FlagsStr, &UseLastGroup);
}
if (extraFlags == -1U)
return TokError("unknown flag");
Flags |= extraFlags;
bool Mergeable = Flags & ELF::SHF_MERGE;
bool Group = Flags & ELF::SHF_GROUP;
if (Group && UseLastGroup)
return TokError("Section cannot specifiy a group name while also acting "
"as a member of the last group");
if (getLexer().isNot(AsmToken::Comma)) {
if (Mergeable)
return TokError("Mergeable section must specify the type");
if (Group)
return TokError("Group section must specify the type");
} else {
Lex();
if (getLexer().is(AsmToken::At) || getLexer().is(AsmToken::Percent) ||
getLexer().is(AsmToken::String)) {
if (!getLexer().is(AsmToken::String))
Lex();
} else
return TokError("expected '@<type>', '%<type>' or \"<type>\"");
if (getParser().parseIdentifier(TypeName))
return TokError("expected identifier in directive");
if (Mergeable) {
if (getLexer().isNot(AsmToken::Comma))
return TokError("expected the entry size");
Lex();
if (getParser().parseAbsoluteExpression(Size))
return true;
if (Size <= 0)
return TokError("entry size must be positive");
}
if (Group) {
if (getLexer().isNot(AsmToken::Comma))
return TokError("expected group name");
Lex();
if (getParser().parseIdentifier(GroupName))
return true;
if (getLexer().is(AsmToken::Comma)) {
Lex();
StringRef Linkage;
if (getParser().parseIdentifier(Linkage))
return true;
if (Linkage != "comdat")
return TokError("Linkage must be 'comdat'");
}
}
if (getLexer().is(AsmToken::Comma)) {
Lex();
if (getParser().parseIdentifier(UniqueStr))
return TokError("expected identifier in directive");
if (UniqueStr != "unique")
return TokError("expected 'unique'");
if (getLexer().isNot(AsmToken::Comma))
return TokError("expected commma");
Lex();
if (getParser().parseAbsoluteExpression(UniqueID))
return true;
if (UniqueID < 0)
return TokError("unique id must be positive");
if (!isUInt<32>(UniqueID) || UniqueID == ~0U)
return TokError("unique id is too large");
}
}
}
EndStmt:
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
unsigned Type = ELF::SHT_PROGBITS;
if (TypeName.empty()) {
if (SectionName.startswith(".note"))
Type = ELF::SHT_NOTE;
else if (SectionName == ".init_array")
Type = ELF::SHT_INIT_ARRAY;
else if (SectionName == ".fini_array")
Type = ELF::SHT_FINI_ARRAY;
else if (SectionName == ".preinit_array")
Type = ELF::SHT_PREINIT_ARRAY;
} else {
if (TypeName == "init_array")
Type = ELF::SHT_INIT_ARRAY;
else if (TypeName == "fini_array")
Type = ELF::SHT_FINI_ARRAY;
else if (TypeName == "preinit_array")
Type = ELF::SHT_PREINIT_ARRAY;
else if (TypeName == "nobits")
Type = ELF::SHT_NOBITS;
else if (TypeName == "progbits")
Type = ELF::SHT_PROGBITS;
else if (TypeName == "note")
Type = ELF::SHT_NOTE;
else if (TypeName == "unwind")
Type = ELF::SHT_X86_64_UNWIND;
else
return TokError("unknown section type");
}
if (UseLastGroup) {
MCSectionSubPair CurrentSection = getStreamer().getCurrentSection();
if (const MCSectionELF *Section =
cast_or_null<MCSectionELF>(CurrentSection.first))
if (const MCSymbol *Group = Section->getGroup()) {
GroupName = Group->getName();
Flags |= ELF::SHF_GROUP;
}
}
MCSection *ELFSection = getContext().getELFSection(SectionName, Type, Flags,
Size, GroupName, UniqueID);
getStreamer().SwitchSection(ELFSection, Subsection);
if (getContext().getGenDwarfForAssembly()) {
bool InsertResult = getContext().addGenDwarfSection(ELFSection);
if (InsertResult) {
if (getContext().getDwarfVersion() <= 2)
Warning(loc, "DWARF2 only supports one section per compilation unit");
if (!ELFSection->getBeginSymbol()) {
MCSymbol *SectionStartSymbol = getContext().createTempSymbol();
getStreamer().EmitLabel(SectionStartSymbol);
ELFSection->setBeginSymbol(SectionStartSymbol);
}
}
}
return false;
}
bool ELFAsmParser::ParseDirectivePrevious(StringRef DirName, SMLoc) {
MCSectionSubPair PreviousSection = getStreamer().getPreviousSection();
if (PreviousSection.first == nullptr)
return TokError(".previous without corresponding .section");
getStreamer().SwitchSection(PreviousSection.first, PreviousSection.second);
return false;
}
static MCSymbolAttr MCAttrForString(StringRef Type) {
return StringSwitch<MCSymbolAttr>(Type)
.Cases("STT_FUNC", "function", MCSA_ELF_TypeFunction)
.Cases("STT_OBJECT", "object", MCSA_ELF_TypeObject)
.Cases("STT_TLS", "tls_object", MCSA_ELF_TypeTLS)
.Cases("STT_COMMON", "common", MCSA_ELF_TypeCommon)
.Cases("STT_NOTYPE", "notype", MCSA_ELF_TypeNoType)
.Cases("STT_GNU_IFUNC", "gnu_indirect_function",
MCSA_ELF_TypeIndFunction)
.Case("gnu_unique_object", MCSA_ELF_TypeGnuUniqueObject)
.Default(MCSA_Invalid);
}
/// ParseDirectiveELFType
/// ::= .type identifier , STT_<TYPE_IN_UPPER_CASE>
/// ::= .type identifier , #attribute
/// ::= .type identifier , @attribute
/// ::= .type identifier , %attribute
/// ::= .type identifier , "attribute"
bool ELFAsmParser::ParseDirectiveType(StringRef, SMLoc) {
StringRef Name;
if (getParser().parseIdentifier(Name))
return TokError("expected identifier in directive");
// Handle the identifier as the key symbol.
MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
// NOTE the comma is optional in all cases. It is only documented as being
// optional in the first case, however, GAS will silently treat the comma as
// optional in all cases. Furthermore, although the documentation states that
// the first form only accepts STT_<TYPE_IN_UPPER_CASE>, in reality, GAS
// accepts both the upper case name as well as the lower case aliases.
if (getLexer().is(AsmToken::Comma))
Lex();
if (getLexer().isNot(AsmToken::Identifier) &&
getLexer().isNot(AsmToken::Hash) &&
getLexer().isNot(AsmToken::Percent) &&
getLexer().isNot(AsmToken::String)) {
if (!getLexer().getAllowAtInIdentifier())
return TokError("expected STT_<TYPE_IN_UPPER_CASE>, '#<type>', "
"'%<type>' or \"<type>\"");
else if (getLexer().isNot(AsmToken::At))
return TokError("expected STT_<TYPE_IN_UPPER_CASE>, '#<type>', '@<type>', "
"'%<type>' or \"<type>\"");
}
if (getLexer().isNot(AsmToken::String) &&
getLexer().isNot(AsmToken::Identifier))
Lex();
SMLoc TypeLoc = getLexer().getLoc();
StringRef Type;
if (getParser().parseIdentifier(Type))
return TokError("expected symbol type in directive");
MCSymbolAttr Attr = MCAttrForString(Type);
if (Attr == MCSA_Invalid)
return Error(TypeLoc, "unsupported attribute in '.type' directive");
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in '.type' directive");
Lex();
getStreamer().EmitSymbolAttribute(Sym, Attr);
return false;
}
/// ParseDirectiveIdent
/// ::= .ident string
bool ELFAsmParser::ParseDirectiveIdent(StringRef, SMLoc) {
if (getLexer().isNot(AsmToken::String))
return TokError("unexpected token in '.ident' directive");
StringRef Data = getTok().getIdentifier();
Lex();
getStreamer().EmitIdent(Data);
return false;
}
/// ParseDirectiveSymver
/// ::= .symver foo, bar2@zed
bool ELFAsmParser::ParseDirectiveSymver(StringRef, SMLoc) {
StringRef Name;
if (getParser().parseIdentifier(Name))
return TokError("expected identifier in directive");
if (getLexer().isNot(AsmToken::Comma))
return TokError("expected a comma");
// ARM assembly uses @ for a comment...
// except when parsing the second parameter of the .symver directive.
// Force the next symbol to allow @ in the identifier, which is
// required for this directive and then reset it to its initial state.
const bool AllowAtInIdentifier = getLexer().getAllowAtInIdentifier();
getLexer().setAllowAtInIdentifier(true);
Lex();
getLexer().setAllowAtInIdentifier(AllowAtInIdentifier);
StringRef AliasName;
if (getParser().parseIdentifier(AliasName))
return TokError("expected identifier in directive");
if (AliasName.find('@') == StringRef::npos)
return TokError("expected a '@' in the name");
MCSymbol *Alias = getContext().getOrCreateSymbol(AliasName);
MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
const MCExpr *Value = MCSymbolRefExpr::create(Sym, getContext());
getStreamer().EmitAssignment(Alias, Value);
return false;
}
/// ParseDirectiveVersion
/// ::= .version string
bool ELFAsmParser::ParseDirectiveVersion(StringRef, SMLoc) {
if (getLexer().isNot(AsmToken::String))
return TokError("unexpected token in '.version' directive");
StringRef Data = getTok().getIdentifier();
Lex();
MCSection *Note = getContext().getELFSection(".note", ELF::SHT_NOTE, 0);
getStreamer().PushSection();
getStreamer().SwitchSection(Note);
getStreamer().EmitIntValue(Data.size()+1, 4); // namesz.
getStreamer().EmitIntValue(0, 4); // descsz = 0 (no description).
getStreamer().EmitIntValue(1, 4); // type = NT_VERSION.
getStreamer().EmitBytes(Data); // name.
getStreamer().EmitIntValue(0, 1); // terminate the string.
getStreamer().EmitValueToAlignment(4); // ensure 4 byte alignment.
getStreamer().PopSection();
return false;
}
/// ParseDirectiveWeakref
/// ::= .weakref foo, bar
bool ELFAsmParser::ParseDirectiveWeakref(StringRef, SMLoc) {
// FIXME: Share code with the other alias building directives.
StringRef AliasName;
if (getParser().parseIdentifier(AliasName))
return TokError("expected identifier in directive");
if (getLexer().isNot(AsmToken::Comma))
return TokError("expected a comma");
Lex();
StringRef Name;
if (getParser().parseIdentifier(Name))
return TokError("expected identifier in directive");
MCSymbol *Alias = getContext().getOrCreateSymbol(AliasName);
MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
getStreamer().EmitWeakReference(Alias, Sym);
return false;
}
bool ELFAsmParser::ParseDirectiveSubsection(StringRef, SMLoc) {
const MCExpr *Subsection = nullptr;
if (getLexer().isNot(AsmToken::EndOfStatement)) {
if (getParser().parseExpression(Subsection))
return true;
}
if (getLexer().isNot(AsmToken::EndOfStatement))
return TokError("unexpected token in directive");
getStreamer().SubSection(Subsection);
return false;
}
namespace llvm {
MCAsmParserExtension *createELFAsmParser() {
return new ELFAsmParser;
}
}
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCDisassembler/MCDisassembler.cpp | //===-- MCDisassembler.cpp - Disassembler interface -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCDisassembler.h"
#include "llvm/MC/MCExternalSymbolizer.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
MCDisassembler::~MCDisassembler() {
}
bool MCDisassembler::tryAddingSymbolicOperand(MCInst &Inst, int64_t Value,
uint64_t Address, bool IsBranch,
uint64_t Offset,
uint64_t InstSize) const {
raw_ostream &cStream = CommentStream ? *CommentStream : nulls();
if (Symbolizer)
return Symbolizer->tryAddingSymbolicOperand(Inst, cStream, Value, Address,
IsBranch, Offset, InstSize);
return false;
}
void MCDisassembler::tryAddingPcLoadReferenceComment(int64_t Value,
uint64_t Address) const {
raw_ostream &cStream = CommentStream ? *CommentStream : nulls();
if (Symbolizer)
Symbolizer->tryAddingPcLoadReferenceComment(cStream, Value, Address);
}
void MCDisassembler::setSymbolizer(std::unique_ptr<MCSymbolizer> Symzer) {
Symbolizer = std::move(Symzer);
}
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCDisassembler/MCRelocationInfo.cpp | //==-- MCRelocationInfo.cpp ------------------------------------------------==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCRelocationInfo.h"
#include "llvm-c/Disassembler.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;
MCRelocationInfo::MCRelocationInfo(MCContext &Ctx)
: Ctx(Ctx) {
}
MCRelocationInfo::~MCRelocationInfo() {
}
const MCExpr *
MCRelocationInfo::createExprForRelocation(object::RelocationRef Rel) {
return nullptr;
}
const MCExpr *
MCRelocationInfo::createExprForCAPIVariantKind(const MCExpr *SubExpr,
unsigned VariantKind) {
if (VariantKind != LLVMDisassembler_VariantKind_None)
return nullptr;
return SubExpr;
}
MCRelocationInfo *llvm::createMCRelocationInfo(const Triple &TT,
MCContext &Ctx) {
return new MCRelocationInfo(Ctx);
}
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCDisassembler/Disassembler.cpp | //===-- lib/MC/Disassembler.cpp - Disassembler Public C Interface ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Disassembler.h"
#include "llvm-c/Disassembler.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDisassembler.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCRelocationInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCSymbolizer.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;
// LLVMCreateDisasm() creates a disassembler for the TripleName. Symbolic
// disassembly is supported by passing a block of information in the DisInfo
// parameter and specifying the TagType and callback functions as described in
// the header llvm-c/Disassembler.h . The pointer to the block and the
// functions can all be passed as NULL. If successful, this returns a
// disassembler context. If not, it returns NULL.
//
LLVMDisasmContextRef
LLVMCreateDisasmCPUFeatures(const char *TT, const char *CPU,
const char *Features, void *DisInfo, int TagType,
LLVMOpInfoCallback GetOpInfo,
LLVMSymbolLookupCallback SymbolLookUp) {
// Get the target.
std::string Error;
const Target *TheTarget = TargetRegistry::lookupTarget(TT, Error);
if (!TheTarget)
return nullptr;
const MCRegisterInfo *MRI = TheTarget->createMCRegInfo(TT);
if (!MRI)
return nullptr;
// Get the assembler info needed to setup the MCContext.
const MCAsmInfo *MAI = TheTarget->createMCAsmInfo(*MRI, TT);
if (!MAI)
return nullptr;
const MCInstrInfo *MII = TheTarget->createMCInstrInfo();
if (!MII)
return nullptr;
const MCSubtargetInfo *STI =
TheTarget->createMCSubtargetInfo(TT, CPU, Features);
if (!STI)
return nullptr;
// Set up the MCContext for creating symbols and MCExpr's.
MCContext *Ctx = new MCContext(MAI, MRI, nullptr);
if (!Ctx)
return nullptr;
// Set up disassembler.
MCDisassembler *DisAsm = TheTarget->createMCDisassembler(*STI, *Ctx);
if (!DisAsm)
return nullptr;
std::unique_ptr<MCRelocationInfo> RelInfo(
TheTarget->createMCRelocationInfo(TT, *Ctx));
if (!RelInfo)
return nullptr;
std::unique_ptr<MCSymbolizer> Symbolizer(TheTarget->createMCSymbolizer(
TT, GetOpInfo, SymbolLookUp, DisInfo, Ctx, std::move(RelInfo)));
DisAsm->setSymbolizer(std::move(Symbolizer));
// Set up the instruction printer.
int AsmPrinterVariant = MAI->getAssemblerDialect();
MCInstPrinter *IP = TheTarget->createMCInstPrinter(
Triple(TT), AsmPrinterVariant, *MAI, *MII, *MRI);
if (!IP)
return nullptr;
LLVMDisasmContext *DC =
new LLVMDisasmContext(TT, DisInfo, TagType, GetOpInfo, SymbolLookUp,
TheTarget, MAI, MRI, STI, MII, Ctx, DisAsm, IP);
if (!DC)
return nullptr;
DC->setCPU(CPU);
return DC;
}
LLVMDisasmContextRef
LLVMCreateDisasmCPU(const char *TT, const char *CPU, void *DisInfo, int TagType,
LLVMOpInfoCallback GetOpInfo,
LLVMSymbolLookupCallback SymbolLookUp) {
return LLVMCreateDisasmCPUFeatures(TT, CPU, "", DisInfo, TagType, GetOpInfo,
SymbolLookUp);
}
LLVMDisasmContextRef LLVMCreateDisasm(const char *TT, void *DisInfo,
int TagType, LLVMOpInfoCallback GetOpInfo,
LLVMSymbolLookupCallback SymbolLookUp) {
return LLVMCreateDisasmCPUFeatures(TT, "", "", DisInfo, TagType, GetOpInfo,
SymbolLookUp);
}
//
// LLVMDisasmDispose() disposes of the disassembler specified by the context.
//
void LLVMDisasmDispose(LLVMDisasmContextRef DCR){
LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
delete DC;
}
/// \brief Emits the comments that are stored in \p DC comment stream.
/// Each comment in the comment stream must end with a newline.
static void emitComments(LLVMDisasmContext *DC,
formatted_raw_ostream &FormattedOS) {
// Flush the stream before taking its content.
DC->CommentStream.flush();
StringRef Comments = DC->CommentsToEmit.str();
// Get the default information for printing a comment.
const MCAsmInfo *MAI = DC->getAsmInfo();
const char *CommentBegin = MAI->getCommentString();
unsigned CommentColumn = MAI->getCommentColumn();
bool IsFirst = true;
while (!Comments.empty()) {
if (!IsFirst)
FormattedOS << '\n';
// Emit a line of comments.
FormattedOS.PadToColumn(CommentColumn);
size_t Position = Comments.find('\n');
FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
// Move after the newline character.
Comments = Comments.substr(Position+1);
IsFirst = false;
}
FormattedOS.flush();
// Tell the comment stream that the vector changed underneath it.
DC->CommentsToEmit.clear();
DC->CommentStream.resync();
}
/// \brief Gets latency information for \p Inst from the itinerary
/// scheduling model, based on \p DC information.
/// \return The maximum expected latency over all the operands or -1
/// if no information is available.
static int getItineraryLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
const int NoInformationAvailable = -1;
// Check if we have a CPU to get the itinerary information.
if (DC->getCPU().empty())
return NoInformationAvailable;
// Get itinerary information.
const MCSubtargetInfo *STI = DC->getSubtargetInfo();
InstrItineraryData IID = STI->getInstrItineraryForCPU(DC->getCPU());
// Get the scheduling class of the requested instruction.
const MCInstrDesc& Desc = DC->getInstrInfo()->get(Inst.getOpcode());
unsigned SCClass = Desc.getSchedClass();
int Latency = 0;
for (unsigned OpIdx = 0, OpIdxEnd = Inst.getNumOperands(); OpIdx != OpIdxEnd;
++OpIdx)
Latency = std::max(Latency, IID.getOperandCycle(SCClass, OpIdx));
return Latency;
}
/// \brief Gets latency information for \p Inst, based on \p DC information.
/// \return The maximum expected latency over all the definitions or -1
/// if no information is available.
static int getLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
// Try to compute scheduling information.
const MCSubtargetInfo *STI = DC->getSubtargetInfo();
const MCSchedModel SCModel = STI->getSchedModel();
const int NoInformationAvailable = -1;
// Check if we have a scheduling model for instructions.
if (!SCModel.hasInstrSchedModel())
// Try to fall back to the itinerary model if the scheduling model doesn't
// have a scheduling table. Note the default does not have a table.
return getItineraryLatency(DC, Inst);
// Get the scheduling class of the requested instruction.
const MCInstrDesc& Desc = DC->getInstrInfo()->get(Inst.getOpcode());
unsigned SCClass = Desc.getSchedClass();
const MCSchedClassDesc *SCDesc = SCModel.getSchedClassDesc(SCClass);
// Resolving the variant SchedClass requires an MI to pass to
// SubTargetInfo::resolveSchedClass.
if (!SCDesc || !SCDesc->isValid() || SCDesc->isVariant())
return NoInformationAvailable;
// Compute output latency.
int Latency = 0;
for (unsigned DefIdx = 0, DefEnd = SCDesc->NumWriteLatencyEntries;
DefIdx != DefEnd; ++DefIdx) {
// Lookup the definition's write latency in SubtargetInfo.
const MCWriteLatencyEntry *WLEntry = STI->getWriteLatencyEntry(SCDesc,
DefIdx);
Latency = std::max(Latency, WLEntry->Cycles);
}
return Latency;
}
/// \brief Emits latency information in DC->CommentStream for \p Inst, based
/// on the information available in \p DC.
static void emitLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
int Latency = getLatency(DC, Inst);
// Report only interesting latencies.
if (Latency < 2)
return;
DC->CommentStream << "Latency: " << Latency << '\n';
}
//
// LLVMDisasmInstruction() disassembles a single instruction using the
// disassembler context specified in the parameter DC. The bytes of the
// instruction are specified in the parameter Bytes, and contains at least
// BytesSize number of bytes. The instruction is at the address specified by
// the PC parameter. If a valid instruction can be disassembled its string is
// returned indirectly in OutString which whos size is specified in the
// parameter OutStringSize. This function returns the number of bytes in the
// instruction or zero if there was no valid instruction. If this function
// returns zero the caller will have to pick how many bytes they want to step
// over by printing a .byte, .long etc. to continue.
//
size_t LLVMDisasmInstruction(LLVMDisasmContextRef DCR, uint8_t *Bytes,
uint64_t BytesSize, uint64_t PC, char *OutString,
size_t OutStringSize){
LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
// Wrap the pointer to the Bytes, BytesSize and PC in a MemoryObject.
ArrayRef<uint8_t> Data(Bytes, BytesSize);
uint64_t Size;
MCInst Inst;
const MCDisassembler *DisAsm = DC->getDisAsm();
MCInstPrinter *IP = DC->getIP();
MCDisassembler::DecodeStatus S;
SmallVector<char, 64> InsnStr;
raw_svector_ostream Annotations(InsnStr);
S = DisAsm->getInstruction(Inst, Size, Data, PC,
/*REMOVE*/ nulls(), Annotations);
switch (S) {
case MCDisassembler::Fail:
case MCDisassembler::SoftFail:
// FIXME: Do something different for soft failure modes?
return 0;
case MCDisassembler::Success: {
Annotations.flush();
StringRef AnnotationsStr = Annotations.str();
SmallVector<char, 64> InsnStr;
raw_svector_ostream OS(InsnStr);
formatted_raw_ostream FormattedOS(OS);
IP->printInst(&Inst, FormattedOS, AnnotationsStr, *DC->getSubtargetInfo());
if (DC->getOptions() & LLVMDisassembler_Option_PrintLatency)
emitLatency(DC, Inst);
emitComments(DC, FormattedOS);
OS.flush();
assert(OutStringSize != 0 && "Output buffer cannot be zero size");
size_t OutputSize = std::min(OutStringSize-1, InsnStr.size());
std::memcpy(OutString, InsnStr.data(), OutputSize);
OutString[OutputSize] = '\0'; // Terminate string.
return Size;
}
}
llvm_unreachable("Invalid DecodeStatus!");
}
//
// LLVMSetDisasmOptions() sets the disassembler's options. It returns 1 if it
// can set all the Options and 0 otherwise.
//
int LLVMSetDisasmOptions(LLVMDisasmContextRef DCR, uint64_t Options){
if (Options & LLVMDisassembler_Option_UseMarkup){
LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
MCInstPrinter *IP = DC->getIP();
IP->setUseMarkup(1);
DC->addOptions(LLVMDisassembler_Option_UseMarkup);
Options &= ~LLVMDisassembler_Option_UseMarkup;
}
if (Options & LLVMDisassembler_Option_PrintImmHex){
LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
MCInstPrinter *IP = DC->getIP();
IP->setPrintImmHex(1);
DC->addOptions(LLVMDisassembler_Option_PrintImmHex);
Options &= ~LLVMDisassembler_Option_PrintImmHex;
}
if (Options & LLVMDisassembler_Option_AsmPrinterVariant){
LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
// Try to set up the new instruction printer.
const MCAsmInfo *MAI = DC->getAsmInfo();
const MCInstrInfo *MII = DC->getInstrInfo();
const MCRegisterInfo *MRI = DC->getRegisterInfo();
int AsmPrinterVariant = MAI->getAssemblerDialect();
AsmPrinterVariant = AsmPrinterVariant == 0 ? 1 : 0;
MCInstPrinter *IP = DC->getTarget()->createMCInstPrinter(
Triple(DC->getTripleName()), AsmPrinterVariant, *MAI, *MII, *MRI);
if (IP) {
DC->setIP(IP);
DC->addOptions(LLVMDisassembler_Option_AsmPrinterVariant);
Options &= ~LLVMDisassembler_Option_AsmPrinterVariant;
}
}
if (Options & LLVMDisassembler_Option_SetInstrComments) {
LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
MCInstPrinter *IP = DC->getIP();
IP->setCommentStream(DC->CommentStream);
DC->addOptions(LLVMDisassembler_Option_SetInstrComments);
Options &= ~LLVMDisassembler_Option_SetInstrComments;
}
if (Options & LLVMDisassembler_Option_PrintLatency) {
LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
DC->addOptions(LLVMDisassembler_Option_PrintLatency);
Options &= ~LLVMDisassembler_Option_PrintLatency;
}
return (Options == 0);
}
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCDisassembler/CMakeLists.txt | add_llvm_library(LLVMMCDisassembler
Disassembler.cpp
MCRelocationInfo.cpp
MCExternalSymbolizer.cpp
MCDisassembler.cpp
)
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCDisassembler/LLVMBuild.txt | ;===- ./lib/MC/MCDisassembler/LLVMBuild.txt --------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Library
name = MCDisassembler
parent = MC
required_libraries = MC Support
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCDisassembler/Disassembler.h | //===------------- Disassembler.h - LLVM Disassembler -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the interface for the Disassembly library's disassembler
// context. The disassembler is responsible for producing strings for
// individual instructions according to a given architecture and disassembly
// syntax.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_MC_MCDISASSEMBLER_DISASSEMBLER_H
#define LLVM_LIB_MC_MCDISASSEMBLER_DISASSEMBLER_H
#include "llvm-c/Disassembler.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/raw_ostream.h"
#include <string>
namespace llvm {
class MCContext;
class MCAsmInfo;
class MCDisassembler;
class MCInstPrinter;
class MCInstrInfo;
class MCRegisterInfo;
class MCSubtargetInfo;
class Target;
//
// This is the disassembler context returned by LLVMCreateDisasm().
//
class LLVMDisasmContext {
private:
//
// The passed parameters when the disassembler context is created.
//
// The TripleName for this disassembler.
std::string TripleName;
// The pointer to the caller's block of symbolic information.
void *DisInfo;
// The Triple specific symbolic information type returned by GetOpInfo.
int TagType;
// The function to get the symbolic information for operands.
LLVMOpInfoCallback GetOpInfo;
// The function to look up a symbol name.
LLVMSymbolLookupCallback SymbolLookUp;
//
// The objects created and saved by LLVMCreateDisasm() then used by
// LLVMDisasmInstruction().
//
// The LLVM target corresponding to the disassembler.
// FIXME: using std::unique_ptr<const llvm::Target> causes a malloc error
// when this LLVMDisasmContext is deleted.
const Target *TheTarget;
// The assembly information for the target architecture.
std::unique_ptr<const llvm::MCAsmInfo> MAI;
// The register information for the target architecture.
std::unique_ptr<const llvm::MCRegisterInfo> MRI;
// The subtarget information for the target architecture.
std::unique_ptr<const llvm::MCSubtargetInfo> MSI;
// The instruction information for the target architecture.
std::unique_ptr<const llvm::MCInstrInfo> MII;
// The assembly context for creating symbols and MCExprs.
std::unique_ptr<const llvm::MCContext> Ctx;
// The disassembler for the target architecture.
std::unique_ptr<const llvm::MCDisassembler> DisAsm;
// The instruction printer for the target architecture.
std::unique_ptr<llvm::MCInstPrinter> IP;
// The options used to set up the disassembler.
uint64_t Options;
// The CPU string.
std::string CPU;
public:
// Comment stream and backing vector.
SmallString<128> CommentsToEmit;
raw_svector_ostream CommentStream;
LLVMDisasmContext(std::string tripleName, void *disInfo, int tagType,
LLVMOpInfoCallback getOpInfo,
LLVMSymbolLookupCallback symbolLookUp,
const Target *theTarget, const MCAsmInfo *mAI,
const MCRegisterInfo *mRI,
const MCSubtargetInfo *mSI,
const MCInstrInfo *mII,
llvm::MCContext *ctx, const MCDisassembler *disAsm,
MCInstPrinter *iP) : TripleName(tripleName),
DisInfo(disInfo), TagType(tagType), GetOpInfo(getOpInfo),
SymbolLookUp(symbolLookUp), TheTarget(theTarget),
Options(0),
CommentStream(CommentsToEmit) {
MAI.reset(mAI);
MRI.reset(mRI);
MSI.reset(mSI);
MII.reset(mII);
Ctx.reset(ctx);
DisAsm.reset(disAsm);
IP.reset(iP);
}
const std::string &getTripleName() const { return TripleName; }
void *getDisInfo() const { return DisInfo; }
int getTagType() const { return TagType; }
LLVMOpInfoCallback getGetOpInfo() const { return GetOpInfo; }
LLVMSymbolLookupCallback getSymbolLookupCallback() const {
return SymbolLookUp;
}
const Target *getTarget() const { return TheTarget; }
const MCDisassembler *getDisAsm() const { return DisAsm.get(); }
const MCAsmInfo *getAsmInfo() const { return MAI.get(); }
const MCInstrInfo *getInstrInfo() const { return MII.get(); }
const MCRegisterInfo *getRegisterInfo() const { return MRI.get(); }
const MCSubtargetInfo *getSubtargetInfo() const { return MSI.get(); }
MCInstPrinter *getIP() { return IP.get(); }
void setIP(MCInstPrinter *NewIP) { IP.reset(NewIP); }
uint64_t getOptions() const { return Options; }
void addOptions(uint64_t Options) { this->Options |= Options; }
StringRef getCPU() const { return CPU; }
void setCPU(const char *CPU) { this->CPU = CPU; }
};
} // namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/lib/MC | repos/DirectXShaderCompiler/lib/MC/MCDisassembler/MCExternalSymbolizer.cpp | //===-- MCExternalSymbolizer.cpp - External symbolizer --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCExternalSymbolizer.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInst.h"
#include "llvm/Support/raw_ostream.h"
#include <cstring>
using namespace llvm;
namespace llvm {
class Triple;
}
// This function tries to add a symbolic operand in place of the immediate
// Value in the MCInst. The immediate Value has had any PC adjustment made by
// the caller. If the instruction is a branch instruction then IsBranch is true,
// else false. If the getOpInfo() function was set as part of the
// setupForSymbolicDisassembly() call then that function is called to get any
// symbolic information at the Address for this instruction. If that returns
// non-zero then the symbolic information it returns is used to create an MCExpr
// and that is added as an operand to the MCInst. If getOpInfo() returns zero
// and IsBranch is true then a symbol look up for Value is done and if a symbol
// is found an MCExpr is created with that, else an MCExpr with Value is
// created. This function returns true if it adds an operand to the MCInst and
// false otherwise.
bool MCExternalSymbolizer::tryAddingSymbolicOperand(MCInst &MI,
raw_ostream &cStream,
int64_t Value,
uint64_t Address,
bool IsBranch,
uint64_t Offset,
uint64_t InstSize) {
struct LLVMOpInfo1 SymbolicOp;
std::memset(&SymbolicOp, '\0', sizeof(struct LLVMOpInfo1));
SymbolicOp.Value = Value;
if (!GetOpInfo ||
!GetOpInfo(DisInfo, Address, Offset, InstSize, 1, &SymbolicOp)) {
// Clear SymbolicOp.Value from above and also all other fields.
std::memset(&SymbolicOp, '\0', sizeof(struct LLVMOpInfo1));
// At this point, GetOpInfo() did not find any relocation information about
// this operand and we are left to use the SymbolLookUp() call back to guess
// if the Value is the address of a symbol. In the case this is a branch
// that always makes sense to guess. But in the case of an immediate it is
// a bit more questionable if it is an address of a symbol or some other
// reference. So if the immediate Value comes from a width of 1 byte,
// InstSize, we will not guess it is an address of a symbol. Because in
// object files assembled starting at address 0 this usually leads to
// incorrect symbolication.
if (!SymbolLookUp || (InstSize == 1 && !IsBranch))
return false;
uint64_t ReferenceType;
if (IsBranch)
ReferenceType = LLVMDisassembler_ReferenceType_In_Branch;
else
ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
const char *ReferenceName;
const char *Name = SymbolLookUp(DisInfo, Value, &ReferenceType, Address,
&ReferenceName);
if (Name) {
SymbolicOp.AddSymbol.Name = Name;
SymbolicOp.AddSymbol.Present = true;
// If Name is a C++ symbol name put the human readable name in a comment.
if(ReferenceType == LLVMDisassembler_ReferenceType_DeMangled_Name)
cStream << ReferenceName;
}
// For branches always create an MCExpr so it gets printed as hex address.
else if (IsBranch) {
SymbolicOp.Value = Value;
}
if(ReferenceType == LLVMDisassembler_ReferenceType_Out_SymbolStub)
cStream << "symbol stub for: " << ReferenceName;
else if(ReferenceType == LLVMDisassembler_ReferenceType_Out_Objc_Message)
cStream << "Objc message: " << ReferenceName;
if (!Name && !IsBranch)
return false;
}
const MCExpr *Add = nullptr;
if (SymbolicOp.AddSymbol.Present) {
if (SymbolicOp.AddSymbol.Name) {
StringRef Name(SymbolicOp.AddSymbol.Name);
MCSymbol *Sym = Ctx.getOrCreateSymbol(Name);
Add = MCSymbolRefExpr::create(Sym, Ctx);
} else {
Add = MCConstantExpr::create((int)SymbolicOp.AddSymbol.Value, Ctx);
}
}
const MCExpr *Sub = nullptr;
if (SymbolicOp.SubtractSymbol.Present) {
if (SymbolicOp.SubtractSymbol.Name) {
StringRef Name(SymbolicOp.SubtractSymbol.Name);
MCSymbol *Sym = Ctx.getOrCreateSymbol(Name);
Sub = MCSymbolRefExpr::create(Sym, Ctx);
} else {
Sub = MCConstantExpr::create((int)SymbolicOp.SubtractSymbol.Value, Ctx);
}
}
const MCExpr *Off = nullptr;
if (SymbolicOp.Value != 0)
Off = MCConstantExpr::create(SymbolicOp.Value, Ctx);
const MCExpr *Expr;
if (Sub) {
const MCExpr *LHS;
if (Add)
LHS = MCBinaryExpr::createSub(Add, Sub, Ctx);
else
LHS = MCUnaryExpr::createMinus(Sub, Ctx);
if (Off)
Expr = MCBinaryExpr::createAdd(LHS, Off, Ctx);
else
Expr = LHS;
} else if (Add) {
if (Off)
Expr = MCBinaryExpr::createAdd(Add, Off, Ctx);
else
Expr = Add;
} else {
if (Off)
Expr = Off;
else
Expr = MCConstantExpr::create(0, Ctx);
}
Expr = RelInfo->createExprForCAPIVariantKind(Expr, SymbolicOp.VariantKind);
if (!Expr)
return false;
MI.addOperand(MCOperand::createExpr(Expr));
return true;
}
// This function tries to add a comment as to what is being referenced by a load
// instruction with the base register that is the Pc. These can often be values
// in a literal pool near the Address of the instruction. The Address of the
// instruction and its immediate Value are used as a possible literal pool entry.
// The SymbolLookUp call back will return the name of a symbol referenced by the
// literal pool's entry if the referenced address is that of a symbol. Or it
// will return a pointer to a literal 'C' string if the referenced address of
// the literal pool's entry is an address into a section with C string literals.
// Or if the reference is to an Objective-C data structure it will return a
// specific reference type for it and a string.
void MCExternalSymbolizer::tryAddingPcLoadReferenceComment(raw_ostream &cStream,
int64_t Value,
uint64_t Address) {
if (SymbolLookUp) {
uint64_t ReferenceType = LLVMDisassembler_ReferenceType_In_PCrel_Load;
const char *ReferenceName;
(void)SymbolLookUp(DisInfo, Value, &ReferenceType, Address, &ReferenceName);
if(ReferenceType == LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr)
cStream << "literal pool symbol address: " << ReferenceName;
else if(ReferenceType ==
LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr) {
cStream << "literal pool for: \"";
cStream.write_escaped(ReferenceName);
cStream << "\"";
}
else if(ReferenceType ==
LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref)
cStream << "Objc cfstring ref: @\"" << ReferenceName << "\"";
else if(ReferenceType ==
LLVMDisassembler_ReferenceType_Out_Objc_Message)
cStream << "Objc message: " << ReferenceName;
else if(ReferenceType ==
LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref)
cStream << "Objc message ref: " << ReferenceName;
else if(ReferenceType ==
LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref)
cStream << "Objc selector ref: " << ReferenceName;
else if(ReferenceType ==
LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref)
cStream << "Objc class ref: " << ReferenceName;
}
}
namespace llvm {
MCSymbolizer *createMCSymbolizer(const Triple &TT, LLVMOpInfoCallback GetOpInfo,
LLVMSymbolLookupCallback SymbolLookUp,
void *DisInfo, MCContext *Ctx,
std::unique_ptr<MCRelocationInfo> &&RelInfo) {
assert(Ctx && "No MCContext given for symbolic disassembly");
return new MCExternalSymbolizer(*Ctx, std::move(RelInfo), GetOpInfo,
SymbolLookUp, DisInfo);
}
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MSSupport/CMakeLists.txt | # Copyright (C) Microsoft Corporation. All rights reserved.
# This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details.
add_llvm_library(LLVMMSSupport
MSFileSystemImpl.cpp
)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/MSSupport/MSFileSystemImpl.cpp | //===- llvm/Support/Windows/MSFileSystemImpl.cpp DXComplier Impl *- C++ -*-===//
///////////////////////////////////////////////////////////////////////////////
// //
// MSFileSystemImpl.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// This file implements the DXCompiler specific implementation of the Path //
// API. //
// //
///////////////////////////////////////////////////////////////////////////////
#include <fcntl.h>
#ifdef _WIN32
#include <io.h>
#else
#include <sys/types.h>
#include <unistd.h>
#endif
#include <errno.h>
#include <new>
#include <stdint.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "dxc/Support/WinIncludes.h"
#include "dxc/WinAdapter.h"
#include "llvm/Support/MSFileSystem.h"
////////////////////////////////////////////////////////////////////////////////
// Externally visible functions.
HRESULT
CreateMSFileSystemForDisk(::llvm::sys::fs::MSFileSystem **pResult) throw();
////////////////////////////////////////////////////////////////////////////////
// Win32-and-CRT-based MSFileSystem implementation with direct filesystem
// access.
namespace llvm {
namespace sys {
namespace fs {
class MSFileSystemForDisk : public MSFileSystem {
public:
unsigned _defaultAttributes;
MSFileSystemForDisk();
virtual BOOL
FindNextFileW(HANDLE hFindFile,
LPWIN32_FIND_DATAW lpFindFileData) throw() override;
virtual HANDLE
FindFirstFileW(LPCWSTR lpFileName,
LPWIN32_FIND_DATAW lpFindFileData) throw() override;
virtual void FindClose(HANDLE findHandle) throw() override;
virtual HANDLE CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess,
DWORD dwShareMode, DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes) throw() override;
virtual BOOL SetFileTime(HANDLE hFile, const FILETIME *lpCreationTime,
const FILETIME *lpLastAccessTime,
const FILETIME *lpLastWriteTime) throw() override;
virtual BOOL GetFileInformationByHandle(
HANDLE hFile,
LPBY_HANDLE_FILE_INFORMATION lpFileInformation) throw() override;
virtual DWORD GetFileType(HANDLE hFile) throw() override;
virtual BOOL CreateHardLinkW(LPCWSTR lpFileName,
LPCWSTR lpExistingFileName) throw() override;
virtual BOOL MoveFileExW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName,
DWORD dwFlags) throw() override;
virtual DWORD GetFileAttributesW(LPCWSTR lpFileName) throw() override;
virtual BOOL CloseHandle(HANDLE hObject) throw() override;
virtual BOOL DeleteFileW(LPCWSTR lpFileName) throw() override;
virtual BOOL RemoveDirectoryW(LPCWSTR lpFileName) throw() override;
virtual BOOL CreateDirectoryW(LPCWSTR lpPathName) throw() override;
virtual DWORD GetCurrentDirectoryW(DWORD nBufferLength,
LPWSTR lpBuffer) throw() override;
virtual DWORD GetMainModuleFileNameW(LPWSTR lpFilename,
DWORD nSize) throw() override;
virtual DWORD GetTempPathW(DWORD nBufferLength,
LPWSTR lpBuffer) throw() override;
virtual BOOLEAN CreateSymbolicLinkW(LPCWSTR lpSymlinkFileName,
LPCWSTR lpTargetFileName,
DWORD dwFlags) throw() override;
virtual bool SupportsCreateSymbolicLink() throw() override;
virtual BOOL ReadFile(HANDLE hFile, LPVOID lpBuffer,
DWORD nNumberOfBytesToRead,
LPDWORD lpNumberOfBytesRead) throw() override;
virtual HANDLE CreateFileMappingW(HANDLE hFile, DWORD flProtect,
DWORD dwMaximumSizeHigh,
DWORD dwMaximumSizeLow) throw() override;
virtual LPVOID MapViewOfFile(HANDLE hFileMappingObject, DWORD dwDesiredAccess,
DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow,
SIZE_T dwNumberOfBytesToMap) throw() override;
virtual BOOL UnmapViewOfFile(LPCVOID lpBaseAddress) throw() override;
// Console APIs.
virtual bool FileDescriptorIsDisplayed(int fd) throw() override;
virtual unsigned GetColumnCount(DWORD nStdHandle) throw() override;
virtual unsigned GetConsoleOutputTextAttributes() throw() override;
virtual void
SetConsoleOutputTextAttributes(unsigned attributes) throw() override;
virtual void ResetConsoleOutputTextAttributes() throw() override;
// CRT APIs.
virtual int open_osfhandle(intptr_t osfhandle, int flags) throw() override;
virtual intptr_t get_osfhandle(int fd) throw() override;
virtual int close(int fd) throw() override;
virtual long lseek(int fd, long offset, int origin) throw() override;
virtual int setmode(int fd, int mode) throw() override;
virtual errno_t resize_file(LPCWSTR path, uint64_t size) throw() override;
virtual int Read(int fd, void *buffer, unsigned int count) throw() override;
virtual int Write(int fd, const void *buffer,
unsigned int count) throw() override;
#ifndef _WIN32
virtual int Open(const char *lpFileName, int flags,
mode_t mode) throw() override;
virtual int Stat(const char *lpFileName,
struct stat *Status) throw() override;
virtual int Fstat(int FD, struct stat *Status) throw() override;
#endif
};
MSFileSystemForDisk::MSFileSystemForDisk() {
#ifdef _WIN32
_defaultAttributes = GetConsoleOutputTextAttributes();
#endif
}
BOOL MSFileSystemForDisk::FindNextFileW(
HANDLE hFindFile, LPWIN32_FIND_DATAW lpFindFileData) throw() {
#ifdef _WIN32
return ::FindNextFileW(hFindFile, lpFindFileData);
#else
assert(false && "Not implemented for Unix");
return false;
#endif
}
HANDLE
MSFileSystemForDisk::FindFirstFileW(LPCWSTR lpFileName,
LPWIN32_FIND_DATAW lpFindFileData) throw() {
#ifdef _WIN32
return ::FindFirstFileW(lpFileName, lpFindFileData);
#else
assert(false && "Not implemented for Unix");
return nullptr;
#endif
}
void MSFileSystemForDisk::FindClose(HANDLE findHandle) throw() {
#ifdef _WIN32
::FindClose(findHandle);
#else
assert(false && "Not implemented for Unix");
#endif
}
HANDLE MSFileSystemForDisk::CreateFileW(LPCWSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes) throw() {
#ifdef _WIN32
return ::CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, nullptr,
dwCreationDisposition, dwFlagsAndAttributes, nullptr);
#else
assert(false && "Not implemented for Unix");
return nullptr;
#endif
}
BOOL MSFileSystemForDisk::SetFileTime(HANDLE hFile,
const FILETIME *lpCreationTime,
const FILETIME *lpLastAccessTime,
const FILETIME *lpLastWriteTime) throw() {
#ifdef _WIN32
return ::SetFileTime(hFile, lpCreationTime, lpLastAccessTime,
lpLastWriteTime);
#else
assert(false && "Not implemented for Unix");
return false;
#endif
}
BOOL MSFileSystemForDisk::GetFileInformationByHandle(
HANDLE hFile, LPBY_HANDLE_FILE_INFORMATION lpFileInformation) throw() {
#ifdef _WIN32
return ::GetFileInformationByHandle(hFile, lpFileInformation);
#else
assert(false && "Not implemented for Unix");
return false;
#endif
}
DWORD
MSFileSystemForDisk::GetFileType(HANDLE hFile) throw() {
#ifdef _WIN32
return ::GetFileType(hFile);
#else
assert(false && "Not implemented for Unix");
return 0;
#endif
}
BOOL MSFileSystemForDisk::CreateHardLinkW(LPCWSTR lpFileName,
LPCWSTR lpExistingFileName) throw() {
#ifdef _WIN32
return ::CreateHardLinkW(lpFileName, lpExistingFileName, nullptr);
#else
assert(false && "Not implemented for Unix");
return false;
#endif
}
BOOL MSFileSystemForDisk::MoveFileExW(LPCWSTR lpExistingFileName,
LPCWSTR lpNewFileName,
DWORD dwFlags) throw() {
#ifdef _WIN32
return ::MoveFileExW(lpExistingFileName, lpNewFileName, dwFlags);
#else
assert(false && "Not implemented for Unix");
return false;
#endif
}
DWORD
MSFileSystemForDisk::GetFileAttributesW(LPCWSTR lpFileName) throw() {
#ifdef _WIN32
return ::GetFileAttributesW(lpFileName);
#else
assert(false && "Not implemented for Unix");
return 0;
#endif
}
BOOL MSFileSystemForDisk::CloseHandle(HANDLE hObject) throw() {
#ifdef _WIN32
return ::CloseHandle(hObject);
#else
assert(false && "Not implemented for Unix");
return false;
#endif
}
BOOL MSFileSystemForDisk::DeleteFileW(LPCWSTR lpFileName) throw() {
#ifdef _WIN32
return ::DeleteFileW(lpFileName);
#else
assert(false && "Not implemented for Unix");
return false;
#endif
}
BOOL MSFileSystemForDisk::RemoveDirectoryW(LPCWSTR lpFileName) throw() {
#ifdef _WIN32
return ::RemoveDirectoryW(lpFileName);
#else
assert(false && "Not implemented for Unix");
return false;
#endif
}
BOOL MSFileSystemForDisk::CreateDirectoryW(LPCWSTR lpPathName) throw() {
#ifdef _WIN32
return ::CreateDirectoryW(lpPathName, nullptr);
#else
assert(false && "Not implemented for Unix");
return false;
#endif
}
DWORD MSFileSystemForDisk::GetCurrentDirectoryW(DWORD nBufferLength,
LPWSTR lpBuffer) throw() {
#ifdef _WIN32
return ::GetCurrentDirectoryW(nBufferLength, lpBuffer);
#else
assert(false && "Not implemented for Unix");
return 0;
#endif
}
DWORD MSFileSystemForDisk::GetMainModuleFileNameW(LPWSTR lpFilename,
DWORD nSize) throw() {
#ifdef _WIN32
// Add some code to ensure that the result is null terminated.
if (nSize <= 1) {
::SetLastError(ERROR_INSUFFICIENT_BUFFER);
return 0;
}
DWORD result = ::GetModuleFileNameW(nullptr, lpFilename, nSize - 1);
if (result == 0)
return result;
lpFilename[result] = L'\0';
return result;
#else
assert(false && "Not implemented for Unix");
return 0;
#endif
}
DWORD MSFileSystemForDisk::GetTempPathW(DWORD nBufferLength,
LPWSTR lpBuffer) throw() {
#ifdef _WIN32
return ::GetTempPathW(nBufferLength, lpBuffer);
#else
assert(false && "Not implemented for Unix");
return 0;
#endif
}
#ifdef _WIN32
namespace {
typedef BOOLEAN(WINAPI *PtrCreateSymbolicLinkW)(
/*__in*/ LPCWSTR lpSymlinkFileName,
/*__in*/ LPCWSTR lpTargetFileName,
/*__in*/ DWORD dwFlags);
PtrCreateSymbolicLinkW create_symbolic_link_api =
PtrCreateSymbolicLinkW(::GetProcAddress(::GetModuleHandleW(L"Kernel32.dll"),
"CreateSymbolicLinkW"));
} // namespace
#endif
BOOLEAN MSFileSystemForDisk::CreateSymbolicLinkW(LPCWSTR lpSymlinkFileName,
LPCWSTR lpTargetFileName,
DWORD dwFlags) throw() {
#ifdef _WIN32
return create_symbolic_link_api(lpSymlinkFileName, lpTargetFileName, dwFlags);
#else
assert(false && "Not implemented for Unix");
return false;
#endif
}
bool MSFileSystemForDisk::SupportsCreateSymbolicLink() throw() {
#ifdef _WIN32
return create_symbolic_link_api != nullptr;
#else
assert(false && "Not implemented for Unix");
return false;
#endif
}
BOOL MSFileSystemForDisk::ReadFile(HANDLE hFile, LPVOID lpBuffer,
DWORD nNumberOfBytesToRead,
LPDWORD lpNumberOfBytesRead) throw() {
#ifdef _WIN32
return ::ReadFile(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead,
nullptr);
#else
assert(false && "Not implemented for Unix");
return false;
#endif
}
HANDLE MSFileSystemForDisk::CreateFileMappingW(HANDLE hFile, DWORD flProtect,
DWORD dwMaximumSizeHigh,
DWORD dwMaximumSizeLow) throw() {
#ifdef _WIN32
return ::CreateFileMappingW(hFile, nullptr, flProtect, dwMaximumSizeHigh,
dwMaximumSizeLow, nullptr);
#else
assert(false && "Not implemented for Unix");
return nullptr;
#endif
}
LPVOID MSFileSystemForDisk::MapViewOfFile(HANDLE hFileMappingObject,
DWORD dwDesiredAccess,
DWORD dwFileOffsetHigh,
DWORD dwFileOffsetLow,
SIZE_T dwNumberOfBytesToMap) throw() {
#ifdef _WIN32
return ::MapViewOfFile(hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh,
dwFileOffsetLow, dwNumberOfBytesToMap);
#else
assert(false && "Not implemented for Unix");
return nullptr;
#endif
}
BOOL MSFileSystemForDisk::UnmapViewOfFile(LPCVOID lpBaseAddress) throw() {
#ifdef _WIN32
return ::UnmapViewOfFile(lpBaseAddress);
#else
assert(false && "Not implemented for Unix");
return false;
#endif
}
bool MSFileSystemForDisk::FileDescriptorIsDisplayed(int fd) throw() {
#ifdef _WIN32
DWORD Mode; // Unused
return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &Mode) != 0);
#else
assert(false && "Not implemented for Unix");
return false;
#endif
}
unsigned MSFileSystemForDisk::GetColumnCount(DWORD nStdHandle) throw() {
#ifdef _WIN32
unsigned Columns = 0;
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (::GetConsoleScreenBufferInfo(GetStdHandle(nStdHandle), &csbi))
Columns = csbi.dwSize.X;
return Columns;
#else
assert(false && "Not implemented for Unix");
return 0;
#endif
}
unsigned MSFileSystemForDisk::GetConsoleOutputTextAttributes() throw() {
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (::GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
return csbi.wAttributes;
return 0;
#else
assert(false && "Not implemented for Unix");
return 0;
#endif
}
void MSFileSystemForDisk::SetConsoleOutputTextAttributes(
unsigned attributes) throw() {
#ifdef _WIN32
::SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), attributes);
#else
assert(false && "Not implemented for Unix");
#endif
}
void MSFileSystemForDisk::ResetConsoleOutputTextAttributes() throw() {
#ifdef _WIN32
::SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
_defaultAttributes);
#else
assert(false && "Not implemented for Unix");
#endif
}
int MSFileSystemForDisk::open_osfhandle(intptr_t osfhandle, int flags) throw() {
#ifdef _WIN32
return ::_open_osfhandle(osfhandle, flags);
#else
assert(false && "Not implemented for Unix");
return 0;
#endif
}
intptr_t MSFileSystemForDisk::get_osfhandle(int fd) throw() {
#ifdef _WIN32
return ::_get_osfhandle(fd);
#else
assert(false && "Not implemented for Unix");
return 0;
#endif
}
int MSFileSystemForDisk::close(int fd) throw() {
#ifdef _WIN32
return ::_close(fd);
#else
return ::close(fd);
#endif
}
long MSFileSystemForDisk::lseek(int fd, long offset, int origin) throw() {
#ifdef _WIN32
return ::_lseek(fd, offset, origin);
#else
return ::lseek(fd, offset, origin);
#endif
}
int MSFileSystemForDisk::setmode(int fd, int mode) throw() {
#ifdef _WIN32
return ::_setmode(fd, mode);
#else
assert(false && "Not implemented for Unix");
return 0;
#endif
}
errno_t MSFileSystemForDisk::resize_file(LPCWSTR path, uint64_t size) throw() {
#ifdef _WIN32
int fd = ::_wopen(path, O_BINARY | _O_RDWR, S_IWRITE);
if (fd == -1)
return errno;
#ifdef HAVE__CHSIZE_S
errno_t error = ::_chsize_s(fd, size);
#else
errno_t error = ::_chsize(fd, size);
#endif
::_close(fd);
return error;
#else
assert(false && "Not implemented for Unix");
return 0;
#endif
}
int MSFileSystemForDisk::Read(int fd, void *buffer,
unsigned int count) throw() {
#ifdef _WIN32
return ::_read(fd, buffer, count);
#else
return ::read(fd, buffer, count);
#endif
}
int MSFileSystemForDisk::Write(int fd, const void *buffer,
unsigned int count) throw() {
#ifdef _WIN32
return ::_write(fd, buffer, count);
#else
return ::write(fd, buffer, count);
#endif
}
#ifndef _WIN32
int MSFileSystemForDisk::Open(const char *lpFileName, int flags,
mode_t mode) throw() {
return ::open(lpFileName, flags, mode);
}
int MSFileSystemForDisk::Stat(const char *lpFileName,
struct stat *Status) throw() {
return ::stat(lpFileName, Status);
}
int MSFileSystemForDisk::Fstat(int FD, struct stat *Status) throw() {
return ::fstat(FD, Status);
}
#endif
} // end namespace fs
} // end namespace sys
} // end namespace llvm
///////////////////////////////////////////////////////////////////////////////////////////////////
// Externally visible functions.
HRESULT
CreateMSFileSystemForDisk(::llvm::sys::fs::MSFileSystem **pResult) throw() {
*pResult = new (std::nothrow)::llvm::sys::fs::MSFileSystemForDisk();
return (*pResult != nullptr) ? S_OK : E_OUTOFMEMORY;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilContainer/D3DReflectionStrings.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// D3DReflectionStrings.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Used to convert reflection data types into strings. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/Test/D3DReflectionStrings.h"
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/Support/Global.h"
// Remove this workaround once newer version of d3dcommon.h can be compiled
// against
#define ADD_16_64_BIT_TYPES
#define ADD_SVC_BIT_FIELD
namespace hlsl {
namespace dump {
// ToString functions for D3D types
LPCSTR ToString(D3D_CBUFFER_TYPE CBType) {
switch (CBType) {
case D3D_CT_CBUFFER:
return "D3D_CT_CBUFFER";
case D3D_CT_TBUFFER:
return "D3D_CT_TBUFFER";
case D3D_CT_INTERFACE_POINTERS:
return "D3D_CT_INTERFACE_POINTERS";
case D3D_CT_RESOURCE_BIND_INFO:
return "D3D_CT_RESOURCE_BIND_INFO";
default:
return nullptr;
}
}
LPCSTR ToString(D3D_SHADER_INPUT_TYPE Type) {
switch ((UINT32)Type) {
case D3D_SIT_CBUFFER:
return "D3D_SIT_CBUFFER";
case D3D_SIT_TBUFFER:
return "D3D_SIT_TBUFFER";
case D3D_SIT_TEXTURE:
return "D3D_SIT_TEXTURE";
case D3D_SIT_SAMPLER:
return "D3D_SIT_SAMPLER";
case D3D_SIT_UAV_RWTYPED:
return "D3D_SIT_UAV_RWTYPED";
case D3D_SIT_STRUCTURED:
return "D3D_SIT_STRUCTURED";
case D3D_SIT_UAV_RWSTRUCTURED:
return "D3D_SIT_UAV_RWSTRUCTURED";
case D3D_SIT_BYTEADDRESS:
return "D3D_SIT_BYTEADDRESS";
case D3D_SIT_UAV_RWBYTEADDRESS:
return "D3D_SIT_UAV_RWBYTEADDRESS";
case D3D_SIT_UAV_APPEND_STRUCTURED:
return "D3D_SIT_UAV_APPEND_STRUCTURED";
case D3D_SIT_UAV_CONSUME_STRUCTURED:
return "D3D_SIT_UAV_CONSUME_STRUCTURED";
case D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER:
return "D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER";
case (D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER + 1):
return "D3D_SIT_RTACCELERATIONSTRUCTURE";
case (D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER + 2):
return "D3D_SIT_UAV_FEEDBACKTEXTURE";
default:
return nullptr;
}
}
LPCSTR ToString(D3D_RESOURCE_RETURN_TYPE ReturnType) {
switch (ReturnType) {
case D3D_RETURN_TYPE_UNORM:
return "D3D_RETURN_TYPE_UNORM";
case D3D_RETURN_TYPE_SNORM:
return "D3D_RETURN_TYPE_SNORM";
case D3D_RETURN_TYPE_SINT:
return "D3D_RETURN_TYPE_SINT";
case D3D_RETURN_TYPE_UINT:
return "D3D_RETURN_TYPE_UINT";
case D3D_RETURN_TYPE_FLOAT:
return "D3D_RETURN_TYPE_FLOAT";
case D3D_RETURN_TYPE_MIXED:
return "D3D_RETURN_TYPE_MIXED";
case D3D_RETURN_TYPE_DOUBLE:
return "D3D_RETURN_TYPE_DOUBLE";
case D3D_RETURN_TYPE_CONTINUED:
return "D3D_RETURN_TYPE_CONTINUED";
default:
return nullptr;
}
}
LPCSTR ToString(D3D_SRV_DIMENSION Dimension) {
switch (Dimension) {
case D3D_SRV_DIMENSION_UNKNOWN:
return "D3D_SRV_DIMENSION_UNKNOWN";
case D3D_SRV_DIMENSION_BUFFER:
return "D3D_SRV_DIMENSION_BUFFER";
case D3D_SRV_DIMENSION_TEXTURE1D:
return "D3D_SRV_DIMENSION_TEXTURE1D";
case D3D_SRV_DIMENSION_TEXTURE1DARRAY:
return "D3D_SRV_DIMENSION_TEXTURE1DARRAY";
case D3D_SRV_DIMENSION_TEXTURE2D:
return "D3D_SRV_DIMENSION_TEXTURE2D";
case D3D_SRV_DIMENSION_TEXTURE2DARRAY:
return "D3D_SRV_DIMENSION_TEXTURE2DARRAY";
case D3D_SRV_DIMENSION_TEXTURE2DMS:
return "D3D_SRV_DIMENSION_TEXTURE2DMS";
case D3D_SRV_DIMENSION_TEXTURE2DMSARRAY:
return "D3D_SRV_DIMENSION_TEXTURE2DMSARRAY";
case D3D_SRV_DIMENSION_TEXTURE3D:
return "D3D_SRV_DIMENSION_TEXTURE3D";
case D3D_SRV_DIMENSION_TEXTURECUBE:
return "D3D_SRV_DIMENSION_TEXTURECUBE";
case D3D_SRV_DIMENSION_TEXTURECUBEARRAY:
return "D3D_SRV_DIMENSION_TEXTURECUBEARRAY";
case D3D_SRV_DIMENSION_BUFFEREX:
return "D3D_SRV_DIMENSION_BUFFEREX";
default:
return nullptr;
}
}
LPCSTR ToString(D3D_PRIMITIVE_TOPOLOGY GSOutputTopology) {
switch (GSOutputTopology) {
case D3D_PRIMITIVE_TOPOLOGY_UNDEFINED:
return "D3D_PRIMITIVE_TOPOLOGY_UNDEFINED";
case D3D_PRIMITIVE_TOPOLOGY_POINTLIST:
return "D3D_PRIMITIVE_TOPOLOGY_POINTLIST";
case D3D_PRIMITIVE_TOPOLOGY_LINELIST:
return "D3D_PRIMITIVE_TOPOLOGY_LINELIST";
case D3D_PRIMITIVE_TOPOLOGY_LINESTRIP:
return "D3D_PRIMITIVE_TOPOLOGY_LINESTRIP";
case D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST:
return "D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST";
case D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP:
return "D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP";
case D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ:
return "D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ";
case D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ:
return "D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ";
case D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ:
return "D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ";
case D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ:
return "D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ";
case D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST";
case D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST:
return "D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST";
default:
return nullptr;
}
}
LPCSTR ToString(D3D_PRIMITIVE InputPrimitive) {
switch (InputPrimitive) {
case D3D_PRIMITIVE_UNDEFINED:
return "D3D_PRIMITIVE_UNDEFINED";
case D3D_PRIMITIVE_POINT:
return "D3D_PRIMITIVE_POINT";
case D3D_PRIMITIVE_LINE:
return "D3D_PRIMITIVE_LINE";
case D3D_PRIMITIVE_TRIANGLE:
return "D3D_PRIMITIVE_TRIANGLE";
case D3D_PRIMITIVE_LINE_ADJ:
return "D3D_PRIMITIVE_LINE_ADJ";
case D3D_PRIMITIVE_TRIANGLE_ADJ:
return "D3D_PRIMITIVE_TRIANGLE_ADJ";
case D3D_PRIMITIVE_1_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_1_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_2_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_2_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_3_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_3_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_4_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_4_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_5_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_5_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_6_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_6_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_7_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_7_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_8_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_8_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_9_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_9_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_10_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_10_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_11_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_11_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_12_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_12_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_13_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_13_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_14_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_14_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_15_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_15_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_16_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_16_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_17_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_17_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_18_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_18_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_19_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_19_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_20_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_20_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_21_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_21_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_22_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_22_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_23_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_23_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_24_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_24_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_25_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_25_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_26_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_26_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_27_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_27_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_28_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_28_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_29_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_29_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_30_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_30_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_31_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_31_CONTROL_POINT_PATCH";
case D3D_PRIMITIVE_32_CONTROL_POINT_PATCH:
return "D3D_PRIMITIVE_32_CONTROL_POINT_PATCH";
default:
return nullptr;
}
}
LPCSTR ToString(D3D_TESSELLATOR_OUTPUT_PRIMITIVE HSOutputPrimitive) {
switch (HSOutputPrimitive) {
case D3D_TESSELLATOR_OUTPUT_UNDEFINED:
return "D3D_TESSELLATOR_OUTPUT_UNDEFINED";
case D3D_TESSELLATOR_OUTPUT_POINT:
return "D3D_TESSELLATOR_OUTPUT_POINT";
case D3D_TESSELLATOR_OUTPUT_LINE:
return "D3D_TESSELLATOR_OUTPUT_LINE";
case D3D_TESSELLATOR_OUTPUT_TRIANGLE_CW:
return "D3D_TESSELLATOR_OUTPUT_TRIANGLE_CW";
case D3D_TESSELLATOR_OUTPUT_TRIANGLE_CCW:
return "D3D_TESSELLATOR_OUTPUT_TRIANGLE_CCW";
default:
return nullptr;
}
}
LPCSTR ToString(D3D_TESSELLATOR_PARTITIONING HSPartitioning) {
switch (HSPartitioning) {
case D3D_TESSELLATOR_PARTITIONING_UNDEFINED:
return "D3D_TESSELLATOR_PARTITIONING_UNDEFINED";
case D3D_TESSELLATOR_PARTITIONING_INTEGER:
return "D3D_TESSELLATOR_PARTITIONING_INTEGER";
case D3D_TESSELLATOR_PARTITIONING_POW2:
return "D3D_TESSELLATOR_PARTITIONING_POW2";
case D3D_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD:
return "D3D_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD";
case D3D_TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN:
return "D3D_TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN";
default:
return nullptr;
}
}
LPCSTR ToString(D3D_TESSELLATOR_DOMAIN TessellatorDomain) {
switch (TessellatorDomain) {
case D3D_TESSELLATOR_DOMAIN_UNDEFINED:
return "D3D_TESSELLATOR_DOMAIN_UNDEFINED";
case D3D_TESSELLATOR_DOMAIN_ISOLINE:
return "D3D_TESSELLATOR_DOMAIN_ISOLINE";
case D3D_TESSELLATOR_DOMAIN_TRI:
return "D3D_TESSELLATOR_DOMAIN_TRI";
case D3D_TESSELLATOR_DOMAIN_QUAD:
return "D3D_TESSELLATOR_DOMAIN_QUAD";
default:
return nullptr;
}
}
#ifdef ADD_SVC_BIT_FIELD
// Disable warning about value not being valid in enum
#pragma warning(disable : 4063)
// FIXME: remove the define once D3D_SVC_BIT_FIELD added into
// D3D_SHADER_VARIABLE_CLASS.
#define D3D_SVC_BIT_FIELD \
((D3D_SHADER_VARIABLE_CLASS)(D3D_SVC_INTERFACE_POINTER + 1))
#endif
LPCSTR ToString(D3D_SHADER_VARIABLE_CLASS Class) {
switch (Class) {
case D3D_SVC_SCALAR:
return "D3D_SVC_SCALAR";
case D3D_SVC_VECTOR:
return "D3D_SVC_VECTOR";
case D3D_SVC_MATRIX_ROWS:
return "D3D_SVC_MATRIX_ROWS";
case D3D_SVC_MATRIX_COLUMNS:
return "D3D_SVC_MATRIX_COLUMNS";
case D3D_SVC_OBJECT:
return "D3D_SVC_OBJECT";
case D3D_SVC_STRUCT:
return "D3D_SVC_STRUCT";
case D3D_SVC_INTERFACE_CLASS:
return "D3D_SVC_INTERFACE_CLASS";
case D3D_SVC_INTERFACE_POINTER:
return "D3D_SVC_INTERFACE_POINTER";
case D3D_SVC_BIT_FIELD:
return "D3D_SVC_BIT_FIELD";
default:
return nullptr;
}
}
#ifdef ADD_16_64_BIT_TYPES
// Disable warning about value not being valid in enum
#pragma warning(disable : 4063)
#define D3D_SVT_INT16 ((D3D_SHADER_VARIABLE_TYPE)58)
#define D3D_SVT_UINT16 ((D3D_SHADER_VARIABLE_TYPE)59)
#define D3D_SVT_FLOAT16 ((D3D_SHADER_VARIABLE_TYPE)60)
#define D3D_SVT_INT64 ((D3D_SHADER_VARIABLE_TYPE)61)
#define D3D_SVT_UINT64 ((D3D_SHADER_VARIABLE_TYPE)62)
#endif // ADD_16_64_BIT_TYPES
LPCSTR ToString(D3D_SHADER_VARIABLE_TYPE Type) {
switch (Type) {
case D3D_SVT_VOID:
return "D3D_SVT_VOID";
case D3D_SVT_BOOL:
return "D3D_SVT_BOOL";
case D3D_SVT_INT:
return "D3D_SVT_INT";
case D3D_SVT_FLOAT:
return "D3D_SVT_FLOAT";
case D3D_SVT_STRING:
return "D3D_SVT_STRING";
case D3D_SVT_TEXTURE:
return "D3D_SVT_TEXTURE";
case D3D_SVT_TEXTURE1D:
return "D3D_SVT_TEXTURE1D";
case D3D_SVT_TEXTURE2D:
return "D3D_SVT_TEXTURE2D";
case D3D_SVT_TEXTURE3D:
return "D3D_SVT_TEXTURE3D";
case D3D_SVT_TEXTURECUBE:
return "D3D_SVT_TEXTURECUBE";
case D3D_SVT_SAMPLER:
return "D3D_SVT_SAMPLER";
case D3D_SVT_SAMPLER1D:
return "D3D_SVT_SAMPLER1D";
case D3D_SVT_SAMPLER2D:
return "D3D_SVT_SAMPLER2D";
case D3D_SVT_SAMPLER3D:
return "D3D_SVT_SAMPLER3D";
case D3D_SVT_SAMPLERCUBE:
return "D3D_SVT_SAMPLERCUBE";
case D3D_SVT_PIXELSHADER:
return "D3D_SVT_PIXELSHADER";
case D3D_SVT_VERTEXSHADER:
return "D3D_SVT_VERTEXSHADER";
case D3D_SVT_PIXELFRAGMENT:
return "D3D_SVT_PIXELFRAGMENT";
case D3D_SVT_VERTEXFRAGMENT:
return "D3D_SVT_VERTEXFRAGMENT";
case D3D_SVT_UINT:
return "D3D_SVT_UINT";
case D3D_SVT_UINT8:
return "D3D_SVT_UINT8";
case D3D_SVT_GEOMETRYSHADER:
return "D3D_SVT_GEOMETRYSHADER";
case D3D_SVT_RASTERIZER:
return "D3D_SVT_RASTERIZER";
case D3D_SVT_DEPTHSTENCIL:
return "D3D_SVT_DEPTHSTENCIL";
case D3D_SVT_BLEND:
return "D3D_SVT_BLEND";
case D3D_SVT_BUFFER:
return "D3D_SVT_BUFFER";
case D3D_SVT_CBUFFER:
return "D3D_SVT_CBUFFER";
case D3D_SVT_TBUFFER:
return "D3D_SVT_TBUFFER";
case D3D_SVT_TEXTURE1DARRAY:
return "D3D_SVT_TEXTURE1DARRAY";
case D3D_SVT_TEXTURE2DARRAY:
return "D3D_SVT_TEXTURE2DARRAY";
case D3D_SVT_RENDERTARGETVIEW:
return "D3D_SVT_RENDERTARGETVIEW";
case D3D_SVT_DEPTHSTENCILVIEW:
return "D3D_SVT_DEPTHSTENCILVIEW";
case D3D_SVT_TEXTURE2DMS:
return "D3D_SVT_TEXTURE2DMS";
case D3D_SVT_TEXTURE2DMSARRAY:
return "D3D_SVT_TEXTURE2DMSARRAY";
case D3D_SVT_TEXTURECUBEARRAY:
return "D3D_SVT_TEXTURECUBEARRAY";
case D3D_SVT_HULLSHADER:
return "D3D_SVT_HULLSHADER";
case D3D_SVT_DOMAINSHADER:
return "D3D_SVT_DOMAINSHADER";
case D3D_SVT_INTERFACE_POINTER:
return "D3D_SVT_INTERFACE_POINTER";
case D3D_SVT_COMPUTESHADER:
return "D3D_SVT_COMPUTESHADER";
case D3D_SVT_DOUBLE:
return "D3D_SVT_DOUBLE";
case D3D_SVT_RWTEXTURE1D:
return "D3D_SVT_RWTEXTURE1D";
case D3D_SVT_RWTEXTURE1DARRAY:
return "D3D_SVT_RWTEXTURE1DARRAY";
case D3D_SVT_RWTEXTURE2D:
return "D3D_SVT_RWTEXTURE2D";
case D3D_SVT_RWTEXTURE2DARRAY:
return "D3D_SVT_RWTEXTURE2DARRAY";
case D3D_SVT_RWTEXTURE3D:
return "D3D_SVT_RWTEXTURE3D";
case D3D_SVT_RWBUFFER:
return "D3D_SVT_RWBUFFER";
case D3D_SVT_BYTEADDRESS_BUFFER:
return "D3D_SVT_BYTEADDRESS_BUFFER";
case D3D_SVT_RWBYTEADDRESS_BUFFER:
return "D3D_SVT_RWBYTEADDRESS_BUFFER";
case D3D_SVT_STRUCTURED_BUFFER:
return "D3D_SVT_STRUCTURED_BUFFER";
case D3D_SVT_RWSTRUCTURED_BUFFER:
return "D3D_SVT_RWSTRUCTURED_BUFFER";
case D3D_SVT_APPEND_STRUCTURED_BUFFER:
return "D3D_SVT_APPEND_STRUCTURED_BUFFER";
case D3D_SVT_CONSUME_STRUCTURED_BUFFER:
return "D3D_SVT_CONSUME_STRUCTURED_BUFFER";
case D3D_SVT_MIN8FLOAT:
return "D3D_SVT_MIN8FLOAT";
case D3D_SVT_MIN10FLOAT:
return "D3D_SVT_MIN10FLOAT";
case D3D_SVT_MIN16FLOAT:
return "D3D_SVT_MIN16FLOAT";
case D3D_SVT_MIN12INT:
return "D3D_SVT_MIN12INT";
case D3D_SVT_MIN16INT:
return "D3D_SVT_MIN16INT";
case D3D_SVT_MIN16UINT:
return "D3D_SVT_MIN16UINT";
case D3D_SVT_INT16:
return "D3D_SVT_INT16";
case D3D_SVT_UINT16:
return "D3D_SVT_UINT16";
case D3D_SVT_FLOAT16:
return "D3D_SVT_FLOAT16";
case D3D_SVT_INT64:
return "D3D_SVT_INT64";
case D3D_SVT_UINT64:
return "D3D_SVT_UINT64";
default:
return nullptr;
}
}
LPCSTR ToString(D3D_SHADER_VARIABLE_FLAGS Flag) {
switch (Flag) {
case D3D_SVF_USERPACKED:
return "D3D_SVF_USERPACKED";
case D3D_SVF_USED:
return "D3D_SVF_USED";
case D3D_SVF_INTERFACE_POINTER:
return "D3D_SVF_INTERFACE_POINTER";
case D3D_SVF_INTERFACE_PARAMETER:
return "D3D_SVF_INTERFACE_PARAMETER";
}
return nullptr;
}
LPCSTR ToString(D3D_SHADER_INPUT_FLAGS Flag) {
switch (Flag) {
case D3D_SIF_USERPACKED:
return "D3D_SIF_USERPACKED";
case D3D_SIF_COMPARISON_SAMPLER:
return "D3D_SIF_COMPARISON_SAMPLER";
case D3D_SIF_TEXTURE_COMPONENT_0:
return "D3D_SIF_TEXTURE_COMPONENT_0";
case D3D_SIF_TEXTURE_COMPONENT_1:
return "D3D_SIF_TEXTURE_COMPONENT_1";
case D3D_SIF_TEXTURE_COMPONENTS:
return "D3D_SIF_TEXTURE_COMPONENTS";
case D3D_SIF_UNUSED:
return "D3D_SIF_UNUSED";
}
return nullptr;
}
LPCSTR ToString(D3D_SHADER_CBUFFER_FLAGS Flag) {
switch (Flag) {
case D3D_CBF_USERPACKED:
return "D3D_CBF_USERPACKED";
}
return nullptr;
}
LPCSTR ToString(D3D_PARAMETER_FLAGS Flag) {
switch (Flag) {
case D3D_PF_IN:
return "D3D_PF_IN";
case D3D_PF_OUT:
return "D3D_PF_OUT";
}
return nullptr;
}
#ifndef D3D_NAME_SHADINGRATE
#define D3D_NAME_SHADINGRATE \
((D3D_NAME)hlsl::DxilProgramSigSemantic::ShadingRate)
#endif
#ifndef D3D_NAME_CULLPRIMITIVE
#define D3D_NAME_CULLPRIMITIVE \
((D3D_NAME)hlsl::DxilProgramSigSemantic::CullPrimitive)
#endif
LPCSTR ToString(D3D_NAME Name) {
switch (Name) {
case D3D_NAME_UNDEFINED:
return "D3D_NAME_UNDEFINED";
case D3D_NAME_POSITION:
return "D3D_NAME_POSITION";
case D3D_NAME_CLIP_DISTANCE:
return "D3D_NAME_CLIP_DISTANCE";
case D3D_NAME_CULL_DISTANCE:
return "D3D_NAME_CULL_DISTANCE";
case D3D_NAME_RENDER_TARGET_ARRAY_INDEX:
return "D3D_NAME_RENDER_TARGET_ARRAY_INDEX";
case D3D_NAME_VIEWPORT_ARRAY_INDEX:
return "D3D_NAME_VIEWPORT_ARRAY_INDEX";
case D3D_NAME_VERTEX_ID:
return "D3D_NAME_VERTEX_ID";
case D3D_NAME_PRIMITIVE_ID:
return "D3D_NAME_PRIMITIVE_ID";
case D3D_NAME_INSTANCE_ID:
return "D3D_NAME_INSTANCE_ID";
case D3D_NAME_IS_FRONT_FACE:
return "D3D_NAME_IS_FRONT_FACE";
case D3D_NAME_SAMPLE_INDEX:
return "D3D_NAME_SAMPLE_INDEX";
case D3D_NAME_FINAL_QUAD_EDGE_TESSFACTOR:
return "D3D_NAME_FINAL_QUAD_EDGE_TESSFACTOR";
case D3D_NAME_FINAL_QUAD_INSIDE_TESSFACTOR:
return "D3D_NAME_FINAL_QUAD_INSIDE_TESSFACTOR";
case D3D_NAME_FINAL_TRI_EDGE_TESSFACTOR:
return "D3D_NAME_FINAL_TRI_EDGE_TESSFACTOR";
case D3D_NAME_FINAL_TRI_INSIDE_TESSFACTOR:
return "D3D_NAME_FINAL_TRI_INSIDE_TESSFACTOR";
case D3D_NAME_FINAL_LINE_DETAIL_TESSFACTOR:
return "D3D_NAME_FINAL_LINE_DETAIL_TESSFACTOR";
case D3D_NAME_FINAL_LINE_DENSITY_TESSFACTOR:
return "D3D_NAME_FINAL_LINE_DENSITY_TESSFACTOR";
case D3D_NAME_BARYCENTRICS:
return "D3D_NAME_BARYCENTRICS";
case D3D_NAME_TARGET:
return "D3D_NAME_TARGET";
case D3D_NAME_DEPTH:
return "D3D_NAME_DEPTH";
case D3D_NAME_COVERAGE:
return "D3D_NAME_COVERAGE";
case D3D_NAME_DEPTH_GREATER_EQUAL:
return "D3D_NAME_DEPTH_GREATER_EQUAL";
case D3D_NAME_DEPTH_LESS_EQUAL:
return "D3D_NAME_DEPTH_LESS_EQUAL";
case D3D_NAME_STENCIL_REF:
return "D3D_NAME_STENCIL_REF";
case D3D_NAME_INNER_COVERAGE:
return "D3D_NAME_INNER_COVERAGE";
case D3D_NAME_SHADINGRATE:
return "D3D_NAME_SHADINGRATE";
case D3D_NAME_CULLPRIMITIVE:
return "D3D_NAME_CULLPRIMITIVE";
}
return nullptr;
}
LPCSTR ToString(D3D_REGISTER_COMPONENT_TYPE CompTy) {
switch (CompTy) {
case D3D_REGISTER_COMPONENT_UNKNOWN:
return "D3D_REGISTER_COMPONENT_UNKNOWN";
case D3D_REGISTER_COMPONENT_UINT32:
return "D3D_REGISTER_COMPONENT_UINT32";
case D3D_REGISTER_COMPONENT_SINT32:
return "D3D_REGISTER_COMPONENT_SINT32";
case D3D_REGISTER_COMPONENT_FLOAT32:
return "D3D_REGISTER_COMPONENT_FLOAT32";
}
return nullptr;
}
LPCSTR ToString(D3D_MIN_PRECISION MinPrec) {
switch (MinPrec) {
case D3D_MIN_PRECISION_DEFAULT:
return "D3D_MIN_PRECISION_DEFAULT";
case D3D_MIN_PRECISION_FLOAT_16:
return "D3D_MIN_PRECISION_FLOAT_16";
case D3D_MIN_PRECISION_FLOAT_2_8:
return "D3D_MIN_PRECISION_FLOAT_2_8";
case D3D_MIN_PRECISION_RESERVED:
return "D3D_MIN_PRECISION_RESERVED";
case D3D_MIN_PRECISION_SINT_16:
return "D3D_MIN_PRECISION_SINT_16";
case D3D_MIN_PRECISION_UINT_16:
return "D3D_MIN_PRECISION_UINT_16";
case D3D_MIN_PRECISION_ANY_16:
return "D3D_MIN_PRECISION_ANY_16";
case D3D_MIN_PRECISION_ANY_10:
return "D3D_MIN_PRECISION_ANY_10";
}
return nullptr;
}
LPCSTR CompMaskToString(unsigned CompMask) {
static const LPCSTR masks[16] = {
"----", "x---", "-y--", "xy--", "--z-", "x-z-", "-yz-", "xyz-",
"---w", "x--w", "-y-w", "xy-w", "--zw", "x-zw", "-yzw", "xyzw"};
if (CompMask < 16) {
return masks[CompMask];
}
return "<invalid mask>";
}
// These macros define the implementation of the DXC ToString functions
#define DEF_RDAT_ENUMS DEF_RDAT_DUMP_IMPL
#define DEF_DXIL_ENUMS DEF_RDAT_DUMP_IMPL
#include "dxc/DxilContainer/RDAT_Macros.inl"
} // namespace dump
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilContainer/D3DReflectionDumper.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// D3DReflectionDumper.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Use this to dump D3D Reflection data for testing. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/Test/D3DReflectionDumper.h"
#include "dxc/DXIL/DxilConstants.h"
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/Support/Global.h"
#include "dxc/Test/D3DReflectionStrings.h"
#include "dxc/dxcapi.h"
#include <sstream>
namespace hlsl {
namespace dump {
void D3DReflectionDumper::DumpDefaultValue(LPCVOID pDefaultValue, UINT Size) {
WriteLn("DefaultValue: ",
pDefaultValue ? "<present>" : "<nullptr>"); // TODO: Dump DefaultValue
}
void D3DReflectionDumper::DumpShaderVersion(UINT Version) {
const char *szType = "<unknown>";
UINT Type = D3D12_SHVER_GET_TYPE(Version);
switch (Type) {
case (UINT)hlsl::DXIL::ShaderKind::Pixel:
szType = "Pixel";
break;
case (UINT)hlsl::DXIL::ShaderKind::Vertex:
szType = "Vertex";
break;
case (UINT)hlsl::DXIL::ShaderKind::Geometry:
szType = "Geometry";
break;
case (UINT)hlsl::DXIL::ShaderKind::Hull:
szType = "Hull";
break;
case (UINT)hlsl::DXIL::ShaderKind::Domain:
szType = "Domain";
break;
case (UINT)hlsl::DXIL::ShaderKind::Compute:
szType = "Compute";
break;
case (UINT)hlsl::DXIL::ShaderKind::Library:
szType = "Library";
break;
case (UINT)hlsl::DXIL::ShaderKind::RayGeneration:
szType = "RayGeneration";
break;
case (UINT)hlsl::DXIL::ShaderKind::Intersection:
szType = "Intersection";
break;
case (UINT)hlsl::DXIL::ShaderKind::AnyHit:
szType = "AnyHit";
break;
case (UINT)hlsl::DXIL::ShaderKind::ClosestHit:
szType = "ClosestHit";
break;
case (UINT)hlsl::DXIL::ShaderKind::Miss:
szType = "Miss";
break;
case (UINT)hlsl::DXIL::ShaderKind::Callable:
szType = "Callable";
break;
case (UINT)hlsl::DXIL::ShaderKind::Mesh:
szType = "Mesh";
break;
case (UINT)hlsl::DXIL::ShaderKind::Amplification:
szType = "Amplification";
break;
case (UINT)hlsl::DXIL::ShaderKind::Invalid:
szType = "Invalid";
break;
}
UINT Major = D3D12_SHVER_GET_MAJOR(Version);
UINT Minor = D3D12_SHVER_GET_MINOR(Version);
WriteLn("Shader Version: ", szType, " ", Major, ".", Minor);
}
void D3DReflectionDumper::Dump(D3D12_SHADER_TYPE_DESC &tyDesc) {
SetLastName(tyDesc.Name);
WriteLn("D3D12_SHADER_TYPE_DESC: Name: ", m_LastName);
Indent();
DumpEnum("Class", tyDesc.Class);
DumpEnum("Type", tyDesc.Type);
WriteLn("Elements: ", tyDesc.Elements);
WriteLn("Rows: ", tyDesc.Rows);
WriteLn("Columns: ", tyDesc.Columns);
WriteLn("Members: ", tyDesc.Members);
WriteLn("Offset: ", tyDesc.Offset);
Dedent();
}
void D3DReflectionDumper::Dump(D3D12_SHADER_VARIABLE_DESC &varDesc) {
SetLastName(varDesc.Name);
WriteLn("D3D12_SHADER_VARIABLE_DESC: Name: ", m_LastName);
Indent();
WriteLn("Size: ", varDesc.Size);
WriteLn("StartOffset: ", varDesc.StartOffset);
WriteLn("uFlags: ", FlagsValue<D3D_SHADER_VARIABLE_FLAGS>(varDesc.uFlags));
DumpDefaultValue(varDesc.DefaultValue, varDesc.Size);
Dedent();
}
void D3DReflectionDumper::Dump(D3D12_SHADER_BUFFER_DESC &Desc) {
SetLastName(Desc.Name);
WriteLn("D3D12_SHADER_BUFFER_DESC: Name: ", m_LastName);
Indent();
DumpEnum("Type", Desc.Type);
WriteLn("Size: ", Desc.Size);
WriteLn("uFlags: ", FlagsValue<D3D_SHADER_CBUFFER_FLAGS>(Desc.uFlags));
WriteLn("Num Variables: ", Desc.Variables);
Dedent();
}
void D3DReflectionDumper::Dump(D3D12_SHADER_INPUT_BIND_DESC &resDesc) {
SetLastName(resDesc.Name);
WriteLn("D3D12_SHADER_INPUT_BIND_DESC: Name: ", m_LastName);
Indent();
DumpEnum("Type", resDesc.Type);
WriteLn("uID: ", resDesc.uID);
WriteLn("BindCount: ", resDesc.BindCount);
WriteLn("BindPoint: ", resDesc.BindPoint);
WriteLn("Space: ", resDesc.Space);
DumpEnum("ReturnType", resDesc.ReturnType);
DumpEnum("Dimension", resDesc.Dimension);
WriteLn("NumSamples (or stride): ", resDesc.NumSamples);
WriteLn("uFlags: ", FlagsValue<D3D_SHADER_INPUT_FLAGS>(resDesc.uFlags));
Dedent();
}
void D3DReflectionDumper::Dump(D3D12_SIGNATURE_PARAMETER_DESC &elDesc) {
WriteLn("D3D12_SIGNATURE_PARAMETER_DESC: SemanticName: ", elDesc.SemanticName,
" SemanticIndex: ", elDesc.SemanticIndex);
Indent();
WriteLn("Register: ", elDesc.Register);
DumpEnum("SystemValueType", elDesc.SystemValueType);
DumpEnum("ComponentType", elDesc.ComponentType);
WriteLn("Mask: ", CompMaskToString(elDesc.Mask), " (", (UINT)elDesc.Mask,
")");
WriteLn("ReadWriteMask: ", CompMaskToString(elDesc.ReadWriteMask), " (",
(UINT)elDesc.ReadWriteMask, ") (AlwaysReads/NeverWrites)");
WriteLn("Stream: ", elDesc.Stream);
DumpEnum("MinPrecision", elDesc.MinPrecision);
Dedent();
}
void D3DReflectionDumper::Dump(D3D12_SHADER_DESC &Desc) {
WriteLn("D3D12_SHADER_DESC:");
Indent();
DumpShaderVersion(Desc.Version);
WriteLn("Creator: ", Desc.Creator ? Desc.Creator : "<nullptr>");
WriteLn("Flags: ", std::hex, std::showbase,
Desc.Flags); // TODO: fxc compiler flags
WriteLn("ConstantBuffers: ", Desc.ConstantBuffers);
WriteLn("BoundResources: ", Desc.BoundResources);
WriteLn("InputParameters: ", Desc.InputParameters);
WriteLn("OutputParameters: ", Desc.OutputParameters);
hlsl::DXIL::ShaderKind ShaderKind =
(hlsl::DXIL::ShaderKind)D3D12_SHVER_GET_TYPE(Desc.Version);
if (ShaderKind == hlsl::DXIL::ShaderKind::Geometry) {
WriteLn("cGSInstanceCount: ", Desc.cGSInstanceCount);
WriteLn("GSMaxOutputVertexCount: ", Desc.GSMaxOutputVertexCount);
DumpEnum("GSOutputTopology", Desc.GSOutputTopology);
DumpEnum("InputPrimitive", Desc.InputPrimitive);
}
if (ShaderKind == hlsl::DXIL::ShaderKind::Hull) {
WriteLn("PatchConstantParameters: ", Desc.PatchConstantParameters);
WriteLn("cControlPoints: ", Desc.cControlPoints);
DumpEnum("InputPrimitive", Desc.InputPrimitive);
DumpEnum("HSOutputPrimitive", Desc.HSOutputPrimitive);
DumpEnum("HSPartitioning", Desc.HSPartitioning);
DumpEnum("TessellatorDomain", Desc.TessellatorDomain);
}
if (ShaderKind == hlsl::DXIL::ShaderKind::Domain) {
WriteLn("PatchConstantParameters: ", Desc.PatchConstantParameters);
WriteLn("cControlPoints: ", Desc.cControlPoints);
DumpEnum("TessellatorDomain", Desc.TessellatorDomain);
}
if (ShaderKind == hlsl::DXIL::ShaderKind::Mesh) {
WriteLn("PatchConstantParameters: ", Desc.PatchConstantParameters,
" (output primitive parameters for mesh shader)");
}
// Instruction Counts
WriteLn("InstructionCount: ", Desc.InstructionCount);
WriteLn("TempArrayCount: ", Desc.TempArrayCount);
WriteLn("DynamicFlowControlCount: ", Desc.DynamicFlowControlCount);
WriteLn("ArrayInstructionCount: ", Desc.ArrayInstructionCount);
WriteLn("TextureNormalInstructions: ", Desc.TextureNormalInstructions);
WriteLn("TextureLoadInstructions: ", Desc.TextureLoadInstructions);
WriteLn("TextureCompInstructions: ", Desc.TextureCompInstructions);
WriteLn("TextureBiasInstructions: ", Desc.TextureBiasInstructions);
WriteLn("TextureGradientInstructions: ", Desc.TextureGradientInstructions);
WriteLn("FloatInstructionCount: ", Desc.FloatInstructionCount);
WriteLn("IntInstructionCount: ", Desc.IntInstructionCount);
WriteLn("UintInstructionCount: ", Desc.UintInstructionCount);
WriteLn("CutInstructionCount: ", Desc.CutInstructionCount);
WriteLn("EmitInstructionCount: ", Desc.EmitInstructionCount);
WriteLn("cBarrierInstructions: ", Desc.cBarrierInstructions);
WriteLn("cInterlockedInstructions: ", Desc.cInterlockedInstructions);
WriteLn("cTextureStoreInstructions: ", Desc.cTextureStoreInstructions);
Dedent();
}
void D3DReflectionDumper::Dump(D3D12_FUNCTION_DESC &Desc) {
SetLastName(Desc.Name);
WriteLn("D3D12_FUNCTION_DESC: Name: ", EscapedString(m_LastName));
Indent();
DumpShaderVersion(Desc.Version);
WriteLn("Creator: ", Desc.Creator ? Desc.Creator : "<nullptr>");
WriteLn("Flags: ", std::hex, std::showbase, Desc.Flags);
WriteLn("RequiredFeatureFlags: ", std::hex, std::showbase,
Desc.RequiredFeatureFlags);
WriteLn("ConstantBuffers: ", Desc.ConstantBuffers);
WriteLn("BoundResources: ", Desc.BoundResources);
WriteLn("FunctionParameterCount: ", Desc.FunctionParameterCount);
WriteLn("HasReturn: ", Desc.HasReturn ? "TRUE" : "FALSE");
Dedent();
}
void D3DReflectionDumper::Dump(D3D12_LIBRARY_DESC &Desc) {
WriteLn("D3D12_LIBRARY_DESC:");
Indent();
WriteLn("Creator: ", Desc.Creator ? Desc.Creator : "<nullptr>");
WriteLn("Flags: ", std::hex, std::showbase, Desc.Flags);
WriteLn("FunctionCount: ", Desc.FunctionCount);
Dedent();
}
void D3DReflectionDumper::Dump(ID3D12ShaderReflectionType *pType) {
WriteLn("ID3D12ShaderReflectionType:");
Indent();
D3D12_SHADER_TYPE_DESC tyDesc;
if (!pType || FAILED(pType->GetDesc(&tyDesc))) {
Failure("GetDesc");
Dedent();
return;
}
Dump(tyDesc);
if (tyDesc.Members) {
WriteLn("{");
Indent();
for (UINT uMember = 0; uMember < tyDesc.Members; uMember++) {
Dump(pType->GetMemberTypeByIndex(uMember));
}
Dedent();
WriteLn("}");
}
Dedent();
}
void D3DReflectionDumper::Dump(ID3D12ShaderReflectionVariable *pVar) {
WriteLn("ID3D12ShaderReflectionVariable:");
Indent();
D3D12_SHADER_VARIABLE_DESC varDesc;
if (!pVar || FAILED(pVar->GetDesc(&varDesc))) {
Failure("GetDesc");
Dedent();
return;
}
Dump(varDesc);
Dump(pVar->GetType());
ID3D12ShaderReflectionConstantBuffer *pCB = pVar->GetBuffer();
D3D12_SHADER_BUFFER_DESC CBDesc;
if (pCB && SUCCEEDED(pCB->GetDesc(&CBDesc))) {
WriteLn("CBuffer: ", CBDesc.Name);
}
Dedent();
}
void D3DReflectionDumper::Dump(
ID3D12ShaderReflectionConstantBuffer *pCBReflection) {
WriteLn("ID3D12ShaderReflectionConstantBuffer:");
Indent();
D3D12_SHADER_BUFFER_DESC Desc;
if (!pCBReflection || FAILED(pCBReflection->GetDesc(&Desc))) {
Failure("GetDesc");
Dedent();
return;
}
Dump(Desc);
if (Desc.Variables) {
WriteLn("{");
Indent();
bool bCheckByNameFailed = false;
for (UINT uVar = 0; uVar < Desc.Variables; uVar++) {
if (m_bCheckByName)
SetLastName();
ID3D12ShaderReflectionVariable *pVar =
pCBReflection->GetVariableByIndex(uVar);
Dump(pVar);
if (m_bCheckByName) {
if (pCBReflection->GetVariableByName(m_LastName) != pVar) {
bCheckByNameFailed = true;
Failure("GetVariableByName ", m_LastName);
}
}
}
if (m_bCheckByName && !bCheckByNameFailed) {
WriteLn("GetVariableByName checks succeeded.");
}
Dedent();
WriteLn("}");
}
Dedent();
}
void D3DReflectionDumper::Dump(ID3D12ShaderReflection *pShaderReflection) {
WriteLn("ID3D12ShaderReflection:");
Indent();
D3D12_SHADER_DESC Desc;
if (!pShaderReflection || FAILED(pShaderReflection->GetDesc(&Desc))) {
Failure("GetDesc");
Dedent();
return;
}
Dump(Desc);
if (Desc.InputParameters) {
WriteLn("InputParameter Elements: ", Desc.InputParameters);
Indent();
for (UINT i = 0; i < Desc.InputParameters; ++i) {
D3D12_SIGNATURE_PARAMETER_DESC elDesc;
if (FAILED(pShaderReflection->GetInputParameterDesc(i, &elDesc))) {
Failure("GetInputParameterDesc ", i);
continue;
}
Dump(elDesc);
}
Dedent();
}
if (Desc.OutputParameters) {
WriteLn("OutputParameter Elements: ", Desc.OutputParameters);
Indent();
for (UINT i = 0; i < Desc.OutputParameters; ++i) {
D3D12_SIGNATURE_PARAMETER_DESC elDesc;
if (FAILED(pShaderReflection->GetOutputParameterDesc(i, &elDesc))) {
Failure("GetOutputParameterDesc ", i);
continue;
}
Dump(elDesc);
}
Dedent();
}
if (Desc.PatchConstantParameters) {
WriteLn("PatchConstantParameter Elements: ", Desc.PatchConstantParameters);
Indent();
for (UINT i = 0; i < Desc.PatchConstantParameters; ++i) {
D3D12_SIGNATURE_PARAMETER_DESC elDesc;
if (FAILED(
pShaderReflection->GetPatchConstantParameterDesc(i, &elDesc))) {
Failure("GetPatchConstantParameterDesc ", i);
continue;
}
Dump(elDesc);
}
Dedent();
}
if (Desc.ConstantBuffers) {
WriteLn("Constant Buffers:");
Indent();
bool bCheckByNameFailed = false;
for (UINT uCB = 0; uCB < Desc.ConstantBuffers; uCB++) {
ID3D12ShaderReflectionConstantBuffer *pCB =
pShaderReflection->GetConstantBufferByIndex(uCB);
if (!pCB) {
Failure("GetConstantBufferByIndex ", uCB);
continue;
}
Dump(pCB);
if (m_bCheckByName && m_LastName) {
if (pShaderReflection->GetConstantBufferByName(m_LastName) != pCB) {
bCheckByNameFailed = true;
Failure("GetConstantBufferByName ", m_LastName);
}
}
}
if (m_bCheckByName && !bCheckByNameFailed) {
WriteLn("GetConstantBufferByName checks succeeded.");
}
Dedent();
}
if (Desc.BoundResources) {
WriteLn("Bound Resources:");
Indent();
bool bCheckByNameFailed = false;
for (UINT uRes = 0; uRes < Desc.BoundResources; uRes++) {
D3D12_SHADER_INPUT_BIND_DESC bindDesc;
if (FAILED(pShaderReflection->GetResourceBindingDesc(uRes, &bindDesc))) {
Failure("GetResourceBindingDesc ", uRes);
continue;
}
Dump(bindDesc);
if (m_bCheckByName && bindDesc.Name) {
D3D12_SHADER_INPUT_BIND_DESC bindDesc2;
if (FAILED(pShaderReflection->GetResourceBindingDescByName(
bindDesc.Name, &bindDesc2)) ||
bindDesc2.Name != bindDesc.Name) {
bCheckByNameFailed = true;
Failure("GetResourceBindingDescByName ", bindDesc.Name);
}
}
}
if (m_bCheckByName && !bCheckByNameFailed) {
WriteLn("GetResourceBindingDescByName checks succeeded.");
}
Dedent();
}
// TODO
Dedent();
}
void D3DReflectionDumper::Dump(ID3D12FunctionReflection *pFunctionReflection) {
WriteLn("ID3D12FunctionReflection:");
Indent();
D3D12_FUNCTION_DESC Desc;
if (!pFunctionReflection || FAILED(pFunctionReflection->GetDesc(&Desc))) {
Failure("GetDesc");
Dedent();
return;
}
Dump(Desc);
if (Desc.ConstantBuffers) {
WriteLn("Constant Buffers:");
Indent();
bool bCheckByNameFailed = false;
for (UINT uCB = 0; uCB < Desc.ConstantBuffers; uCB++) {
ID3D12ShaderReflectionConstantBuffer *pCB =
pFunctionReflection->GetConstantBufferByIndex(uCB);
Dump(pCB);
if (m_bCheckByName && m_LastName) {
if (pFunctionReflection->GetConstantBufferByName(m_LastName) != pCB) {
bCheckByNameFailed = true;
Failure("GetConstantBufferByName ", m_LastName);
}
}
}
if (m_bCheckByName && !bCheckByNameFailed) {
WriteLn("GetConstantBufferByName checks succeeded.");
}
Dedent();
}
if (Desc.BoundResources) {
WriteLn("Bound Resources:");
Indent();
bool bCheckByNameFailed = false;
for (UINT uRes = 0; uRes < Desc.BoundResources; uRes++) {
D3D12_SHADER_INPUT_BIND_DESC bindDesc;
if (FAILED(
pFunctionReflection->GetResourceBindingDesc(uRes, &bindDesc))) {
}
Dump(bindDesc);
if (m_bCheckByName && bindDesc.Name) {
D3D12_SHADER_INPUT_BIND_DESC bindDesc2;
if (FAILED(pFunctionReflection->GetResourceBindingDescByName(
bindDesc.Name, &bindDesc2)) ||
bindDesc2.Name != bindDesc.Name) {
bCheckByNameFailed = true;
Failure("GetResourceBindingDescByName ", bindDesc.Name);
}
}
}
if (m_bCheckByName && !bCheckByNameFailed) {
WriteLn("GetResourceBindingDescByName checks succeeded.");
}
Dedent();
}
// TODO
Dedent();
}
void D3DReflectionDumper::Dump(ID3D12LibraryReflection *pLibraryReflection) {
WriteLn("ID3D12LibraryReflection:");
Indent();
D3D12_LIBRARY_DESC Desc;
if (!pLibraryReflection || FAILED(pLibraryReflection->GetDesc(&Desc))) {
Failure("GetDesc");
Dedent();
return;
}
Dump(Desc);
if (Desc.FunctionCount) {
for (UINT uFunc = 0; uFunc < Desc.FunctionCount; uFunc++)
Dump(pLibraryReflection->GetFunctionByIndex((INT)uFunc));
}
Dedent();
}
} // namespace dump
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilContainer/DxilRDATBuilder.cpp | #include "dxc/DxilContainer/DxilRDATBuilder.h"
#include "dxc/DxilContainer/DxilPipelineStateValidation.h"
#include "dxc/Support/FileIOHelper.h"
#include "dxc/Support/Global.h"
using namespace llvm;
using namespace hlsl;
using namespace RDAT;
void RDATTable::SetRecordStride(size_t RecordStride) {
DXASSERT(m_rows.empty(), "record stride is fixed for the entire table");
m_RecordStride = RecordStride;
}
uint32_t RDATTable::InsertImpl(const void *ptr, size_t size) {
IFTBOOL(m_RecordStride <= size, DXC_E_GENERAL_INTERNAL_ERROR);
size_t count = m_rows.size();
if (count < (UINT32_MAX - 1)) {
const char *pData = (const char *)ptr;
auto result = m_map.insert(
std::make_pair(std::string(pData, pData + m_RecordStride), count));
if (!m_bDeduplicationEnabled || result.second) {
m_rows.emplace_back(result.first->first);
return count;
} else {
return result.first->second;
}
}
return RDAT_NULL_REF;
}
void RDATTable::Write(void *ptr) {
char *pCur = (char *)ptr;
RuntimeDataTableHeader &header =
*reinterpret_cast<RuntimeDataTableHeader *>(pCur);
header.RecordCount = m_rows.size();
header.RecordStride = m_RecordStride;
pCur += sizeof(RuntimeDataTableHeader);
for (auto &record : m_rows) {
DXASSERT_NOMSG(record.size() == m_RecordStride);
memcpy(pCur, record.data(), m_RecordStride);
pCur += m_RecordStride;
}
};
uint32_t RDATTable::GetPartSize() const {
if (m_rows.empty())
return 0;
return sizeof(RuntimeDataTableHeader) + m_rows.size() * m_RecordStride;
}
uint32_t RawBytesPart::Insert(const void *pData, size_t dataSize) {
auto result = m_Map.insert(std::make_pair(
std::string((const char *)pData, (const char *)pData + dataSize),
m_Size));
auto iterator = result.first;
if (result.second) {
const std::string &key = iterator->first;
m_List.push_back(llvm::StringRef(key.data(), key.size()));
m_Size += key.size();
}
return iterator->second;
}
void RawBytesPart::Write(void *ptr) {
for (llvm::StringRef &entry : m_List) {
memcpy(ptr, entry.data(), entry.size());
ptr = (char *)ptr + entry.size();
}
}
DxilRDATBuilder::DxilRDATBuilder(bool allowRecordDuplication)
: m_bRecordDeduplicationEnabled(allowRecordDuplication) {}
DxilRDATBuilder::SizeInfo DxilRDATBuilder::ComputeSize() const {
uint32_t totalSizeOfNonEmptyParts = 0;
uint32_t numNonEmptyParts = 0;
for (auto &part : m_Parts) {
if (part->GetPartSize() == 0)
continue;
numNonEmptyParts++;
totalSizeOfNonEmptyParts +=
sizeof(RuntimeDataPartHeader) + PSVALIGN4(part->GetPartSize());
}
uint32_t total = sizeof(RuntimeDataHeader) + // Header
numNonEmptyParts * sizeof(uint32_t) + // Offset array
totalSizeOfNonEmptyParts; // Parts contents
SizeInfo ret = {};
ret.numParts = numNonEmptyParts;
ret.sizeInBytes = total;
return ret;
}
namespace {
// Size-checked writer
// on overrun: throw buffer_overrun{};
// on overlap: throw buffer_overlap{};
class CheckedWriter {
char *Ptr;
size_t Size;
size_t Offset;
public:
class exception : public std::exception {};
class buffer_overrun : public exception {
public:
buffer_overrun() noexcept {}
virtual const char *what() const noexcept override {
return ("buffer_overrun");
}
};
class buffer_overlap : public exception {
public:
buffer_overlap() noexcept {}
virtual const char *what() const noexcept override {
return ("buffer_overlap");
}
};
CheckedWriter(void *ptr, size_t size)
: Ptr(reinterpret_cast<char *>(ptr)), Size(size), Offset(0) {}
size_t GetOffset() const { return Offset; }
void Reset(size_t offset = 0) {
if (offset >= Size)
throw buffer_overrun{};
Offset = offset;
}
// offset is absolute, ensure offset is >= current offset
void Advance(size_t offset = 0) {
if (offset < Offset)
throw buffer_overlap{};
if (offset >= Size)
throw buffer_overrun{};
Offset = offset;
}
void CheckBounds(size_t size) const {
assert(Offset <= Size && "otherwise, offset larger than size");
if (size > Size - Offset)
throw buffer_overrun{};
}
template <typename T> T *Cast(size_t size = 0) {
if (0 == size)
size = sizeof(T);
CheckBounds(size);
return reinterpret_cast<T *>(Ptr + Offset);
}
// Map and Write advance Offset:
template <typename T> T &Map() {
const size_t size = sizeof(T);
T *p = Cast<T>(size);
Offset += size;
return *p;
}
template <typename T> T *MapArray(size_t count = 1) {
const size_t size = sizeof(T) * count;
T *p = Cast<T>(size);
Offset += size;
return p;
}
template <typename T> void Write(const T &obj) {
const size_t size = sizeof(T);
*Cast<T>(size) = obj;
Offset += size;
}
template <typename T> void WriteArray(const T *pArray, size_t count = 1) {
const size_t size = sizeof(T) * count;
memcpy(Cast<T>(size), pArray, size);
Offset += size;
}
};
} // namespace
// returns the offset of the name inserted
uint32_t StringBufferPart::Insert(llvm::StringRef str) {
auto result = m_Map.insert(
std::make_pair(std::string(str.data(), str.data() + str.size()), m_Size));
auto iterator = result.first;
if (result.second) {
const std::string &key = iterator->first;
m_List.push_back(llvm::StringRef(key.data(), key.size()));
m_Size += key.size() + 1 /*null terminator*/;
}
return iterator->second;
}
void StringBufferPart::Write(void *ptr) {
for (llvm::StringRef &entry : m_List) {
memcpy(ptr, entry.data(), entry.size() + 1 /*null terminator*/);
ptr = (char *)ptr + entry.size() + 1;
}
}
StringRef DxilRDATBuilder::FinalizeAndGetData() {
try {
m_RDATBuffer.resize(size(), 0);
CheckedWriter W(m_RDATBuffer.data(), m_RDATBuffer.size());
// write RDAT header
RuntimeDataHeader &header = W.Map<RuntimeDataHeader>();
header.Version = RDAT_Version_10;
header.PartCount = ComputeSize().numParts;
// map offsets
uint32_t *offsets = W.MapArray<uint32_t>(header.PartCount);
// write parts
unsigned i = 0;
for (auto &part : m_Parts) {
if (part->GetPartSize() == 0)
continue;
offsets[i++] = W.GetOffset();
RuntimeDataPartHeader &partHeader = W.Map<RuntimeDataPartHeader>();
partHeader.Type = part->GetType();
partHeader.Size = PSVALIGN4(part->GetPartSize());
DXASSERT(partHeader.Size, "otherwise, failed to remove empty part");
char *bytes = W.MapArray<char>(partHeader.Size);
part->Write(bytes);
}
} catch (CheckedWriter::exception e) {
throw hlsl::Exception(DXC_E_GENERAL_INTERNAL_ERROR, e.what());
}
return llvm::StringRef(m_RDATBuffer.data(), m_RDATBuffer.size());
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilContainer/RDATDumper.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// RDATDumper.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Use this to dump DxilRuntimeData (RDAT) for testing. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/Test/RDATDumper.h"
#include "dxc/Support/Global.h"
using namespace hlsl;
using namespace RDAT;
namespace hlsl {
namespace dump {
void DumpRuntimeData(const RDAT::DxilRuntimeData &RDAT, DumpContext &d) {
const RDATContext &ctx = RDAT.GetContext();
d.WriteLn("DxilRuntimeData (size = ", RDAT.GetDataSize(), " bytes):");
d.Indent();
d.WriteLn("StringBuffer (size = ", ctx.StringBuffer.Size(), " bytes)");
d.WriteLn("IndexTable (size = ", ctx.IndexTable.Count() * 4, " bytes)");
d.WriteLn("RawBytes (size = ", ctx.RawBytes.Size(), " bytes)");
// Once per table.
#define RDAT_STRUCT_TABLE(type, table) \
DumpRecordTable<type>(ctx, d, #table, ctx.Table(RecordTableIndex::table));
#define DEF_RDAT_TYPES DEF_RDAT_DEFAULTS
#include "dxc/DxilContainer/RDAT_Macros.inl"
d.Dedent();
}
template <typename RecordType>
void DumpRecordTable(const RDAT::RDATContext &ctx, DumpContext &d,
const char *tableName, const RDAT::TableReader &table) {
if (!table.Count())
return;
d.WriteLn("RecordTable (stride = ", table.Stride(), " bytes) ", tableName,
"[", table.Count(), "] = {");
d.Indent();
for (unsigned i = 0; i < table.Count(); i++) {
DumpRecordTableEntry<RecordType>(ctx, d, i);
}
d.Dedent();
d.WriteLn("}");
}
template <typename RecordType>
void DumpRecordTableEntry(const RDAT::RDATContext &ctx, DumpContext &d,
uint32_t i) {
// Visit() will prevent recursive/repeated reference expansion. Resetting
// for each top-level table entry prevents a record from dumping differently
// depending on differences in other unrelated records.
d.VisitReset();
// RecordRefDumper handles derived types.
RecordRefDumper<RecordType> rrDumper(i);
d.WriteLn("<", i, ":", rrDumper.TypeName(ctx), "> = {");
rrDumper.Dump(ctx, d);
d.WriteLn("}");
}
template <typename _T>
void DumpRecordValue(const hlsl::RDAT::RDATContext &ctx, DumpContext &d,
const char *tyName, const char *memberName,
const _T *memberPtr) {
d.WriteLn(memberName, ": <", tyName, ">");
DumpWithBase(ctx, d, memberPtr);
}
template <typename _T>
void DumpRecordRef(const hlsl::RDAT::RDATContext &ctx, DumpContext &d,
const char *tyName, const char *memberName,
hlsl::RDAT::RecordRef<_T> rr) {
RecordRefDumper<_T> rrDumper(rr.Index);
const char *storedTypeName = rrDumper.TypeName(ctx);
if (nullptr == storedTypeName)
storedTypeName = tyName;
// Unique visit location is based on end of struct so derived are not skipped
if (rr.Get(ctx)) {
if (d.Visit(rr.Get(ctx))) {
d.WriteLn(memberName, ": <", rr.Index, ":", storedTypeName, "> = {");
rrDumper.Dump(ctx, d);
d.WriteLn("}");
} else {
d.WriteLn(memberName, ": <", rr.Index, ":", storedTypeName, ">");
}
} else {
d.WriteLn(memberName, ": <", rr.Index, ":", storedTypeName,
"> = <nullptr>");
}
}
template <typename _T>
void DumpRecordArrayRef(const hlsl::RDAT::RDATContext &ctx, DumpContext &d,
const char *tyName, const char *memberName,
hlsl::RDAT::RecordArrayRef<_T> rar) {
auto row = ctx.IndexTable.getRow(rar.Index);
if (row.Count()) {
d.WriteLn(memberName, ": <", rar.Index, ":RecordArrayRef<", tyName, ">[",
row.Count(), "]> = {");
d.Indent();
for (uint32_t i = 0; i < row.Count(); ++i) {
RecordRefDumper<_T> rrDumper(row.At(i));
if (rrDumper.Get(ctx)) {
if (d.Visit(rrDumper.Get(ctx))) {
d.WriteLn("[", i, "]: <", rrDumper.Index, ":", rrDumper.TypeName(ctx),
"> = {");
rrDumper.Dump(ctx, d);
d.WriteLn("}");
} else {
d.WriteLn("[", i, "]: <", rrDumper.Index, ":", rrDumper.TypeName(ctx),
">");
}
} else {
d.WriteLn("[", i, "]: <", row.At(i), ":", tyName, "> = <nullptr>");
}
}
d.Dedent();
d.WriteLn("}");
} else {
d.WriteLn(memberName, ": <RecordArrayRef<", tyName, ">[0]> = {}");
}
}
void DumpStringArray(const hlsl::RDAT::RDATContext &ctx, DumpContext &d,
const char *memberName, hlsl::RDAT::RDATStringArray sa) {
auto sar = sa.Get(ctx);
if (sar && sar.Count()) {
d.WriteLn(memberName, ": <", sa.Index, ":string[", sar.Count(), "]> = {");
d.Indent();
for (uint32_t _i = 0; _i < (uint32_t)sar.Count(); ++_i) {
const char *str = sar[_i];
if (str) {
d.WriteLn("[", _i, "]: ", QuotedStringValue(str));
} else {
d.WriteLn("[", _i, "]: <nullptr>");
}
}
d.Dedent();
d.WriteLn("}");
} else {
d.WriteLn(memberName, ": <string[0]> = {}");
}
}
// Currently dumps index array inline
void DumpIndexArray(const hlsl::RDAT::RDATContext &ctx, DumpContext &d,
const char *memberName, uint32_t index) {
auto indexArray = ctx.IndexTable.getRow(index);
unsigned arraySize = indexArray.Count();
std::ostringstream oss;
std::ostream &os = oss;
d.Write(os, memberName, ": <", index, ":array[", arraySize, "]> = { ");
for (unsigned i = 0; i < arraySize; ++i) {
d.Write(os, indexArray[i]);
if (i < arraySize - 1)
d.Write(os, ", ");
}
d.Write(os, " }");
d.WriteLn(oss.str());
}
void DumpBytesRef(const hlsl::RDAT::RDATContext &ctx, DumpContext &d,
const char *memberName, hlsl::RDAT::BytesRef bytesRef) {
d.WriteLn(memberName, ": <", bytesRef.Offset, ":bytes[", bytesRef.Size, "]>");
}
template <typename _T>
void DumpValueArray(DumpContext &d, const char *memberName,
const char *typeName, const void *valueArray,
unsigned arraySize) {
d.WriteLn(memberName, ": ", typeName, "[", arraySize, "] = { ");
for (unsigned i = 0; i < arraySize; i++) {
d.Write(((const _T *)valueArray)[i]);
if (i < arraySize - 1)
d.Write(", ");
}
d.WriteLn(" }");
}
#define DEF_RDAT_TYPES DEF_RDAT_DUMP_IMPL
#include "dxc/DxilContainer/RDAT_Macros.inl"
} // namespace dump
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilContainer/RDATDxilSubobjects.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// RDATDxilSubobjects.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Implement LoadSubobjectsFromRDAT, depending on both DXIL and RDAT libs. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilSubobject.h"
#include "dxc/DxilContainer/DxilRuntimeReflection.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/Unicode.h"
#include "dxc/Support/WinIncludes.h"
namespace hlsl {
bool LoadSubobjectsFromRDAT(DxilSubobjects &subobjects,
const RDAT::DxilRuntimeData &rdat) {
auto table = rdat.GetSubobjectTable();
if (!table)
return false;
bool result = true;
for (unsigned i = 0; i < table.Count(); ++i) {
try {
auto reader = table[i];
DXIL::SubobjectKind kind = reader.getKind();
bool bLocalRS = false;
switch (kind) {
case DXIL::SubobjectKind::StateObjectConfig:
subobjects.CreateStateObjectConfig(
reader.getName(), reader.getStateObjectConfig().getFlags());
break;
case DXIL::SubobjectKind::LocalRootSignature:
bLocalRS = true;
LLVM_FALLTHROUGH;
case DXIL::SubobjectKind::GlobalRootSignature:
if (!reader.getRootSignature()) {
result = false;
continue;
}
subobjects.CreateRootSignature(reader.getName(), bLocalRS,
reader.getRootSignature().getData(),
reader.getRootSignature().sizeData());
break;
case DXIL::SubobjectKind::SubobjectToExportsAssociation: {
auto association = reader.getSubobjectToExportsAssociation();
auto exports = association.getExports();
uint32_t NumExports = exports.Count();
std::vector<llvm::StringRef> Exports;
Exports.resize(NumExports);
for (unsigned i = 0; i < NumExports; ++i) {
Exports[i] = exports[i];
}
subobjects.CreateSubobjectToExportsAssociation(
reader.getName(), association.getSubobject(), Exports.data(),
NumExports);
break;
}
case DXIL::SubobjectKind::RaytracingShaderConfig:
subobjects.CreateRaytracingShaderConfig(
reader.getName(),
reader.getRaytracingShaderConfig().getMaxPayloadSizeInBytes(),
reader.getRaytracingShaderConfig().getMaxAttributeSizeInBytes());
break;
case DXIL::SubobjectKind::RaytracingPipelineConfig:
subobjects.CreateRaytracingPipelineConfig(
reader.getName(),
reader.getRaytracingPipelineConfig().getMaxTraceRecursionDepth());
break;
case DXIL::SubobjectKind::HitGroup:
subobjects.CreateHitGroup(reader.getName(),
reader.getHitGroup().getType(),
reader.getHitGroup().getAnyHit(),
reader.getHitGroup().getClosestHit(),
reader.getHitGroup().getIntersection());
break;
case DXIL::SubobjectKind::RaytracingPipelineConfig1:
subobjects.CreateRaytracingPipelineConfig1(
reader.getName(),
reader.getRaytracingPipelineConfig1().getMaxTraceRecursionDepth(),
reader.getRaytracingPipelineConfig1().getFlags());
break;
}
} catch (hlsl::Exception &) {
result = false;
}
}
return result;
}
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilContainer/DxilContainer.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilContainer.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides support for manipulating DXIL container structures. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DxilContainer/DxilContainer.h"
#include <algorithm>
namespace hlsl {
DxilPartIterator begin(const DxilContainerHeader *pHeader) {
return {pHeader, 0};
}
DxilPartIterator end(const DxilContainerHeader *pHeader) {
return {pHeader, pHeader->PartCount};
}
void InitDxilContainer(DxilContainerHeader *pHeader, uint32_t partCount,
uint32_t containerSizeInBytes) {
memset(pHeader, 0, sizeof(*pHeader));
pHeader->HeaderFourCC = DFCC_Container;
pHeader->Version.Major = DxilContainerVersionMajor;
pHeader->Version.Minor = DxilContainerVersionMinor;
pHeader->PartCount = partCount;
pHeader->ContainerSizeInBytes = containerSizeInBytes;
}
const DxilContainerHeader *IsDxilContainerLike(const void *ptr, size_t length) {
if (ptr == nullptr || length < sizeof(DxilContainerHeader))
return nullptr;
if (DFCC_Container != *reinterpret_cast<const uint32_t *>(ptr))
return nullptr;
return reinterpret_cast<const DxilContainerHeader *>(ptr);
}
DxilContainerHeader *IsDxilContainerLike(void *ptr, size_t length) {
return const_cast<DxilContainerHeader *>(
IsDxilContainerLike(static_cast<const void *>(ptr), length));
}
bool IsValidDxilContainer(const DxilContainerHeader *pHeader, size_t length) {
// Validate that the header is where it's supposed to be.
if (pHeader == nullptr)
return false;
if (length < sizeof(DxilContainerHeader))
return false;
// Validate the header values.
if (pHeader->HeaderFourCC != DFCC_Container)
return false;
if (pHeader->Version.Major != DxilContainerVersionMajor)
return false;
if (pHeader->ContainerSizeInBytes > length)
return false;
if (pHeader->ContainerSizeInBytes > DxilContainerMaxSize)
return false;
// Make sure that the count of offsets fits.
size_t partOffsetTableBytes = sizeof(uint32_t) * pHeader->PartCount;
if (partOffsetTableBytes + sizeof(DxilContainerHeader) >
pHeader->ContainerSizeInBytes)
return false;
// Make sure that each part is within the bounds.
const uint8_t *pLinearContainer = reinterpret_cast<const uint8_t *>(pHeader);
const uint32_t *pPartOffsetTable =
reinterpret_cast<const uint32_t *>(pHeader + 1);
const uint8_t *nextPartBegin = ((const uint8_t *)pPartOffsetTable) +
(sizeof(uint32_t) * pHeader->PartCount);
for (uint32_t i = 0; i < pHeader->PartCount; ++i) {
// The part header should fit.
if (pPartOffsetTable[i] >
(pHeader->ContainerSizeInBytes - sizeof(DxilPartHeader)))
return false;
// The contents of the part should fit.
const DxilPartHeader *pPartHeader =
reinterpret_cast<const DxilPartHeader *>(pLinearContainer +
pPartOffsetTable[i]);
// Each part should start at next location with no gaps.
if ((const void *)nextPartBegin != pPartHeader)
return false;
if (pPartOffsetTable[i] + sizeof(DxilPartHeader) + pPartHeader->PartSize >
pHeader->ContainerSizeInBytes) {
return false;
}
nextPartBegin += sizeof(DxilPartHeader) + pPartHeader->PartSize;
}
// Container size should match end of last part
if ((uint32_t)(nextPartBegin - pLinearContainer) !=
pHeader->ContainerSizeInBytes)
return false;
return true;
}
const DxilPartHeader *GetDxilPartByType(const DxilContainerHeader *pHeader,
DxilFourCC fourCC) {
if (!IsDxilContainerLike(pHeader, pHeader->ContainerSizeInBytes)) {
return nullptr;
}
const DxilPartIterator partIter =
std::find_if(begin(pHeader), end(pHeader), DxilPartIsType(fourCC));
if (partIter == end(pHeader)) {
return nullptr;
}
return *partIter;
}
DxilPartHeader *GetDxilPartByType(DxilContainerHeader *pHeader,
DxilFourCC fourCC) {
return const_cast<DxilPartHeader *>(GetDxilPartByType(
static_cast<const DxilContainerHeader *>(pHeader), fourCC));
}
const DxilProgramHeader *
GetDxilProgramHeader(const DxilContainerHeader *pHeader, DxilFourCC fourCC) {
if (!IsDxilContainerLike(pHeader, pHeader->ContainerSizeInBytes)) {
return nullptr;
}
const DxilPartHeader *PartHeader = GetDxilPartByType(pHeader, fourCC);
if (!PartHeader) {
return nullptr;
}
const DxilProgramHeader *ProgramHeader =
reinterpret_cast<const DxilProgramHeader *>(GetDxilPartData(PartHeader));
return IsValidDxilProgramHeader(ProgramHeader,
ProgramHeader->SizeInUint32 * 4)
? ProgramHeader
: nullptr;
}
DxilProgramHeader *GetDxilProgramHeader(DxilContainerHeader *pHeader,
DxilFourCC fourCC) {
return const_cast<DxilProgramHeader *>(GetDxilProgramHeader(
static_cast<const DxilContainerHeader *>(pHeader), fourCC));
}
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilContainer/CMakeLists.txt | # Copyright (C) Microsoft Corporation. All rights reserved.
# This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details.
add_llvm_library(LLVMDxilContainer
D3DReflectionDumper.cpp
D3DReflectionStrings.cpp
DxilContainer.cpp
DxilContainerAssembler.cpp
DxilContainerReader.cpp
DxcContainerBuilder.cpp
DxilPipelineStateValidation.cpp
DxilRDATBuilder.cpp
DxilRuntimeReflection.cpp
RDATDumper.cpp
RDATDxilSubobjects.cpp
ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/IR
)
add_dependencies(LLVMDxilContainer intrinsics_gen)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilContainer/LLVMBuild.txt | ; Copyright (C) Microsoft Corporation. All rights reserved.
; This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details.
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Library
name = DxilContainer
parent = Libraries
required_libraries = BitReader BitWriter Core DxcSupport IPA Support DXIL TransformUtils
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilContainer/DxilRuntimeReflection.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilRuntimeReflection.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides support for manipulating DXIL container structures. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DxilContainer/DxilRuntimeReflection.h"
#include "dxc/DXIL/DxilSubobject.h"
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/Unicode.h"
#include "dxc/Support/WinIncludes.h"
// DxilRuntimeReflection implementation
#include "dxc/DxilContainer/DxilRuntimeReflection.inl"
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilContainer/DxilPipelineStateValidation.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilPipelineStateValidation.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Utils for PSV. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DxilContainer/DxilPipelineStateValidation.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilResource.h"
#include "dxc/DXIL/DxilResourceBase.h"
#include "dxc/DXIL/DxilSignature.h"
#include "dxc/DXIL/DxilSignatureElement.h"
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/Support/Global.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
using namespace hlsl;
using namespace llvm;
void hlsl::InitPSVResourceBinding(PSVResourceBindInfo0 *Bind0,
PSVResourceBindInfo1 *Bind1,
DxilResourceBase *Res) {
Bind0->Space = Res->GetSpaceID();
Bind0->LowerBound = Res->GetLowerBound();
Bind0->UpperBound = Res->GetUpperBound();
PSVResourceType ResType = PSVResourceType::Invalid;
bool IsUAV = Res->GetClass() == DXIL::ResourceClass::UAV;
switch (Res->GetKind()) {
case DXIL::ResourceKind::Sampler:
ResType = PSVResourceType::Sampler;
break;
case DXIL::ResourceKind::CBuffer:
ResType = PSVResourceType::CBV;
break;
case DXIL::ResourceKind::StructuredBuffer:
ResType =
IsUAV ? PSVResourceType::UAVStructured : PSVResourceType::SRVStructured;
if (IsUAV) {
DxilResource *UAV = static_cast<DxilResource *>(Res);
if (UAV->HasCounter())
ResType = PSVResourceType::UAVStructuredWithCounter;
}
break;
case DXIL::ResourceKind::RTAccelerationStructure:
ResType = PSVResourceType::SRVRaw;
break;
case DXIL::ResourceKind::RawBuffer:
ResType = IsUAV ? PSVResourceType::UAVRaw : PSVResourceType::SRVRaw;
break;
default:
ResType = IsUAV ? PSVResourceType::UAVTyped : PSVResourceType::SRVTyped;
break;
}
Bind0->ResType = static_cast<uint32_t>(ResType);
if (Bind1) {
Bind1->ResKind = static_cast<uint32_t>(Res->GetKind());
Bind1->ResFlags = 0;
if (IsUAV) {
DxilResource *UAV = static_cast<DxilResource *>(Res);
unsigned ResFlags =
UAV->HasAtomic64Use()
? static_cast<unsigned>(PSVResourceFlag::UsedByAtomic64)
: 0;
Bind1->ResFlags = ResFlags;
}
}
}
void hlsl::InitPSVSignatureElement(PSVSignatureElement0 &E,
const DxilSignatureElement &SE,
bool i1ToUnknownCompat) {
memset(&E, 0, sizeof(PSVSignatureElement0));
DXASSERT_NOMSG(SE.GetRows() <= 32);
E.Rows = (uint8_t)SE.GetRows();
DXASSERT_NOMSG(SE.GetCols() <= 4);
E.ColsAndStart = (uint8_t)SE.GetCols() & 0xF;
if (SE.IsAllocated()) {
DXASSERT_NOMSG(SE.GetStartCol() < 4);
DXASSERT_NOMSG(SE.GetStartRow() < 32);
E.ColsAndStart |= 0x40 | (SE.GetStartCol() << 4);
E.StartRow = (uint8_t)SE.GetStartRow();
}
E.SemanticKind = (uint8_t)SE.GetKind();
E.ComponentType = (uint8_t)CompTypeToSigCompType(SE.GetCompType().GetKind(),
i1ToUnknownCompat);
E.InterpolationMode = (uint8_t)SE.GetInterpolationMode()->GetKind();
DXASSERT_NOMSG(SE.GetOutputStream() < 4);
E.DynamicMaskAndStream = (uint8_t)((SE.GetOutputStream() & 0x3) << 4);
E.DynamicMaskAndStream |= (SE.GetDynIdxCompMask()) & 0xF;
}
void hlsl::InitPSVRuntimeInfo(PSVRuntimeInfo0 *pInfo, PSVRuntimeInfo1 *pInfo1,
PSVRuntimeInfo2 *pInfo2, PSVRuntimeInfo3 *pInfo3,
const DxilModule &DM) {
const ShaderModel *SM = DM.GetShaderModel();
pInfo->MinimumExpectedWaveLaneCount = 0;
pInfo->MaximumExpectedWaveLaneCount = (uint32_t)-1;
switch (SM->GetKind()) {
case ShaderModel::Kind::Vertex: {
pInfo->VS.OutputPositionPresent = 0;
const DxilSignature &S = DM.GetOutputSignature();
for (auto &&E : S.GetElements()) {
if (E->GetKind() == Semantic::Kind::Position) {
// Ideally, we might check never writes mask here,
// but this is not yet part of the signature element in Dxil
pInfo->VS.OutputPositionPresent = 1;
break;
}
}
break;
}
case ShaderModel::Kind::Hull: {
pInfo->HS.InputControlPointCount = (uint32_t)DM.GetInputControlPointCount();
pInfo->HS.OutputControlPointCount =
(uint32_t)DM.GetOutputControlPointCount();
pInfo->HS.TessellatorDomain = (uint32_t)DM.GetTessellatorDomain();
pInfo->HS.TessellatorOutputPrimitive =
(uint32_t)DM.GetTessellatorOutputPrimitive();
break;
}
case ShaderModel::Kind::Domain: {
pInfo->DS.InputControlPointCount = (uint32_t)DM.GetInputControlPointCount();
pInfo->DS.OutputPositionPresent = 0;
const DxilSignature &S = DM.GetOutputSignature();
for (auto &&E : S.GetElements()) {
if (E->GetKind() == Semantic::Kind::Position) {
// Ideally, we might check never writes mask here,
// but this is not yet part of the signature element in Dxil
pInfo->DS.OutputPositionPresent = 1;
break;
}
}
pInfo->DS.TessellatorDomain = (uint32_t)DM.GetTessellatorDomain();
break;
}
case ShaderModel::Kind::Geometry: {
pInfo->GS.InputPrimitive = (uint32_t)DM.GetInputPrimitive();
// NOTE: For OutputTopology, pick one from a used stream, or if none
// are used, use stream 0, and set OutputStreamMask to 1.
pInfo->GS.OutputTopology = (uint32_t)DM.GetStreamPrimitiveTopology();
pInfo->GS.OutputStreamMask = DM.GetActiveStreamMask();
if (pInfo->GS.OutputStreamMask == 0) {
pInfo->GS.OutputStreamMask = 1; // This is what runtime expects.
}
pInfo->GS.OutputPositionPresent = 0;
const DxilSignature &S = DM.GetOutputSignature();
for (auto &&E : S.GetElements()) {
if (E->GetKind() == Semantic::Kind::Position) {
// Ideally, we might check never writes mask here,
// but this is not yet part of the signature element in Dxil
pInfo->GS.OutputPositionPresent = 1;
break;
}
}
break;
}
case ShaderModel::Kind::Pixel: {
pInfo->PS.DepthOutput = 0;
pInfo->PS.SampleFrequency = 0;
{
const DxilSignature &S = DM.GetInputSignature();
for (auto &&E : S.GetElements()) {
if (E->GetInterpolationMode()->IsAnySample() ||
E->GetKind() == Semantic::Kind::SampleIndex) {
pInfo->PS.SampleFrequency = 1;
}
}
}
{
const DxilSignature &S = DM.GetOutputSignature();
for (auto &&E : S.GetElements()) {
if (E->IsAnyDepth()) {
pInfo->PS.DepthOutput = 1;
break;
}
}
}
break;
}
case ShaderModel::Kind::Compute: {
DxilWaveSize waveSize = DM.GetWaveSize();
pInfo->MinimumExpectedWaveLaneCount = 0;
pInfo->MaximumExpectedWaveLaneCount = UINT32_MAX;
if (waveSize.IsDefined()) {
pInfo->MinimumExpectedWaveLaneCount = waveSize.Min;
pInfo->MaximumExpectedWaveLaneCount =
waveSize.IsRange() ? waveSize.Max : waveSize.Min;
}
break;
}
case ShaderModel::Kind::Library:
case ShaderModel::Kind::Invalid:
// Library and Invalid not relevant to PSVRuntimeInfo0
break;
case ShaderModel::Kind::Mesh: {
pInfo->MS.MaxOutputVertices = (uint16_t)DM.GetMaxOutputVertices();
pInfo->MS.MaxOutputPrimitives = (uint16_t)DM.GetMaxOutputPrimitives();
pInfo1->MS1.MeshOutputTopology = (uint8_t)DM.GetMeshOutputTopology();
Module *mod = DM.GetModule();
const DataLayout &DL = mod->getDataLayout();
unsigned totalByteSize = 0;
for (GlobalVariable &GV : mod->globals()) {
PointerType *gvPtrType = cast<PointerType>(GV.getType());
if (gvPtrType->getAddressSpace() == hlsl::DXIL::kTGSMAddrSpace) {
Type *gvType = gvPtrType->getPointerElementType();
unsigned byteSize = DL.getTypeAllocSize(gvType);
totalByteSize += byteSize;
}
}
pInfo->MS.GroupSharedBytesUsed = totalByteSize;
pInfo->MS.PayloadSizeInBytes = DM.GetPayloadSizeInBytes();
break;
}
case ShaderModel::Kind::Amplification: {
pInfo->AS.PayloadSizeInBytes = DM.GetPayloadSizeInBytes();
break;
}
}
// Write MaxVertexCount
if (pInfo1) {
if (SM->GetKind() == ShaderModel::Kind::Geometry)
pInfo1->MaxVertexCount = (uint16_t)DM.GetMaxVertexCount();
}
if (pInfo2) {
switch (SM->GetKind()) {
case ShaderModel::Kind::Compute:
case ShaderModel::Kind::Mesh:
case ShaderModel::Kind::Amplification:
pInfo2->NumThreadsX = DM.GetNumThreads(0);
pInfo2->NumThreadsY = DM.GetNumThreads(1);
pInfo2->NumThreadsZ = DM.GetNumThreads(2);
break;
}
}
}
void PSVResourceBindInfo0::Print(raw_ostream &OS) const {
OS << "PSVResourceBindInfo:\n";
OS << " Space: " << Space << "\n";
OS << " LowerBound: " << LowerBound << "\n";
OS << " UpperBound: " << UpperBound << "\n";
switch (static_cast<PSVResourceType>(ResType)) {
case PSVResourceType::CBV:
OS << " ResType: CBV\n";
break;
case PSVResourceType::Sampler:
OS << " ResType: Sampler\n";
break;
case PSVResourceType::SRVRaw:
OS << " ResType: SRVRaw\n";
break;
case PSVResourceType::SRVStructured:
OS << " ResType: SRVStructured\n";
break;
case PSVResourceType::SRVTyped:
OS << " ResType: SRVTyped\n";
break;
case PSVResourceType::UAVRaw:
OS << " ResType: UAVRaw\n";
break;
case PSVResourceType::UAVStructured:
OS << " ResType: UAVStructured\n";
break;
case PSVResourceType::UAVTyped:
OS << " ResType: UAVTyped\n";
break;
case PSVResourceType::UAVStructuredWithCounter:
OS << " ResType: UAVStructuredWithCounter\n";
break;
case PSVResourceType::Invalid:
OS << " ResType: Invalid\n";
break;
default:
OS << " ResType: Unknown\n";
break;
}
}
void PSVResourceBindInfo1::Print(raw_ostream &OS) const {
PSVResourceBindInfo0::Print(OS);
switch (static_cast<PSVResourceKind>(ResKind)) {
case PSVResourceKind::Invalid:
OS << " ResKind: Invalid\n";
break;
case PSVResourceKind::CBuffer:
OS << " ResKind: CBuffer\n";
break;
case PSVResourceKind::Sampler:
OS << " ResKind: Sampler\n";
break;
case PSVResourceKind::FeedbackTexture2D:
OS << " ResKind: FeedbackTexture2D\n";
break;
case PSVResourceKind::FeedbackTexture2DArray:
OS << " ResKind: FeedbackTexture2DArray\n";
break;
case PSVResourceKind::RawBuffer:
OS << " ResKind: RawBuffer\n";
break;
case PSVResourceKind::StructuredBuffer:
OS << " ResKind: StructuredBuffer\n";
break;
case PSVResourceKind::TypedBuffer:
OS << " ResKind: TypedBuffer\n";
break;
case PSVResourceKind::RTAccelerationStructure:
OS << " ResKind: RTAccelerationStructure\n";
break;
case PSVResourceKind::TBuffer:
OS << " ResKind: TBuffer\n";
break;
case PSVResourceKind::Texture1D:
OS << " ResKind: Texture1D\n";
break;
case PSVResourceKind::Texture1DArray:
OS << " ResKind: Texture1DArray\n";
break;
case PSVResourceKind::Texture2D:
OS << " ResKind: Texture2D\n";
break;
case PSVResourceKind::Texture2DArray:
OS << " ResKind: Texture2DArray\n";
break;
case PSVResourceKind::Texture2DMS:
OS << " ResKind: Texture2DMS\n";
break;
case PSVResourceKind::Texture2DMSArray:
OS << " ResKind: Texture2DMSArray\n";
break;
case PSVResourceKind::Texture3D:
OS << " ResKind: Texture3D\n";
break;
case PSVResourceKind::TextureCube:
OS << " ResKind: TextureCube\n";
break;
case PSVResourceKind::TextureCubeArray:
OS << " ResKind: TextureCubeArray\n";
break;
}
if (ResFlags == 0) {
OS << " ResFlags: None\n";
} else {
OS << " ResFlags: ";
if (ResFlags & static_cast<uint32_t>(PSVResourceFlag::UsedByAtomic64)) {
OS << "UsedByAtomic64 ";
}
OS << "\n";
}
}
void PSVSignatureElement::Print(raw_ostream &OS) const {
OS << "PSVSignatureElement:\n";
OS << " SemanticName: " << GetSemanticName() << "\n";
OS << " SemanticIndex: ";
const uint32_t *SemanticIndexes = GetSemanticIndexes();
for (unsigned i = 0; i < GetRows(); ++i) {
OS << *(SemanticIndexes + i) << " ";
}
OS << "\n";
OS << " IsAllocated: " << IsAllocated() << "\n";
OS << " StartRow: " << GetStartRow() << "\n";
OS << " StartCol: " << GetStartCol() << "\n";
OS << " Rows: " << GetRows() << "\n";
OS << " Cols: " << GetCols() << "\n";
OS << " SemanticKind: ";
switch (GetSemanticKind()) {
case PSVSemanticKind::Arbitrary:
OS << "Arbitrary\n";
break;
case PSVSemanticKind::VertexID:
OS << "VertexID\n";
break;
case PSVSemanticKind::InstanceID:
OS << "InstanceID\n";
break;
case PSVSemanticKind::Position:
OS << "Position\n";
break;
case PSVSemanticKind::RenderTargetArrayIndex:
OS << "RenderTargetArrayIndex\n";
break;
case PSVSemanticKind::ViewPortArrayIndex:
OS << "ViewPortArrayIndex\n";
break;
case PSVSemanticKind::ClipDistance:
OS << "ClipDistance\n";
break;
case PSVSemanticKind::CullDistance:
OS << "CullDistance\n";
break;
case PSVSemanticKind::OutputControlPointID:
OS << "OutputControlPointID\n";
break;
case PSVSemanticKind::DomainLocation:
OS << "DomainLocation\n";
break;
case PSVSemanticKind::PrimitiveID:
OS << "PrimitiveID\n";
break;
case PSVSemanticKind::GSInstanceID:
OS << "GSInstanceID\n";
break;
case PSVSemanticKind::SampleIndex:
OS << "SampleIndex\n";
break;
case PSVSemanticKind::IsFrontFace:
OS << "IsFrontFace\n";
break;
case PSVSemanticKind::Coverage:
OS << "Coverage\n";
break;
case PSVSemanticKind::InnerCoverage:
OS << "InnerCoverage\n";
break;
case PSVSemanticKind::Target:
OS << "Target\n";
break;
case PSVSemanticKind::Depth:
OS << "Depth\n";
break;
case PSVSemanticKind::DepthLessEqual:
OS << "DepthLessEqual\n";
break;
case PSVSemanticKind::DepthGreaterEqual:
OS << "DepthGreaterEqual\n";
break;
case PSVSemanticKind::StencilRef:
OS << "StencilRef\n";
break;
case PSVSemanticKind::DispatchThreadID:
OS << "DispatchThreadID\n";
break;
case PSVSemanticKind::GroupID:
OS << "GroupID\n";
break;
case PSVSemanticKind::GroupIndex:
OS << "GroupIndex\n";
break;
case PSVSemanticKind::GroupThreadID:
OS << "GroupThreadID\n";
break;
case PSVSemanticKind::TessFactor:
OS << "TessFactor\n";
break;
case PSVSemanticKind::InsideTessFactor:
OS << "InsideTessFactor\n";
break;
case PSVSemanticKind::ViewID:
OS << "ViewID\n";
break;
case PSVSemanticKind::Barycentrics:
OS << "Barycentrics\n";
break;
case PSVSemanticKind::ShadingRate:
OS << "ShadingRate\n";
break;
case PSVSemanticKind::CullPrimitive:
OS << "CullPrimitive\n";
break;
case PSVSemanticKind::Invalid:
OS << "Invalid\n";
break;
}
OS << " InterpolationMode: " << GetInterpolationMode() << "\n";
OS << " OutputStream: " << GetOutputStream() << "\n";
OS << " ComponentType: " << GetComponentType() << "\n";
OS << " DynamicIndexMask: " << GetDynamicIndexMask() << "\n";
}
void PSVComponentMask::Print(raw_ostream &OS, const char *InputSetName,
const char *OutputSetName) const {
OS << " " << InputSetName << " influencing " << OutputSetName << " :";
bool Empty = true;
for (unsigned i = 0; i < NumVectors; ++i) {
for (unsigned j = 0; j < 32; ++j) {
uint32_t Index = i * 32 + j;
if (Get(Index)) {
OS << " " << Index << " ";
Empty = false;
}
}
}
if (Empty)
OS << " None";
OS << "\n";
}
void PSVDependencyTable::Print(raw_ostream &OS, const char *InputSetName,
const char *OutputSetName) const {
OS << InputSetName << " contributing to computation of " << OutputSetName
<< ":";
if (!IsValid()) {
OS << " None\n";
return;
}
OS << "\n";
for (unsigned i = 0; i < InputVectors; ++i) {
for (unsigned j = 0; j < 4; ++j) {
unsigned Index = i * 4 + j;
const PSVComponentMask Mask = GetMaskForInput(Index);
std::string InputName = InputSetName;
InputName += "[" + std::to_string(Index) + "]";
Mask.Print(OS, InputName.c_str(), OutputSetName);
}
}
}
void DxilPipelineStateValidation::PrintPSVRuntimeInfo(
raw_ostream &OS, uint8_t ShaderKind, const char *Comment) const {
PSVRuntimeInfo0 *pInfo0 = m_pPSVRuntimeInfo0;
PSVRuntimeInfo1 *pInfo1 = m_pPSVRuntimeInfo1;
PSVRuntimeInfo2 *pInfo2 = m_pPSVRuntimeInfo2;
PSVRuntimeInfo3 *pInfo3 = m_pPSVRuntimeInfo3;
if (pInfo1 && pInfo1->ShaderStage != ShaderKind)
ShaderKind = pInfo1->ShaderStage;
OS << Comment << "PSVRuntimeInfo:\n";
switch (static_cast<PSVShaderKind>(ShaderKind)) {
case PSVShaderKind::Hull: {
OS << Comment << " Hull Shader\n";
OS << Comment
<< " InputControlPointCount=" << pInfo0->HS.InputControlPointCount
<< "\n";
OS << Comment
<< " OutputControlPointCount=" << pInfo0->HS.OutputControlPointCount
<< "\n";
OS << Comment << " Domain=";
DXIL::TessellatorDomain domain =
static_cast<DXIL::TessellatorDomain>(pInfo0->HS.TessellatorDomain);
switch (domain) {
case DXIL::TessellatorDomain::IsoLine:
OS << "isoline\n";
break;
case DXIL::TessellatorDomain::Tri:
OS << "tri\n";
break;
case DXIL::TessellatorDomain::Quad:
OS << "quad\n";
break;
default:
OS << "invalid\n";
break;
}
OS << Comment << " OutputPrimitive=";
DXIL::TessellatorOutputPrimitive primitive =
static_cast<DXIL::TessellatorOutputPrimitive>(
pInfo0->HS.TessellatorOutputPrimitive);
switch (primitive) {
case DXIL::TessellatorOutputPrimitive::Point:
OS << "point\n";
break;
case DXIL::TessellatorOutputPrimitive::Line:
OS << "line\n";
break;
case DXIL::TessellatorOutputPrimitive::TriangleCW:
OS << "triangle_cw\n";
break;
case DXIL::TessellatorOutputPrimitive::TriangleCCW:
OS << "triangle_ccw\n";
break;
default:
OS << "invalid\n";
break;
}
} break;
case PSVShaderKind::Domain:
OS << Comment << " Domain Shader\n";
OS << Comment
<< " InputControlPointCount=" << pInfo0->DS.InputControlPointCount
<< "\n";
OS << Comment
<< " OutputPositionPresent=" << (bool)pInfo0->DS.OutputPositionPresent
<< "\n";
break;
case PSVShaderKind::Geometry: {
OS << Comment << " Geometry Shader\n";
OS << Comment << " InputPrimitive=";
DXIL::InputPrimitive primitive =
static_cast<DXIL::InputPrimitive>(pInfo0->GS.InputPrimitive);
switch (primitive) {
case DXIL::InputPrimitive::Point:
OS << "point\n";
break;
case DXIL::InputPrimitive::Line:
OS << "line\n";
break;
case DXIL::InputPrimitive::LineWithAdjacency:
OS << "lineadj\n";
break;
case DXIL::InputPrimitive::Triangle:
OS << "triangle\n";
break;
case DXIL::InputPrimitive::TriangleWithAdjacency:
OS << "triangleadj\n";
break;
case DXIL::InputPrimitive::ControlPointPatch1:
OS << "patch1\n";
break;
case DXIL::InputPrimitive::ControlPointPatch2:
OS << "patch2\n";
break;
case DXIL::InputPrimitive::ControlPointPatch3:
OS << "patch3\n";
break;
case DXIL::InputPrimitive::ControlPointPatch4:
OS << "patch4\n";
break;
case DXIL::InputPrimitive::ControlPointPatch5:
OS << "patch5\n";
break;
case DXIL::InputPrimitive::ControlPointPatch6:
OS << "patch6\n";
break;
case DXIL::InputPrimitive::ControlPointPatch7:
OS << "patch7\n";
break;
case DXIL::InputPrimitive::ControlPointPatch8:
OS << "patch8\n";
break;
case DXIL::InputPrimitive::ControlPointPatch9:
OS << "patch9\n";
break;
case DXIL::InputPrimitive::ControlPointPatch10:
OS << "patch10\n";
break;
case DXIL::InputPrimitive::ControlPointPatch11:
OS << "patch11\n";
break;
case DXIL::InputPrimitive::ControlPointPatch12:
OS << "patch12\n";
break;
case DXIL::InputPrimitive::ControlPointPatch13:
OS << "patch13\n";
break;
case DXIL::InputPrimitive::ControlPointPatch14:
OS << "patch14\n";
break;
case DXIL::InputPrimitive::ControlPointPatch15:
OS << "patch15\n";
break;
case DXIL::InputPrimitive::ControlPointPatch16:
OS << "patch16\n";
break;
case DXIL::InputPrimitive::ControlPointPatch17:
OS << "patch17\n";
break;
case DXIL::InputPrimitive::ControlPointPatch18:
OS << "patch18\n";
break;
case DXIL::InputPrimitive::ControlPointPatch19:
OS << "patch19\n";
break;
case DXIL::InputPrimitive::ControlPointPatch20:
OS << "patch20\n";
break;
case DXIL::InputPrimitive::ControlPointPatch21:
OS << "patch21\n";
break;
case DXIL::InputPrimitive::ControlPointPatch22:
OS << "patch22\n";
break;
case DXIL::InputPrimitive::ControlPointPatch23:
OS << "patch23\n";
break;
case DXIL::InputPrimitive::ControlPointPatch24:
OS << "patch24\n";
break;
case DXIL::InputPrimitive::ControlPointPatch25:
OS << "patch25\n";
break;
case DXIL::InputPrimitive::ControlPointPatch26:
OS << "patch26\n";
break;
case DXIL::InputPrimitive::ControlPointPatch27:
OS << "patch27\n";
break;
case DXIL::InputPrimitive::ControlPointPatch28:
OS << "patch28\n";
break;
case DXIL::InputPrimitive::ControlPointPatch29:
OS << "patch29\n";
break;
case DXIL::InputPrimitive::ControlPointPatch30:
OS << "patch30\n";
break;
case DXIL::InputPrimitive::ControlPointPatch31:
OS << "patch31\n";
break;
case DXIL::InputPrimitive::ControlPointPatch32:
OS << "patch32\n";
break;
default:
OS << "invalid\n";
break;
}
OS << Comment << " OutputTopology=";
DXIL::PrimitiveTopology topology =
static_cast<DXIL::PrimitiveTopology>(pInfo0->GS.OutputTopology);
switch (topology) {
case DXIL::PrimitiveTopology::PointList:
OS << "point\n";
break;
case DXIL::PrimitiveTopology::LineStrip:
OS << "line\n";
break;
case DXIL::PrimitiveTopology::TriangleStrip:
OS << "triangle\n";
break;
default:
OS << "invalid\n";
break;
}
OS << Comment << " OutputStreamMask=" << pInfo0->GS.OutputStreamMask
<< "\n";
OS << Comment
<< " OutputPositionPresent=" << (bool)pInfo0->GS.OutputPositionPresent
<< "\n";
} break;
case PSVShaderKind::Vertex:
OS << Comment << " Vertex Shader\n";
OS << Comment
<< " OutputPositionPresent=" << (bool)pInfo0->VS.OutputPositionPresent
<< "\n";
break;
case PSVShaderKind::Pixel:
OS << Comment << " Pixel Shader\n";
OS << Comment << " DepthOutput=" << (bool)pInfo0->PS.DepthOutput << "\n";
OS << Comment << " SampleFrequency=" << (bool)pInfo0->PS.SampleFrequency
<< "\n";
break;
case PSVShaderKind::Compute:
OS << Comment << " Compute Shader\n";
if (pInfo2) {
OS << Comment << " NumThreads=(" << pInfo2->NumThreadsX << ","
<< pInfo2->NumThreadsY << "," << pInfo2->NumThreadsZ << ")\n";
}
break;
case PSVShaderKind::Amplification:
OS << Comment << " Amplification Shader\n";
if (pInfo2) {
OS << Comment << " NumThreads=(" << pInfo2->NumThreadsX << ","
<< pInfo2->NumThreadsY << "," << pInfo2->NumThreadsZ << ")\n";
}
break;
case PSVShaderKind::Mesh:
OS << Comment << " Mesh Shader\n";
if (pInfo1) {
OS << Comment << " MeshOutputTopology=";
DXIL::MeshOutputTopology topology =
static_cast<DXIL::MeshOutputTopology>(pInfo1->MS1.MeshOutputTopology);
switch (topology) {
case DXIL::MeshOutputTopology::Undefined:
OS << "undefined\n";
break;
case DXIL::MeshOutputTopology::Line:
OS << "line\n";
break;
case DXIL::MeshOutputTopology::Triangle:
OS << "triangle\n";
break;
default:
OS << "invalid\n";
break;
}
}
if (pInfo2) {
OS << Comment << " NumThreads=(" << pInfo2->NumThreadsX << ","
<< pInfo2->NumThreadsY << "," << pInfo2->NumThreadsZ << ")\n";
}
break;
case PSVShaderKind::Library:
case PSVShaderKind::Invalid:
// Nothing to print for these shader kinds.
break;
}
if (pInfo0->MinimumExpectedWaveLaneCount ==
pInfo0->MaximumExpectedWaveLaneCount) {
OS << Comment << " WaveSize=" << pInfo0->MinimumExpectedWaveLaneCount
<< "\n";
} else {
OS << Comment << " MinimumExpectedWaveLaneCount: "
<< pInfo0->MinimumExpectedWaveLaneCount << "\n";
OS << Comment << " MaximumExpectedWaveLaneCount: "
<< pInfo0->MaximumExpectedWaveLaneCount << "\n";
}
if (pInfo1) {
OS << Comment;
pInfo1->UsesViewID ? OS << " UsesViewID: true\n"
: OS << " UsesViewID: false\n";
OS << Comment << " SigInputElements: " << (uint32_t)pInfo1->SigInputElements
<< "\n";
OS << Comment
<< " SigOutputElements: " << (uint32_t)pInfo1->SigOutputElements << "\n";
OS << Comment << " SigPatchConstOrPrimElements: "
<< (uint32_t)pInfo1->SigPatchConstOrPrimElements << "\n";
OS << Comment << " SigInputVectors: " << (uint32_t)pInfo1->SigInputVectors
<< "\n";
for (uint32_t i = 0; i < PSV_GS_MAX_STREAMS; ++i) {
OS << Comment << " SigOutputVectors[" << i
<< "]: " << (uint32_t)pInfo1->SigOutputVectors[i] << "\n";
}
}
if (pInfo3)
OS << Comment
<< " EntryFunctionName: " << m_StringTable.Get(pInfo3->EntryFunctionName)
<< "\n";
}
void DxilPipelineStateValidation::Print(raw_ostream &OS,
uint8_t ShaderKind) const {
OS << "DxilPipelineStateValidation:\n";
PrintPSVRuntimeInfo(OS, ShaderKind, "");
OS << "ResourceCount : " << m_uResourceCount << "\n ";
if (m_uResourceCount) {
if (m_uPSVResourceBindInfoSize == sizeof(PSVResourceBindInfo0)) {
auto *BindInfoPtr = (PSVResourceBindInfo0 *)m_pPSVResourceBindInfo;
for (uint32_t i = 0; i < m_uResourceCount; ++i)
(BindInfoPtr + i)->Print(OS);
} else {
assert(m_uPSVResourceBindInfoSize == sizeof(PSVResourceBindInfo1));
auto *BindInfoPtr = (PSVResourceBindInfo1 *)m_pPSVResourceBindInfo;
for (uint32_t i = 0; i < m_uResourceCount; ++i)
(BindInfoPtr + i)->Print(OS);
}
}
if (m_pPSVRuntimeInfo1 && (!IsCS() && !IsAS())) {
assert(m_uPSVSignatureElementSize == sizeof(PSVSignatureElement0));
PSVSignatureElement0 *InputElements =
(PSVSignatureElement0 *)m_pSigInputElements;
for (uint32_t i = 0; i < m_pPSVRuntimeInfo1->SigInputElements; ++i) {
PSVSignatureElement PSVSE(m_StringTable, m_SemanticIndexTable,
InputElements + i);
PSVSE.Print(OS);
}
PSVSignatureElement0 *OutputElements =
(PSVSignatureElement0 *)m_pSigOutputElements;
for (uint32_t i = 0; i < m_pPSVRuntimeInfo1->SigOutputElements; ++i) {
PSVSignatureElement PSVSE(m_StringTable, m_SemanticIndexTable,
OutputElements + i);
PSVSE.Print(OS);
}
PSVSignatureElement0 *PatchConstOrPrimElements =
(PSVSignatureElement0 *)m_pSigPatchConstOrPrimElements;
for (uint32_t i = 0; i < m_pPSVRuntimeInfo1->SigPatchConstOrPrimElements;
++i) {
PSVSignatureElement PSVSE(m_StringTable, m_SemanticIndexTable,
PatchConstOrPrimElements + i);
PSVSE.Print(OS);
}
unsigned NumStreams = IsGS() ? PSV_GS_MAX_STREAMS : 1;
if (m_pPSVRuntimeInfo1->UsesViewID) {
for (unsigned i = 0; i < NumStreams; ++i) {
OS << "Outputs affected by ViewID as a bitmask for stream " << i
<< ":\n ";
uint8_t OutputVectors = m_pPSVRuntimeInfo1->SigOutputVectors[i];
const PSVComponentMask ViewIDMask(m_pViewIDOutputMask[i],
OutputVectors);
std::string OutputSetName = "Outputs";
OutputSetName += "[" + std::to_string(i) + "]";
ViewIDMask.Print(OS, "ViewID", OutputSetName.c_str());
}
if (IsHS() || IsMS()) {
OS << "PCOutputs affected by ViewID as a bitmask:\n";
uint8_t OutputVectors = m_pPSVRuntimeInfo1->SigPatchConstOrPrimVectors;
const PSVComponentMask ViewIDMask(m_pViewIDPCOrPrimOutputMask,
OutputVectors);
ViewIDMask.Print(OS, "ViewID", "PCOutputs");
}
}
for (unsigned i = 0; i < NumStreams; ++i) {
OS << "Outputs affected by inputs as a table of bitmasks for stream " << i
<< ":\n";
uint8_t InputVectors = m_pPSVRuntimeInfo1->SigInputVectors;
uint8_t OutputVectors = m_pPSVRuntimeInfo1->SigOutputVectors[i];
const PSVDependencyTable Table(m_pInputToOutputTable[i], InputVectors,
OutputVectors);
std::string OutputSetName = "Outputs";
OutputSetName += "[" + std::to_string(i) + "]";
Table.Print(OS, "Inputs", OutputSetName.c_str());
}
if (IsHS()) {
OS << "Patch constant outputs affected by inputs as a table of "
"bitmasks:\n";
uint8_t InputVectors = m_pPSVRuntimeInfo1->SigInputVectors;
uint8_t OutputVectors = m_pPSVRuntimeInfo1->SigPatchConstOrPrimVectors;
const PSVDependencyTable Table(m_pInputToPCOutputTable, InputVectors,
OutputVectors);
Table.Print(OS, "Inputs", "PatchConstantOutputs");
} else if (IsDS()) {
OS << "Outputs affected by patch constant inputs as a table of "
"bitmasks:\n";
uint8_t InputVectors = m_pPSVRuntimeInfo1->SigPatchConstOrPrimVectors;
uint8_t OutputVectors = m_pPSVRuntimeInfo1->SigOutputVectors[0];
const PSVDependencyTable Table(m_pPCInputToOutputTable, InputVectors,
OutputVectors);
Table.Print(OS, "PatchConstantInputs", "Outputs");
}
}
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilContainer/DxilContainerAssembler.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilContainerAssembler.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides support for serializing a module into DXIL container structures. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DxilContainer/DxilContainerAssembler.h"
#include "dxc/DXIL/DxilCounters.h"
#include "dxc/DXIL/DxilEntryProps.h"
#include "dxc/DXIL/DxilFunctionProps.h"
#include "dxc/DXIL/DxilInstructions.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilShaderModel.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/DxilContainer/DxilPipelineStateValidation.h"
#include "dxc/DxilContainer/DxilRDATBuilder.h"
#include "dxc/DxilContainer/DxilRuntimeReflection.h"
#include "dxc/DxilRootSignature/DxilRootSignature.h"
#include "dxc/Support/FileIOHelper.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/Unicode.h"
#include "dxc/Support/WinIncludes.h"
#include "dxc/Support/dxcapi.impl.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/MD5.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include <algorithm>
#include <assert.h> // Needed for DxilPipelineStateValidation.h
#include <functional>
using namespace llvm;
using namespace hlsl;
using namespace hlsl::RDAT;
static_assert((unsigned)PSVShaderKind::Invalid ==
(unsigned)DXIL::ShaderKind::Invalid,
"otherwise, PSVShaderKind enum out of sync.");
static DxilProgramSigSemantic
KindToSystemValue(Semantic::Kind kind, DXIL::TessellatorDomain domain) {
switch (kind) {
case Semantic::Kind::Arbitrary:
return DxilProgramSigSemantic::Undefined;
case Semantic::Kind::VertexID:
return DxilProgramSigSemantic::VertexID;
case Semantic::Kind::InstanceID:
return DxilProgramSigSemantic::InstanceID;
case Semantic::Kind::Position:
return DxilProgramSigSemantic::Position;
case Semantic::Kind::Coverage:
return DxilProgramSigSemantic::Coverage;
case Semantic::Kind::InnerCoverage:
return DxilProgramSigSemantic::InnerCoverage;
case Semantic::Kind::PrimitiveID:
return DxilProgramSigSemantic::PrimitiveID;
case Semantic::Kind::SampleIndex:
return DxilProgramSigSemantic::SampleIndex;
case Semantic::Kind::IsFrontFace:
return DxilProgramSigSemantic::IsFrontFace;
case Semantic::Kind::RenderTargetArrayIndex:
return DxilProgramSigSemantic::RenderTargetArrayIndex;
case Semantic::Kind::ViewPortArrayIndex:
return DxilProgramSigSemantic::ViewPortArrayIndex;
case Semantic::Kind::ClipDistance:
return DxilProgramSigSemantic::ClipDistance;
case Semantic::Kind::CullDistance:
return DxilProgramSigSemantic::CullDistance;
case Semantic::Kind::Barycentrics:
return DxilProgramSigSemantic::Barycentrics;
case Semantic::Kind::ShadingRate:
return DxilProgramSigSemantic::ShadingRate;
case Semantic::Kind::CullPrimitive:
return DxilProgramSigSemantic::CullPrimitive;
case Semantic::Kind::TessFactor: {
switch (domain) {
case DXIL::TessellatorDomain::IsoLine:
// Will bu updated to DetailTessFactor in next row.
return DxilProgramSigSemantic::FinalLineDensityTessfactor;
case DXIL::TessellatorDomain::Tri:
return DxilProgramSigSemantic::FinalTriEdgeTessfactor;
case DXIL::TessellatorDomain::Quad:
return DxilProgramSigSemantic::FinalQuadEdgeTessfactor;
default:
// No other valid TesselatorDomain options.
return DxilProgramSigSemantic::Undefined;
}
}
case Semantic::Kind::InsideTessFactor: {
switch (domain) {
case DXIL::TessellatorDomain::IsoLine:
DXASSERT(0, "invalid semantic");
return DxilProgramSigSemantic::Undefined;
case DXIL::TessellatorDomain::Tri:
return DxilProgramSigSemantic::FinalTriInsideTessfactor;
case DXIL::TessellatorDomain::Quad:
return DxilProgramSigSemantic::FinalQuadInsideTessfactor;
default:
// No other valid DxilProgramSigSemantic options.
return DxilProgramSigSemantic::Undefined;
}
}
case Semantic::Kind::Invalid:
return DxilProgramSigSemantic::Undefined;
case Semantic::Kind::Target:
return DxilProgramSigSemantic::Target;
case Semantic::Kind::Depth:
return DxilProgramSigSemantic::Depth;
case Semantic::Kind::DepthLessEqual:
return DxilProgramSigSemantic::DepthLE;
case Semantic::Kind::DepthGreaterEqual:
return DxilProgramSigSemantic::DepthGE;
case Semantic::Kind::StencilRef:
LLVM_FALLTHROUGH;
default:
DXASSERT(kind == Semantic::Kind::StencilRef,
"else Invalid or switch is missing a case");
return DxilProgramSigSemantic::StencilRef;
}
// TODO: Final_* values need mappings
}
DxilProgramSigCompType hlsl::CompTypeToSigCompType(hlsl::CompType::Kind Kind,
bool i1ToUnknownCompat) {
switch (Kind) {
case CompType::Kind::I32:
return DxilProgramSigCompType::SInt32;
case CompType::Kind::I1:
// Validator 1.4 and below returned Unknown for i1
if (i1ToUnknownCompat)
return DxilProgramSigCompType::Unknown;
else
return DxilProgramSigCompType::UInt32;
case CompType::Kind::U32:
return DxilProgramSigCompType::UInt32;
case CompType::Kind::F32:
return DxilProgramSigCompType::Float32;
case CompType::Kind::I16:
return DxilProgramSigCompType::SInt16;
case CompType::Kind::I64:
return DxilProgramSigCompType::SInt64;
case CompType::Kind::U16:
return DxilProgramSigCompType::UInt16;
case CompType::Kind::U64:
return DxilProgramSigCompType::UInt64;
case CompType::Kind::F16:
return DxilProgramSigCompType::Float16;
case CompType::Kind::F64:
return DxilProgramSigCompType::Float64;
case CompType::Kind::Invalid:
LLVM_FALLTHROUGH;
default:
return DxilProgramSigCompType::Unknown;
}
}
static DxilProgramSigMinPrecision
CompTypeToSigMinPrecision(hlsl::CompType value) {
switch (value.GetKind()) {
case CompType::Kind::I32:
return DxilProgramSigMinPrecision::Default;
case CompType::Kind::U32:
return DxilProgramSigMinPrecision::Default;
case CompType::Kind::F32:
return DxilProgramSigMinPrecision::Default;
case CompType::Kind::I1:
return DxilProgramSigMinPrecision::Default;
case CompType::Kind::U64:
LLVM_FALLTHROUGH;
case CompType::Kind::I64:
LLVM_FALLTHROUGH;
case CompType::Kind::F64:
return DxilProgramSigMinPrecision::Default;
case CompType::Kind::I16:
return DxilProgramSigMinPrecision::SInt16;
case CompType::Kind::U16:
return DxilProgramSigMinPrecision::UInt16;
case CompType::Kind::F16:
return DxilProgramSigMinPrecision::Float16; // Float2_8 is not supported in
// DXIL.
case CompType::Kind::Invalid:
LLVM_FALLTHROUGH;
default:
return DxilProgramSigMinPrecision::Default;
}
}
template <typename T> struct sort_second {
bool operator()(const T &a, const T &b) {
return std::less<decltype(a.second)>()(a.second, b.second);
}
};
struct sort_sig {
bool operator()(const DxilProgramSignatureElement &a,
const DxilProgramSignatureElement &b) {
return (a.Stream < b.Stream) ||
((a.Stream == b.Stream) && (a.Register < b.Register)) ||
((a.Stream == b.Stream) && (a.Register == b.Register) &&
(a.SemanticName < b.SemanticName));
}
};
static uint8_t NegMask(uint8_t V) {
V ^= 0xF;
return V & 0xF;
}
class DxilProgramSignatureWriter : public DxilPartWriter {
private:
const DxilSignature &m_signature;
DXIL::TessellatorDomain m_domain;
bool m_isInput;
bool m_useMinPrecision;
bool m_bCompat_1_4;
bool m_bCompat_1_6; // unaligned size, no dedup for < 1.7
size_t m_fixedSize;
typedef std::pair<const char *, uint32_t> NameOffsetPair_nodedup;
typedef llvm::SmallMapVector<const char *, uint32_t, 8> NameOffsetMap_nodedup;
typedef std::pair<llvm::StringRef, uint32_t> NameOffsetPair;
typedef llvm::SmallMapVector<llvm::StringRef, uint32_t, 8> NameOffsetMap;
uint32_t m_lastOffset;
NameOffsetMap_nodedup m_semanticNameOffsets_nodedup;
NameOffsetMap m_semanticNameOffsets;
unsigned m_paramCount;
const char *GetSemanticName(const hlsl::DxilSignatureElement *pElement) {
DXASSERT_NOMSG(pElement != nullptr);
DXASSERT(pElement->GetName() != nullptr, "else sig is malformed");
return pElement->GetName();
}
uint32_t
GetSemanticOffset_nodedup(const hlsl::DxilSignatureElement *pElement) {
const char *pName = GetSemanticName(pElement);
NameOffsetMap_nodedup::iterator nameOffset =
m_semanticNameOffsets_nodedup.find(pName);
uint32_t result;
if (nameOffset == m_semanticNameOffsets_nodedup.end()) {
result = m_lastOffset;
m_semanticNameOffsets_nodedup.insert(
NameOffsetPair_nodedup(pName, result));
m_lastOffset += strlen(pName) + 1;
} else {
result = nameOffset->second;
}
return result;
}
uint32_t GetSemanticOffset(const hlsl::DxilSignatureElement *pElement) {
if (m_bCompat_1_6)
return GetSemanticOffset_nodedup(pElement);
StringRef name = GetSemanticName(pElement);
NameOffsetMap::iterator nameOffset = m_semanticNameOffsets.find(name);
uint32_t result;
if (nameOffset == m_semanticNameOffsets.end()) {
result = m_lastOffset;
m_semanticNameOffsets.insert(NameOffsetPair(name, result));
m_lastOffset += name.size() + 1;
} else {
result = nameOffset->second;
}
return result;
}
void write(std::vector<DxilProgramSignatureElement> &orderedSig,
const hlsl::DxilSignatureElement *pElement) {
const std::vector<unsigned> &indexVec = pElement->GetSemanticIndexVec();
unsigned eltCount = pElement->GetSemanticIndexVec().size();
unsigned eltRows = 1;
if (eltCount)
eltRows = pElement->GetRows() / eltCount;
DXASSERT_NOMSG(eltRows == 1);
DxilProgramSignatureElement sig;
memset(&sig, 0, sizeof(DxilProgramSignatureElement));
sig.Stream = pElement->GetOutputStream();
sig.SemanticName = GetSemanticOffset(pElement);
sig.SystemValue = KindToSystemValue(pElement->GetKind(), m_domain);
sig.CompType =
CompTypeToSigCompType(pElement->GetCompType().GetKind(), m_bCompat_1_4);
sig.Register = pElement->GetStartRow();
sig.Mask = pElement->GetColsAsMask();
if (m_bCompat_1_4) {
// Match what validator 1.4 and below expects
// Only mark exist channel write for output.
// All channel not used for input.
if (!m_isInput)
sig.NeverWrites_Mask = ~sig.Mask;
else
sig.AlwaysReads_Mask = 0;
} else {
unsigned UsageMask = pElement->GetUsageMask();
if (pElement->IsAllocated())
UsageMask <<= pElement->GetStartCol();
if (!m_isInput)
sig.NeverWrites_Mask = NegMask(UsageMask);
else
sig.AlwaysReads_Mask = UsageMask;
}
sig.MinPrecision = m_useMinPrecision
? CompTypeToSigMinPrecision(pElement->GetCompType())
: DxilProgramSigMinPrecision::Default;
for (unsigned i = 0; i < eltCount; ++i) {
sig.SemanticIndex = indexVec[i];
orderedSig.emplace_back(sig);
if (pElement->IsAllocated())
sig.Register += eltRows;
if (sig.SystemValue == DxilProgramSigSemantic::FinalLineDensityTessfactor)
sig.SystemValue = DxilProgramSigSemantic::FinalLineDetailTessfactor;
}
}
void calcSizes() {
// Calculate size for signature elements.
const std::vector<std::unique_ptr<hlsl::DxilSignatureElement>> &elements =
m_signature.GetElements();
uint32_t result = sizeof(DxilProgramSignature);
m_paramCount = 0;
for (size_t i = 0; i < elements.size(); ++i) {
DXIL::SemanticInterpretationKind I = elements[i]->GetInterpretation();
if (I == DXIL::SemanticInterpretationKind::NA ||
I == DXIL::SemanticInterpretationKind::NotInSig)
continue;
unsigned semanticCount = elements[i]->GetSemanticIndexVec().size();
result += semanticCount * sizeof(DxilProgramSignatureElement);
m_paramCount += semanticCount;
}
m_fixedSize = result;
m_lastOffset = m_fixedSize;
// Calculate size for semantic strings.
for (size_t i = 0; i < elements.size(); ++i) {
GetSemanticOffset(elements[i].get());
}
}
public:
DxilProgramSignatureWriter(const DxilSignature &signature,
DXIL::TessellatorDomain domain, bool isInput,
bool UseMinPrecision, bool bCompat_1_4,
bool bCompat_1_6)
: m_signature(signature), m_domain(domain), m_isInput(isInput),
m_useMinPrecision(UseMinPrecision), m_bCompat_1_4(bCompat_1_4),
m_bCompat_1_6(bCompat_1_6) {
calcSizes();
}
uint32_t size() const override {
if (m_bCompat_1_6)
return m_lastOffset;
else
return PSVALIGN4(m_lastOffset);
}
void write(AbstractMemoryStream *pStream) override {
UINT64 startPos = pStream->GetPosition();
const std::vector<std::unique_ptr<hlsl::DxilSignatureElement>> &elements =
m_signature.GetElements();
DxilProgramSignature programSig;
programSig.ParamCount = m_paramCount;
programSig.ParamOffset = sizeof(DxilProgramSignature);
IFT(WriteStreamValue(pStream, programSig));
// Write structures in register order.
std::vector<DxilProgramSignatureElement> orderedSig;
for (size_t i = 0; i < elements.size(); ++i) {
DXIL::SemanticInterpretationKind I = elements[i]->GetInterpretation();
if (I == DXIL::SemanticInterpretationKind::NA ||
I == DXIL::SemanticInterpretationKind::NotInSig)
continue;
write(orderedSig, elements[i].get());
}
std::sort(orderedSig.begin(), orderedSig.end(), sort_sig());
for (size_t i = 0; i < orderedSig.size(); ++i) {
DxilProgramSignatureElement &sigElt = orderedSig[i];
IFT(WriteStreamValue(pStream, sigElt));
}
// Write strings in the offset order.
std::vector<NameOffsetPair> ordered;
if (m_bCompat_1_6) {
ordered.assign(m_semanticNameOffsets_nodedup.begin(),
m_semanticNameOffsets_nodedup.end());
} else {
ordered.assign(m_semanticNameOffsets.begin(),
m_semanticNameOffsets.end());
}
std::sort(ordered.begin(), ordered.end(), sort_second<NameOffsetPair>());
for (size_t i = 0; i < ordered.size(); ++i) {
StringRef name = ordered[i].first;
ULONG cbWritten;
UINT64 offsetPos = pStream->GetPosition();
DXASSERT_LOCALVAR(offsetPos, offsetPos - startPos == ordered[i].second,
"else str offset is incorrect");
IFT(pStream->Write(name.data(), name.size() + 1, &cbWritten));
}
// Align, and verify we wrote the same number of bytes we though we would.
UINT64 bytesWritten = pStream->GetPosition() - startPos;
if (!m_bCompat_1_6 && (bytesWritten % 4 != 0)) {
unsigned paddingToAdd = 4 - (bytesWritten % 4);
char padding[4] = {0};
ULONG cbWritten = 0;
IFT(pStream->Write(padding, paddingToAdd, &cbWritten));
bytesWritten += cbWritten;
}
DXASSERT(bytesWritten == size(), "else size is incorrect");
}
};
DxilPartWriter *hlsl::NewProgramSignatureWriter(const DxilModule &M,
DXIL::SignatureKind Kind) {
DXIL::TessellatorDomain domain = DXIL::TessellatorDomain::Undefined;
if (M.GetShaderModel()->IsHS() || M.GetShaderModel()->IsDS())
domain = M.GetTessellatorDomain();
unsigned ValMajor, ValMinor;
M.GetValidatorVersion(ValMajor, ValMinor);
bool bCompat_1_4 = DXIL::CompareVersions(ValMajor, ValMinor, 1, 5) < 0;
bool bCompat_1_6 = DXIL::CompareVersions(ValMajor, ValMinor, 1, 7) < 0;
switch (Kind) {
case DXIL::SignatureKind::Input:
return new DxilProgramSignatureWriter(M.GetInputSignature(), domain, true,
M.GetUseMinPrecision(), bCompat_1_4,
bCompat_1_6);
case DXIL::SignatureKind::Output:
return new DxilProgramSignatureWriter(M.GetOutputSignature(), domain, false,
M.GetUseMinPrecision(), bCompat_1_4,
bCompat_1_6);
case DXIL::SignatureKind::PatchConstOrPrim:
return new DxilProgramSignatureWriter(
M.GetPatchConstOrPrimSignature(), domain,
/*IsInput*/ M.GetShaderModel()->IsDS(),
/*UseMinPrecision*/ M.GetUseMinPrecision(), bCompat_1_4, bCompat_1_6);
case DXIL::SignatureKind::Invalid:
return nullptr;
}
return nullptr;
}
class DxilProgramRootSignatureWriter : public DxilPartWriter {
private:
const RootSignatureHandle &m_Sig;
public:
DxilProgramRootSignatureWriter(const RootSignatureHandle &S) : m_Sig(S) {}
uint32_t size() const { return m_Sig.GetSerializedSize(); }
void write(AbstractMemoryStream *pStream) {
ULONG cbWritten;
IFT(pStream->Write(m_Sig.GetSerializedBytes(), size(), &cbWritten));
}
};
DxilPartWriter *hlsl::NewRootSignatureWriter(const RootSignatureHandle &S) {
return new DxilProgramRootSignatureWriter(S);
}
class DxilFeatureInfoWriter : public DxilPartWriter {
private:
// Only save the shader properties after create class for it.
DxilShaderFeatureInfo featureInfo;
public:
DxilFeatureInfoWriter(const DxilModule &M) {
featureInfo.FeatureFlags = M.m_ShaderFlags.GetFeatureInfo();
}
uint32_t size() const override { return sizeof(DxilShaderFeatureInfo); }
void write(AbstractMemoryStream *pStream) override {
IFT(WriteStreamValue(pStream, featureInfo.FeatureFlags));
}
};
DxilPartWriter *hlsl::NewFeatureInfoWriter(const DxilModule &M) {
return new DxilFeatureInfoWriter(M);
}
//////////////////////////////////////////////////////////
// Utility code for serializing/deserializing ViewID state
// Code for ComputeSeriaizedViewIDStateSizeInUInts copied from
// ComputeViewIdState. It could be moved into some common location if this
// ViewID serialization/deserialization code were moved out of here.
static unsigned RoundUpToUINT(unsigned x) { return (x + 31) / 32; }
static unsigned ComputeSeriaizedViewIDStateSizeInUInts(
const PSVShaderKind SK, const bool bUsesViewID, const unsigned InputScalars,
const unsigned OutputScalars[4], const unsigned PCScalars) {
// Compute serialized state size in UINTs.
unsigned NumStreams = SK == PSVShaderKind::Geometry ? 4 : 1;
unsigned Size = 0;
Size += 1; // #Inputs.
for (unsigned StreamId = 0; StreamId < NumStreams; StreamId++) {
Size += 1; // #Outputs for stream StreamId.
unsigned NumOutputs = OutputScalars[StreamId];
unsigned NumOutUINTs = RoundUpToUINT(NumOutputs);
if (bUsesViewID) {
Size += NumOutUINTs; // m_OutputsDependentOnViewId[StreamId]
}
Size +=
InputScalars * NumOutUINTs; // m_InputsContributingToOutputs[StreamId]
}
if (SK == PSVShaderKind::Hull || SK == PSVShaderKind::Domain ||
SK == PSVShaderKind::Mesh) {
Size += 1; // #PatchConstant.
unsigned NumPCUINTs = RoundUpToUINT(PCScalars);
if (SK == PSVShaderKind::Hull || SK == PSVShaderKind::Mesh) {
if (bUsesViewID) {
Size += NumPCUINTs; // m_PCOrPrimOutputsDependentOnViewId
}
Size +=
InputScalars * NumPCUINTs; // m_InputsContributingToPCOrPrimOutputs
} else {
unsigned NumOutputs = OutputScalars[0];
unsigned NumOutUINTs = RoundUpToUINT(NumOutputs);
Size += PCScalars * NumOutUINTs; // m_PCInputsContributingToOutputs
}
}
return Size;
}
static const uint32_t *CopyViewIDStateForOutputToPSV(
const uint32_t *pSrc, uint32_t InputScalars, uint32_t OutputScalars,
PSVComponentMask ViewIDMask, PSVDependencyTable IOTable) {
unsigned MaskDwords =
PSVComputeMaskDwordsFromVectors(PSVALIGN4(OutputScalars) / 4);
if (ViewIDMask.IsValid()) {
DXASSERT_NOMSG(!IOTable.Table ||
ViewIDMask.NumVectors == IOTable.OutputVectors);
memcpy(ViewIDMask.Mask, pSrc, 4 * MaskDwords);
pSrc += MaskDwords;
}
if (IOTable.IsValid() && IOTable.InputVectors && IOTable.OutputVectors) {
DXASSERT_NOMSG((InputScalars <= IOTable.InputVectors * 4) &&
(IOTable.InputVectors * 4 - InputScalars < 4));
DXASSERT_NOMSG((OutputScalars <= IOTable.OutputVectors * 4) &&
(IOTable.OutputVectors * 4 - OutputScalars < 4));
memcpy(IOTable.Table, pSrc, 4 * MaskDwords * InputScalars);
pSrc += MaskDwords * InputScalars;
}
return pSrc;
}
static uint32_t *CopyViewIDStateForOutputFromPSV(uint32_t *pOutputData,
const unsigned InputScalars,
const unsigned OutputScalars,
PSVComponentMask ViewIDMask,
PSVDependencyTable IOTable) {
unsigned MaskDwords =
PSVComputeMaskDwordsFromVectors(PSVALIGN4(OutputScalars) / 4);
if (ViewIDMask.IsValid()) {
DXASSERT_NOMSG(!IOTable.Table ||
ViewIDMask.NumVectors == IOTable.OutputVectors);
for (unsigned i = 0; i < MaskDwords; i++)
*(pOutputData++) = ViewIDMask.Mask[i];
}
if (IOTable.IsValid() && IOTable.InputVectors && IOTable.OutputVectors) {
DXASSERT_NOMSG((InputScalars <= IOTable.InputVectors * 4) &&
(IOTable.InputVectors * 4 - InputScalars < 4));
DXASSERT_NOMSG((OutputScalars <= IOTable.OutputVectors * 4) &&
(IOTable.OutputVectors * 4 - OutputScalars < 4));
for (unsigned i = 0; i < MaskDwords * InputScalars; i++)
*(pOutputData++) = IOTable.Table[i];
}
return pOutputData;
}
void hlsl::StoreViewIDStateToPSV(const uint32_t *pInputData,
unsigned InputSizeInUInts,
DxilPipelineStateValidation &PSV) {
PSVRuntimeInfo1 *pInfo1 = PSV.GetPSVRuntimeInfo1();
DXASSERT(pInfo1, "otherwise, PSV does not meet version requirement.");
PSVShaderKind SK = static_cast<PSVShaderKind>(pInfo1->ShaderStage);
const unsigned OutputStreams = SK == PSVShaderKind::Geometry ? 4 : 1;
const uint32_t *pSrc = pInputData;
const uint32_t InputScalars = *(pSrc++);
uint32_t OutputScalars[4];
for (unsigned streamIndex = 0; streamIndex < OutputStreams; streamIndex++) {
OutputScalars[streamIndex] = *(pSrc++);
pSrc = CopyViewIDStateForOutputToPSV(
pSrc, InputScalars, OutputScalars[streamIndex],
PSV.GetViewIDOutputMask(streamIndex),
PSV.GetInputToOutputTable(streamIndex));
}
if (SK == PSVShaderKind::Hull || SK == PSVShaderKind::Mesh) {
const uint32_t PCScalars = *(pSrc++);
pSrc = CopyViewIDStateForOutputToPSV(pSrc, InputScalars, PCScalars,
PSV.GetViewIDPCOutputMask(),
PSV.GetInputToPCOutputTable());
} else if (SK == PSVShaderKind::Domain) {
const uint32_t PCScalars = *(pSrc++);
pSrc = CopyViewIDStateForOutputToPSV(pSrc, PCScalars, OutputScalars[0],
PSVComponentMask(),
PSV.GetPCInputToOutputTable());
}
DXASSERT((unsigned)(pSrc - pInputData) == InputSizeInUInts,
"otherwise, different amout of data written than expected.");
}
// This function is defined close to the serialization code in DxilPSVWriter to
// reduce the chance of a mismatch. It could be defined elsewhere, but it would
// make sense to move both the serialization and deserialization out of here and
// into a common location.
unsigned hlsl::LoadViewIDStateFromPSV(unsigned *pOutputData,
unsigned OutputSizeInUInts,
const DxilPipelineStateValidation &PSV) {
PSVRuntimeInfo1 *pInfo1 = PSV.GetPSVRuntimeInfo1();
if (!pInfo1) {
return 0;
}
PSVShaderKind SK = static_cast<PSVShaderKind>(pInfo1->ShaderStage);
const unsigned OutputStreams = SK == PSVShaderKind::Geometry ? 4 : 1;
const unsigned InputScalars = pInfo1->SigInputVectors * 4;
unsigned OutputScalars[4];
for (unsigned streamIndex = 0; streamIndex < OutputStreams; streamIndex++) {
OutputScalars[streamIndex] = pInfo1->SigOutputVectors[streamIndex] * 4;
}
unsigned PCScalars = 0;
if (SK == PSVShaderKind::Hull || SK == PSVShaderKind::Mesh ||
SK == PSVShaderKind::Domain) {
PCScalars = pInfo1->SigPatchConstOrPrimVectors * 4;
}
if (pOutputData == nullptr) {
return ComputeSeriaizedViewIDStateSizeInUInts(
SK, pInfo1->UsesViewID != 0, InputScalars, OutputScalars, PCScalars);
}
// Fill in serialized viewid buffer.
DXASSERT(ComputeSeriaizedViewIDStateSizeInUInts(
SK, pInfo1->UsesViewID != 0, InputScalars, OutputScalars,
PCScalars) == OutputSizeInUInts,
"otherwise, OutputSize doesn't match computed size.");
unsigned *pStartOutputData = pOutputData;
*(pOutputData++) = InputScalars;
for (unsigned streamIndex = 0; streamIndex < OutputStreams; streamIndex++) {
*(pOutputData++) = OutputScalars[streamIndex];
pOutputData = CopyViewIDStateForOutputFromPSV(
pOutputData, InputScalars, OutputScalars[streamIndex],
PSV.GetViewIDOutputMask(streamIndex),
PSV.GetInputToOutputTable(streamIndex));
}
if (SK == PSVShaderKind::Hull || SK == PSVShaderKind::Mesh) {
*(pOutputData++) = PCScalars;
pOutputData = CopyViewIDStateForOutputFromPSV(
pOutputData, InputScalars, PCScalars, PSV.GetViewIDPCOutputMask(),
PSV.GetInputToPCOutputTable());
} else if (SK == PSVShaderKind::Domain) {
*(pOutputData++) = PCScalars;
pOutputData = CopyViewIDStateForOutputFromPSV(
pOutputData, PCScalars, OutputScalars[0], PSVComponentMask(),
PSV.GetPCInputToOutputTable());
}
DXASSERT((unsigned)(pOutputData - pStartOutputData) == OutputSizeInUInts,
"otherwise, OutputSizeInUInts didn't match size written.");
return pOutputData - pStartOutputData;
}
//////////////////////////////////////////////////////////
// DxilPSVWriter - Writes PSV0 part
class DxilPSVWriter : public DxilPartWriter {
private:
const DxilModule &m_Module;
unsigned m_ValMajor = 0, m_ValMinor = 0;
PSVInitInfo m_PSVInitInfo;
DxilPipelineStateValidation m_PSV;
uint32_t m_PSVBufferSize = 0;
SmallVector<char, 512> m_PSVBuffer;
SmallVector<char, 256> m_StringBuffer;
SmallVector<uint32_t, 8> m_SemanticIndexBuffer;
std::vector<PSVSignatureElement0> m_SigInputElements;
std::vector<PSVSignatureElement0> m_SigOutputElements;
std::vector<PSVSignatureElement0> m_SigPatchConstOrPrimElements;
unsigned EntryFunctionName = 0;
void SetPSVSigElement(PSVSignatureElement0 &E,
const DxilSignatureElement &SE) {
memset(&E, 0, sizeof(PSVSignatureElement0));
bool i1ToUnknownCompat =
DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 5) < 0;
InitPSVSignatureElement(E, SE, i1ToUnknownCompat);
// Setup semantic name.
if (SE.GetKind() == DXIL::SemanticKind::Arbitrary &&
strlen(SE.GetName()) > 0) {
E.SemanticName = (uint32_t)m_StringBuffer.size();
StringRef Name(SE.GetName());
m_StringBuffer.append(Name.size() + 1, '\0');
memcpy(m_StringBuffer.data() + E.SemanticName, Name.data(), Name.size());
} else {
// m_StringBuffer always starts with '\0' so offset 0 is empty string:
E.SemanticName = 0;
}
// Search index buffer for matching semantic index sequence
DXASSERT_NOMSG(SE.GetRows() == SE.GetSemanticIndexVec().size());
auto &SemIdx = SE.GetSemanticIndexVec();
bool match = false;
for (uint32_t offset = 0;
offset + SE.GetRows() - 1 < m_SemanticIndexBuffer.size(); offset++) {
match = true;
for (uint32_t row = 0; row < SE.GetRows(); row++) {
if ((uint32_t)SemIdx[row] != m_SemanticIndexBuffer[offset + row]) {
match = false;
break;
}
}
if (match) {
E.SemanticIndexes = offset;
break;
}
}
if (!match) {
E.SemanticIndexes = m_SemanticIndexBuffer.size();
for (uint32_t row = 0; row < SemIdx.size(); row++) {
m_SemanticIndexBuffer.push_back((uint32_t)SemIdx[row]);
}
}
}
public:
DxilPSVWriter(const DxilModule &mod, uint32_t PSVVersion = UINT_MAX)
: m_Module(mod), m_PSVInitInfo(PSVVersion) {
m_Module.GetValidatorVersion(m_ValMajor, m_ValMinor);
// Constraint PSVVersion based on validator version
if (PSVVersion > 0 &&
DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 1) < 0)
m_PSVInitInfo.PSVVersion = 0;
else if (PSVVersion > 1 &&
DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 6) < 0)
m_PSVInitInfo.PSVVersion = 1;
else if (PSVVersion > 2 &&
DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 8) < 0)
m_PSVInitInfo.PSVVersion = 2;
else if (PSVVersion > MAX_PSV_VERSION)
m_PSVInitInfo.PSVVersion = MAX_PSV_VERSION;
const ShaderModel *SM = m_Module.GetShaderModel();
UINT uCBuffers = m_Module.GetCBuffers().size();
UINT uSamplers = m_Module.GetSamplers().size();
UINT uSRVs = m_Module.GetSRVs().size();
UINT uUAVs = m_Module.GetUAVs().size();
m_PSVInitInfo.ResourceCount = uCBuffers + uSamplers + uSRVs + uUAVs;
// TODO: for >= 6.2 version, create more efficient structure
if (m_PSVInitInfo.PSVVersion > 0) {
m_PSVInitInfo.ShaderStage = (PSVShaderKind)SM->GetKind();
// Copy Dxil Signatures
m_StringBuffer.push_back('\0'); // For empty semantic name (system value)
m_PSVInitInfo.SigInputElements =
m_Module.GetInputSignature().GetElements().size();
m_SigInputElements.resize(m_PSVInitInfo.SigInputElements);
m_PSVInitInfo.SigOutputElements =
m_Module.GetOutputSignature().GetElements().size();
m_SigOutputElements.resize(m_PSVInitInfo.SigOutputElements);
m_PSVInitInfo.SigPatchConstOrPrimElements =
m_Module.GetPatchConstOrPrimSignature().GetElements().size();
m_SigPatchConstOrPrimElements.resize(
m_PSVInitInfo.SigPatchConstOrPrimElements);
uint32_t i = 0;
for (auto &SE : m_Module.GetInputSignature().GetElements()) {
SetPSVSigElement(m_SigInputElements[i++], *(SE.get()));
}
i = 0;
for (auto &SE : m_Module.GetOutputSignature().GetElements()) {
SetPSVSigElement(m_SigOutputElements[i++], *(SE.get()));
}
i = 0;
for (auto &SE : m_Module.GetPatchConstOrPrimSignature().GetElements()) {
SetPSVSigElement(m_SigPatchConstOrPrimElements[i++], *(SE.get()));
}
// Add entry function name to string table in version 3 and above.
if (m_PSVInitInfo.PSVVersion > 2) {
EntryFunctionName = (uint32_t)m_StringBuffer.size();
StringRef Name(m_Module.GetEntryFunctionName());
m_StringBuffer.append(Name.size() + 1, '\0');
memcpy(m_StringBuffer.data() + EntryFunctionName, Name.data(),
Name.size());
}
// Set String and SemanticInput Tables
m_PSVInitInfo.StringTable.Table = m_StringBuffer.data();
m_PSVInitInfo.StringTable.Size = m_StringBuffer.size();
m_PSVInitInfo.SemanticIndexTable.Table = m_SemanticIndexBuffer.data();
m_PSVInitInfo.SemanticIndexTable.Entries = m_SemanticIndexBuffer.size();
// Set up ViewID and signature dependency info
m_PSVInitInfo.UsesViewID =
m_Module.m_ShaderFlags.GetViewID() ? true : false;
m_PSVInitInfo.SigInputVectors =
m_Module.GetInputSignature().NumVectorsUsed(0);
for (unsigned streamIndex = 0; streamIndex < 4; streamIndex++) {
m_PSVInitInfo.SigOutputVectors[streamIndex] =
m_Module.GetOutputSignature().NumVectorsUsed(streamIndex);
}
m_PSVInitInfo.SigPatchConstOrPrimVectors = 0;
if (SM->IsHS() || SM->IsDS() || SM->IsMS()) {
m_PSVInitInfo.SigPatchConstOrPrimVectors =
m_Module.GetPatchConstOrPrimSignature().NumVectorsUsed(0);
}
}
if (!m_PSV.InitNew(m_PSVInitInfo, nullptr, &m_PSVBufferSize)) {
DXASSERT(false, "PSV InitNew failed computing size!");
}
}
uint32_t size() const override { return m_PSVBufferSize; }
void write(AbstractMemoryStream *pStream) override {
// Do not add any data in write() which wasn't accounted for already in the
// constructor, where we compute the size based on m_PSVInitInfo.
m_PSVBuffer.resize(m_PSVBufferSize);
if (!m_PSV.InitNew(m_PSVInitInfo, m_PSVBuffer.data(), &m_PSVBufferSize)) {
DXASSERT(false, "PSV InitNew failed!");
}
DXASSERT_NOMSG(m_PSVBuffer.size() == m_PSVBufferSize);
// Set DxilRuntimeInfo
PSVRuntimeInfo0 *pInfo = m_PSV.GetPSVRuntimeInfo0();
PSVRuntimeInfo1 *pInfo1 = m_PSV.GetPSVRuntimeInfo1();
PSVRuntimeInfo2 *pInfo2 = m_PSV.GetPSVRuntimeInfo2();
PSVRuntimeInfo3 *pInfo3 = m_PSV.GetPSVRuntimeInfo3();
hlsl::InitPSVRuntimeInfo(pInfo, pInfo1, pInfo2, pInfo3, m_Module);
if (pInfo3)
pInfo3->EntryFunctionName = EntryFunctionName;
// Set resource binding information
UINT uResIndex = 0;
for (auto &&R : m_Module.GetCBuffers()) {
DXASSERT_NOMSG(uResIndex < m_PSVInitInfo.ResourceCount);
PSVResourceBindInfo0 *pBindInfo =
m_PSV.GetPSVResourceBindInfo0(uResIndex);
PSVResourceBindInfo1 *pBindInfo1 =
m_PSV.GetPSVResourceBindInfo1(uResIndex);
DXASSERT_NOMSG(pBindInfo);
InitPSVResourceBinding(pBindInfo, pBindInfo1, R.get());
uResIndex++;
}
for (auto &&R : m_Module.GetSamplers()) {
DXASSERT_NOMSG(uResIndex < m_PSVInitInfo.ResourceCount);
PSVResourceBindInfo0 *pBindInfo =
m_PSV.GetPSVResourceBindInfo0(uResIndex);
PSVResourceBindInfo1 *pBindInfo1 =
m_PSV.GetPSVResourceBindInfo1(uResIndex);
DXASSERT_NOMSG(pBindInfo);
InitPSVResourceBinding(pBindInfo, pBindInfo1, R.get());
uResIndex++;
}
for (auto &&R : m_Module.GetSRVs()) {
DXASSERT_NOMSG(uResIndex < m_PSVInitInfo.ResourceCount);
PSVResourceBindInfo0 *pBindInfo =
m_PSV.GetPSVResourceBindInfo0(uResIndex);
PSVResourceBindInfo1 *pBindInfo1 =
m_PSV.GetPSVResourceBindInfo1(uResIndex);
DXASSERT_NOMSG(pBindInfo);
InitPSVResourceBinding(pBindInfo, pBindInfo1, R.get());
uResIndex++;
}
for (auto &&R : m_Module.GetUAVs()) {
DXASSERT_NOMSG(uResIndex < m_PSVInitInfo.ResourceCount);
PSVResourceBindInfo0 *pBindInfo =
m_PSV.GetPSVResourceBindInfo0(uResIndex);
PSVResourceBindInfo1 *pBindInfo1 =
m_PSV.GetPSVResourceBindInfo1(uResIndex);
DXASSERT_NOMSG(pBindInfo);
InitPSVResourceBinding(pBindInfo, pBindInfo1, R.get());
uResIndex++;
}
DXASSERT_NOMSG(uResIndex == m_PSVInitInfo.ResourceCount);
if (m_PSVInitInfo.PSVVersion > 0) {
DXASSERT_NOMSG(pInfo1);
// Write Dxil Signature Elements
for (unsigned i = 0; i < m_PSV.GetSigInputElements(); i++) {
PSVSignatureElement0 *pInputElement = m_PSV.GetInputElement0(i);
DXASSERT_NOMSG(pInputElement);
memcpy(pInputElement, &m_SigInputElements[i],
sizeof(PSVSignatureElement0));
}
for (unsigned i = 0; i < m_PSV.GetSigOutputElements(); i++) {
PSVSignatureElement0 *pOutputElement = m_PSV.GetOutputElement0(i);
DXASSERT_NOMSG(pOutputElement);
memcpy(pOutputElement, &m_SigOutputElements[i],
sizeof(PSVSignatureElement0));
}
for (unsigned i = 0; i < m_PSV.GetSigPatchConstOrPrimElements(); i++) {
PSVSignatureElement0 *pPatchConstOrPrimElement =
m_PSV.GetPatchConstOrPrimElement0(i);
DXASSERT_NOMSG(pPatchConstOrPrimElement);
memcpy(pPatchConstOrPrimElement, &m_SigPatchConstOrPrimElements[i],
sizeof(PSVSignatureElement0));
}
// Gather ViewID dependency information
auto &viewState = m_Module.GetSerializedViewIdState();
if (!viewState.empty()) {
StoreViewIDStateToPSV(viewState.data(), (unsigned)viewState.size(),
m_PSV);
}
}
// Ensure that these buffers were not modified after m_PSVInitInfo was set.
DXASSERT((uint32_t)m_StringBuffer.size() == m_PSVInitInfo.StringTable.Size,
"otherwise m_StringBuffer modified after m_PSVInitInfo set.");
DXASSERT(
(uint32_t)m_SemanticIndexBuffer.size() ==
m_PSVInitInfo.SemanticIndexTable.Entries,
"otherwise m_SemanticIndexBuffer modified after m_PSVInitInfo set.");
ULONG cbWritten;
IFT(pStream->Write(m_PSVBuffer.data(), m_PSVBufferSize, &cbWritten));
DXASSERT_NOMSG(cbWritten == m_PSVBufferSize);
}
};
//////////////////////////////////////////////////////////
// DxilVersionWriter - Writes VERS part
class DxilVersionWriter : public DxilPartWriter {
hlsl::DxilCompilerVersion m_Header = {};
CComHeapPtr<char> m_CommitShaStorage;
llvm::StringRef m_CommitSha = "";
CComHeapPtr<char> m_CustomStringStorage;
llvm::StringRef m_CustomString = "";
public:
DxilVersionWriter(IDxcVersionInfo *pVersion) { Init(pVersion); }
void Init(IDxcVersionInfo *pVersionInfo) {
m_Header = {};
UINT32 Major = 0, Minor = 0;
UINT32 Flags = 0;
IFT(pVersionInfo->GetVersion(&Major, &Minor));
IFT(pVersionInfo->GetFlags(&Flags));
m_Header.Major = Major;
m_Header.Minor = Minor;
m_Header.VersionFlags = Flags;
CComPtr<IDxcVersionInfo2> pVersionInfo2;
if (SUCCEEDED(pVersionInfo->QueryInterface(&pVersionInfo2))) {
UINT32 CommitCount = 0;
IFT(pVersionInfo2->GetCommitInfo(&CommitCount, &m_CommitShaStorage));
m_CommitSha = llvm::StringRef(m_CommitShaStorage.m_pData,
strlen(m_CommitShaStorage.m_pData));
m_Header.CommitCount = CommitCount;
m_Header.VersionStringListSizeInBytes += m_CommitSha.size();
}
m_Header.VersionStringListSizeInBytes += /*null term*/ 1;
CComPtr<IDxcVersionInfo3> pVersionInfo3;
if (SUCCEEDED(pVersionInfo->QueryInterface(&pVersionInfo3))) {
IFT(pVersionInfo3->GetCustomVersionString(&m_CustomStringStorage));
m_CustomString = llvm::StringRef(m_CustomStringStorage,
strlen(m_CustomStringStorage.m_pData));
m_Header.VersionStringListSizeInBytes += m_CustomString.size();
}
m_Header.VersionStringListSizeInBytes += /*null term*/ 1;
}
static uint32_t PadToDword(uint32_t size, uint32_t *outNumPadding = nullptr) {
uint32_t rem = size % 4;
if (rem) {
uint32_t padding = (4 - rem);
if (outNumPadding)
*outNumPadding = padding;
return size + padding;
}
if (outNumPadding)
*outNumPadding = 0;
return size;
}
UINT32 size() const override {
return PadToDword(sizeof(m_Header) + m_Header.VersionStringListSizeInBytes);
}
void write(AbstractMemoryStream *pStream) override {
const uint8_t padByte = 0;
UINT32 uPadding = 0;
UINT32 uSize = PadToDword(
sizeof(m_Header) + m_Header.VersionStringListSizeInBytes, &uPadding);
(void)uSize;
ULONG cbWritten = 0;
IFT(pStream->Write(&m_Header, sizeof(m_Header), &cbWritten));
// Write a null terminator even if the string is empty
IFT(pStream->Write(m_CommitSha.data(), m_CommitSha.size(), &cbWritten));
// Null terminator for the commit sha
IFT(pStream->Write(&padByte, sizeof(padByte), &cbWritten));
// Write the custom version string.
IFT(pStream->Write(m_CustomString.data(), m_CustomString.size(),
&cbWritten));
// Null terminator for the custom version string.
IFT(pStream->Write(&padByte, sizeof(padByte), &cbWritten));
// Write padding
for (unsigned i = 0; i < uPadding; i++) {
IFT(pStream->Write(&padByte, sizeof(padByte), &cbWritten));
}
}
};
using namespace DXIL;
class DxilRDATWriter : public DxilPartWriter {
private:
DxilRDATBuilder Builder;
RDATTable *m_pResourceTable;
RDATTable *m_pFunctionTable;
RDATTable *m_pSubobjectTable;
typedef llvm::SmallSetVector<uint32_t, 8> Indices;
typedef std::unordered_map<const llvm::Function *, Indices> FunctionIndexMap;
FunctionIndexMap m_FuncToResNameOffset; // list of resources used
FunctionIndexMap m_FuncToDependencies; // list of unresolved functions used
unsigned m_ValMajor, m_ValMinor;
void
FindUsingFunctions(const llvm::Value *User,
llvm::SmallVectorImpl<const llvm::Function *> &functions) {
if (const llvm::Instruction *I = dyn_cast<const llvm::Instruction>(User)) {
// Instruction should be inside a basic block, which is in a function
functions.push_back(
cast<const llvm::Function>(I->getParent()->getParent()));
return;
}
// User can be either instruction, constant, or operator. But User is an
// operator only if constant is a scalar value, not resource pointer.
const llvm::Constant *CU = cast<const llvm::Constant>(User);
for (auto U : CU->users())
FindUsingFunctions(U, functions);
}
void UpdateFunctionToResourceInfo(const DxilResourceBase *resource,
uint32_t offset) {
Constant *var = resource->GetGlobalSymbol();
if (var) {
for (auto user : var->users()) {
// Find the function(s).
llvm::SmallVector<const llvm::Function *, 8> functions;
FindUsingFunctions(user, functions);
for (const llvm::Function *F : functions) {
if (m_FuncToResNameOffset.find(F) == m_FuncToResNameOffset.end()) {
m_FuncToResNameOffset[F] = Indices();
}
m_FuncToResNameOffset[F].insert(offset);
}
}
}
}
void InsertToResourceTable(DxilResourceBase &resource,
ResourceClass resourceClass,
uint32_t &resourceIndex) {
uint32_t stringIndex = Builder.InsertString(resource.GetGlobalName());
UpdateFunctionToResourceInfo(&resource, resourceIndex++);
RDAT::RuntimeDataResourceInfo info = {};
info.ID = resource.GetID();
info.Class = static_cast<uint32_t>(resourceClass);
info.Kind = static_cast<uint32_t>(resource.GetKind());
info.Space = resource.GetSpaceID();
info.LowerBound = resource.GetLowerBound();
info.UpperBound = resource.GetUpperBound();
info.Name = stringIndex;
info.Flags = 0;
if (ResourceClass::UAV == resourceClass) {
DxilResource *pRes = static_cast<DxilResource *>(&resource);
if (pRes->HasCounter())
info.Flags |= static_cast<uint32_t>(RDAT::DxilResourceFlag::UAVCounter);
if (pRes->IsGloballyCoherent())
info.Flags |=
static_cast<uint32_t>(RDAT::DxilResourceFlag::UAVGloballyCoherent);
if (pRes->IsROV())
info.Flags |= static_cast<uint32_t>(
RDAT::DxilResourceFlag::UAVRasterizerOrderedView);
if (pRes->HasAtomic64Use())
info.Flags |=
static_cast<uint32_t>(RDAT::DxilResourceFlag::Atomics64Use);
// TODO: add dynamic index flag
}
m_pResourceTable->Insert(info);
}
void UpdateResourceInfo(const DxilModule &DM) {
// Try to allocate string table for resources. String table is a sequence
// of strings delimited by \0
uint32_t resourceIndex = 0;
for (auto &resource : DM.GetCBuffers()) {
InsertToResourceTable(*resource.get(), ResourceClass::CBuffer,
resourceIndex);
}
for (auto &resource : DM.GetSamplers()) {
InsertToResourceTable(*resource.get(), ResourceClass::Sampler,
resourceIndex);
}
for (auto &resource : DM.GetSRVs()) {
InsertToResourceTable(*resource.get(), ResourceClass::SRV, resourceIndex);
}
for (auto &resource : DM.GetUAVs()) {
InsertToResourceTable(*resource.get(), ResourceClass::UAV, resourceIndex);
}
}
void UpdateFunctionDependency(llvm::Function *F) {
for (const llvm::User *user : F->users()) {
llvm::SmallVector<const llvm::Function *, 8> functions;
FindUsingFunctions(user, functions);
for (const llvm::Function *userFunction : functions) {
uint32_t index = Builder.InsertString(F->getName());
if (m_FuncToDependencies.find(userFunction) ==
m_FuncToDependencies.end()) {
m_FuncToDependencies[userFunction] = Indices();
}
m_FuncToDependencies[userFunction].insert(index);
}
}
}
uint32_t AddSigElements(const DxilSignature &sig, uint32_t &shaderFlags,
uint8_t *pOutputStreamMask = nullptr) {
shaderFlags = 0; // Fresh flags each call
SmallVector<uint32_t, 16> rdatElements;
for (auto &&E : sig.GetElements()) {
RDAT::SignatureElement e = {};
e.SemanticName = Builder.InsertString(E->GetSemanticName());
e.SemanticIndices = Builder.InsertArray(E->GetSemanticIndexVec().begin(),
E->GetSemanticIndexVec().end());
e.SemanticKind = (uint8_t)E->GetKind();
e.ComponentType = (uint8_t)E->GetCompType().GetKind();
e.InterpolationMode = (uint8_t)E->GetInterpolationMode()->GetKind();
e.StartRow = E->IsAllocated() ? E->GetStartRow() : 0xFF;
e.SetCols(E->GetCols());
e.SetStartCol(E->GetStartCol());
e.SetOutputStream(E->GetOutputStream());
e.SetUsageMask(E->GetUsageMask());
e.SetDynamicIndexMask(E->GetDynIdxCompMask());
rdatElements.push_back(Builder.InsertRecord(e));
if (E->GetKind() == DXIL::SemanticKind::Position)
shaderFlags |= (uint32_t)DxilShaderFlags::OutputPositionPresent;
if (E->GetInterpolationMode()->IsAnySample() ||
E->GetKind() == Semantic::Kind::SampleIndex)
shaderFlags |= (uint32_t)DxilShaderFlags::SampleFrequency;
if (E->IsAnyDepth())
shaderFlags |= (uint32_t)DxilShaderFlags::DepthOutput;
if (pOutputStreamMask)
*pOutputStreamMask |= 1 << E->GetOutputStream();
}
return Builder.InsertArray(rdatElements.begin(), rdatElements.end());
}
uint32_t AddIONodes(const std::vector<NodeIOProperties> &nodes) {
SmallVector<uint32_t, 16> rdatNodes;
for (auto &N : nodes) {
RDAT::IONode ioNode = {};
ioNode.IOFlagsAndKind = N.Flags;
SmallVector<uint32_t, 16> nodeAttribs;
RDAT::NodeShaderIOAttrib nAttrib = {};
if (N.Flags.IsOutputNode()) {
nAttrib = {};
nAttrib.AttribKind = (uint32_t)NodeAttribKind::OutputID;
RDAT::NodeID ID = {};
ID.Name = Builder.InsertString(N.OutputID.Name);
ID.Index = N.OutputID.Index;
nAttrib.OutputID = Builder.InsertRecord(ID);
nodeAttribs.push_back(Builder.InsertRecord(nAttrib));
nAttrib = {};
nAttrib.AttribKind = (uint32_t)NodeAttribKind::OutputArraySize;
nAttrib.OutputArraySize = N.OutputArraySize;
nodeAttribs.push_back(Builder.InsertRecord(nAttrib));
// Only include if these are specified
if (N.MaxRecords) {
nAttrib = {};
nAttrib.AttribKind = (uint32_t)NodeAttribKind::MaxRecords;
nAttrib.MaxRecords = N.MaxRecords;
nodeAttribs.push_back(Builder.InsertRecord(nAttrib));
} else if (N.MaxRecordsSharedWith >= 0) {
nAttrib = {};
nAttrib.AttribKind =
(uint32_t)RDAT::NodeAttribKind::MaxRecordsSharedWith;
nAttrib.MaxRecordsSharedWith = N.MaxRecordsSharedWith;
nodeAttribs.push_back(Builder.InsertRecord(nAttrib));
}
if (N.AllowSparseNodes) {
nAttrib = {};
nAttrib.AttribKind = (uint32_t)RDAT::NodeAttribKind::AllowSparseNodes;
nAttrib.AllowSparseNodes = N.AllowSparseNodes;
nodeAttribs.push_back(Builder.InsertRecord(nAttrib));
}
} else if (N.Flags.IsInputRecord()) {
if (N.MaxRecords) {
nAttrib = {};
nAttrib.AttribKind = (uint32_t)NodeAttribKind::MaxRecords;
nAttrib.MaxRecords = N.MaxRecords;
nodeAttribs.push_back(Builder.InsertRecord(nAttrib));
}
}
// Common attributes
if (N.RecordType.size) {
nAttrib = {};
nAttrib.AttribKind = (uint32_t)NodeAttribKind::RecordSizeInBytes;
nAttrib.RecordSizeInBytes = N.RecordType.size;
nodeAttribs.push_back(Builder.InsertRecord(nAttrib));
if (N.RecordType.SV_DispatchGrid.ComponentType !=
DXIL::ComponentType::Invalid) {
nAttrib = {};
nAttrib.AttribKind = (uint32_t)NodeAttribKind::RecordDispatchGrid;
nAttrib.RecordDispatchGrid.ByteOffset =
(uint16_t)N.RecordType.SV_DispatchGrid.ByteOffset;
nAttrib.RecordDispatchGrid.SetComponentType(
N.RecordType.SV_DispatchGrid.ComponentType);
nAttrib.RecordDispatchGrid.SetNumComponents(
N.RecordType.SV_DispatchGrid.NumComponents);
nodeAttribs.push_back(Builder.InsertRecord(nAttrib));
}
if (N.RecordType.alignment) {
nAttrib = {};
nAttrib.AttribKind = (uint32_t)NodeAttribKind::RecordAlignmentInBytes;
nAttrib.RecordAlignmentInBytes = N.RecordType.alignment;
nodeAttribs.push_back(Builder.InsertRecord(nAttrib));
}
}
ioNode.Attribs =
Builder.InsertArray(nodeAttribs.begin(), nodeAttribs.end());
rdatNodes.push_back(Builder.InsertRecord(ioNode));
}
return Builder.InsertArray(rdatNodes.begin(), rdatNodes.end());
}
uint32_t AddShaderInfo(llvm::Function &function,
const DxilEntryProps &entryProps,
RuntimeDataFunctionInfo2 &funcInfo,
const ShaderFlags &flags, uint32_t tgsmSizeInBytes) {
const DxilFunctionProps &props = entryProps.props;
const DxilEntrySignature &sig = entryProps.sig;
if (flags.GetViewID())
funcInfo.ShaderFlags |= (uint16_t)DxilShaderFlags::UsesViewID;
uint32_t shaderFlags = 0;
switch (props.shaderKind) {
case ShaderKind::Pixel: {
RDAT::PSInfo info = {};
info.SigInputElements = AddSigElements(sig.InputSignature, shaderFlags);
funcInfo.ShaderFlags |=
(uint16_t)(shaderFlags & (uint16_t)DxilShaderFlags::SampleFrequency);
info.SigOutputElements = AddSigElements(sig.OutputSignature, shaderFlags);
funcInfo.ShaderFlags |=
(uint16_t)(shaderFlags & (uint16_t)DxilShaderFlags::DepthOutput);
return Builder.InsertRecord(info);
} break;
case ShaderKind::Vertex: {
RDAT::VSInfo info = {};
info.SigInputElements = AddSigElements(sig.InputSignature, shaderFlags);
info.SigOutputElements = AddSigElements(sig.OutputSignature, shaderFlags);
funcInfo.ShaderFlags |=
(uint16_t)(shaderFlags &
(uint16_t)DxilShaderFlags::OutputPositionPresent);
// TODO: Fill in ViewID related masks
return Builder.InsertRecord(info);
} break;
case ShaderKind::Geometry: {
RDAT::GSInfo info = {};
info.SigInputElements = AddSigElements(sig.InputSignature, shaderFlags);
shaderFlags = 0;
info.SigOutputElements = AddSigElements(sig.OutputSignature, shaderFlags,
&info.OutputStreamMask);
funcInfo.ShaderFlags |=
(uint16_t)(shaderFlags &
(uint16_t)DxilShaderFlags::OutputPositionPresent);
// TODO: Fill in ViewID related masks
info.InputPrimitive = (uint8_t)props.ShaderProps.GS.inputPrimitive;
info.OutputTopology =
(uint8_t)props.ShaderProps.GS.streamPrimitiveTopologies[0];
info.MaxVertexCount = (uint8_t)props.ShaderProps.GS.maxVertexCount;
return Builder.InsertRecord(info);
} break;
case ShaderKind::Hull: {
RDAT::HSInfo info = {};
info.SigInputElements = AddSigElements(sig.InputSignature, shaderFlags);
info.SigOutputElements = AddSigElements(sig.OutputSignature, shaderFlags);
info.SigPatchConstOutputElements =
AddSigElements(sig.PatchConstOrPrimSignature, shaderFlags);
// TODO: Fill in ViewID related masks
info.InputControlPointCount =
(uint8_t)props.ShaderProps.HS.inputControlPoints;
info.OutputControlPointCount =
(uint8_t)props.ShaderProps.HS.outputControlPoints;
info.TessellatorDomain = (uint8_t)props.ShaderProps.HS.domain;
info.TessellatorOutputPrimitive =
(uint8_t)props.ShaderProps.HS.outputPrimitive;
return Builder.InsertRecord(info);
} break;
case ShaderKind::Domain: {
RDAT::DSInfo info = {};
info.SigInputElements = AddSigElements(sig.InputSignature, shaderFlags);
info.SigOutputElements = AddSigElements(sig.OutputSignature, shaderFlags);
funcInfo.ShaderFlags |=
(uint16_t)(shaderFlags &
(uint16_t)DxilShaderFlags::OutputPositionPresent);
info.SigPatchConstInputElements =
AddSigElements(sig.PatchConstOrPrimSignature, shaderFlags);
// TODO: Fill in ViewID related masks
info.InputControlPointCount =
(uint8_t)props.ShaderProps.DS.inputControlPoints;
info.TessellatorDomain = (uint8_t)props.ShaderProps.DS.domain;
return Builder.InsertRecord(info);
} break;
case ShaderKind::Compute: {
RDAT::CSInfo info = {};
info.NumThreads =
Builder.InsertArray(&props.numThreads[0], &props.numThreads[0] + 3);
info.GroupSharedBytesUsed = tgsmSizeInBytes;
return Builder.InsertRecord(info);
} break;
case ShaderKind::Mesh: {
RDAT::MSInfo info = {};
info.SigOutputElements = AddSigElements(sig.OutputSignature, shaderFlags);
funcInfo.ShaderFlags |=
(uint16_t)(shaderFlags &
(uint16_t)DxilShaderFlags::OutputPositionPresent);
info.SigPrimOutputElements =
AddSigElements(sig.PatchConstOrPrimSignature, shaderFlags);
// TODO: Fill in ViewID related masks
info.NumThreads =
Builder.InsertArray(&props.numThreads[0], &props.numThreads[0] + 3);
info.GroupSharedBytesUsed = tgsmSizeInBytes;
info.GroupSharedBytesDependentOnViewID =
(uint32_t)0; // TODO: same thing (note: this isn't filled in for PSV!)
info.PayloadSizeInBytes =
(uint32_t)props.ShaderProps.MS.payloadSizeInBytes;
info.MaxOutputVertices = (uint16_t)props.ShaderProps.MS.maxVertexCount;
info.MaxOutputPrimitives =
(uint16_t)props.ShaderProps.MS.maxPrimitiveCount;
info.MeshOutputTopology = (uint8_t)props.ShaderProps.MS.outputTopology;
return Builder.InsertRecord(info);
} break;
case ShaderKind::Amplification: {
RDAT::ASInfo info = {};
info.NumThreads =
Builder.InsertArray(&props.numThreads[0], &props.numThreads[0] + 3);
info.GroupSharedBytesUsed = tgsmSizeInBytes;
info.PayloadSizeInBytes =
(uint32_t)props.ShaderProps.AS.payloadSizeInBytes;
return Builder.InsertRecord(info);
} break;
}
return RDAT_NULL_REF;
}
uint32_t AddShaderNodeInfo(const DxilModule &DM, llvm::Function &function,
const DxilEntryProps &entryProps,
RuntimeDataFunctionInfo2 &funcInfo,
uint32_t tgsmSizeInBytes) {
const DxilFunctionProps &props = entryProps.props;
// Add node info
RDAT::NodeShaderInfo nInfo = {};
RDAT::NodeShaderFuncAttrib nAttrib = {};
SmallVector<uint32_t, 16> funcAttribs;
// LaunchType is technically optional, but less optional
nInfo.LaunchType = (uint32_t)props.Node.LaunchType;
nInfo.GroupSharedBytesUsed = tgsmSizeInBytes;
// Add the function attribute fields
if (!props.NodeShaderID.Name.empty()) {
nAttrib = {};
nAttrib.AttribKind = (uint32_t)RDAT::NodeFuncAttribKind::ID;
RDAT::NodeID ID = {};
ID.Name = Builder.InsertString(props.NodeShaderID.Name);
ID.Index = props.NodeShaderID.Index;
nAttrib.ID = Builder.InsertRecord(ID);
funcAttribs.push_back(Builder.InsertRecord(nAttrib));
}
if (props.Node.IsProgramEntry)
funcInfo.ShaderFlags |= (uint16_t)DxilShaderFlags::NodeProgramEntry;
if (props.numThreads[0] || props.numThreads[1] || props.numThreads[2]) {
nAttrib = {};
nAttrib.AttribKind = (uint32_t)RDAT::NodeFuncAttribKind::NumThreads;
nAttrib.NumThreads =
Builder.InsertArray(&props.numThreads[0], &props.numThreads[0] + 3);
funcAttribs.push_back(Builder.InsertRecord(nAttrib));
}
if (props.Node.LocalRootArgumentsTableIndex >= 0) {
nAttrib = {};
nAttrib.AttribKind =
(uint32_t)RDAT::NodeFuncAttribKind::LocalRootArgumentsTableIndex;
nAttrib.LocalRootArgumentsTableIndex =
props.Node.LocalRootArgumentsTableIndex;
funcAttribs.push_back(Builder.InsertRecord(nAttrib));
}
if (!props.NodeShaderSharedInput.Name.empty()) {
nAttrib = {};
nAttrib.AttribKind = (uint32_t)RDAT::NodeFuncAttribKind::ShareInputOf;
RDAT::NodeID ID = {};
ID.Name = Builder.InsertString(props.NodeShaderSharedInput.Name);
ID.Index = props.NodeShaderSharedInput.Index;
nAttrib.ShareInputOf = Builder.InsertRecord(ID);
funcAttribs.push_back(Builder.InsertRecord(nAttrib));
}
if (props.Node.DispatchGrid[0] || props.Node.DispatchGrid[1] ||
props.Node.DispatchGrid[2]) {
nAttrib = {};
nAttrib.AttribKind = (uint32_t)RDAT::NodeFuncAttribKind::DispatchGrid;
nAttrib.DispatchGrid = Builder.InsertArray(
&props.Node.DispatchGrid[0], &props.Node.DispatchGrid[0] + 3);
funcAttribs.push_back(Builder.InsertRecord(nAttrib));
}
if (props.Node.MaxRecursionDepth) {
nAttrib = {};
nAttrib.AttribKind =
(uint32_t)RDAT::NodeFuncAttribKind::MaxRecursionDepth;
nAttrib.MaxRecursionDepth = props.Node.MaxRecursionDepth;
funcAttribs.push_back(Builder.InsertRecord(nAttrib));
}
if (props.Node.MaxDispatchGrid[0] || props.Node.MaxDispatchGrid[1] ||
props.Node.MaxDispatchGrid[2]) {
nAttrib = {};
nAttrib.AttribKind = (uint32_t)RDAT::NodeFuncAttribKind::MaxDispatchGrid;
nAttrib.MaxDispatchGrid = Builder.InsertArray(
&props.Node.MaxDispatchGrid[0], &props.Node.MaxDispatchGrid[0] + 3);
funcAttribs.push_back(Builder.InsertRecord(nAttrib));
}
nInfo.Attribs = Builder.InsertArray(funcAttribs.begin(), funcAttribs.end());
// Add the input and output nodes
nInfo.Inputs = AddIONodes(props.InputNodes);
nInfo.Outputs = AddIONodes(props.OutputNodes);
return Builder.InsertRecord(nInfo);
}
void UpdateFunctionInfo(const DxilModule &DM) {
llvm::Module *M = DM.GetModule();
for (auto &function : M->getFunctionList()) {
if (function.isDeclaration() && !function.isIntrinsic() &&
function.getLinkage() ==
llvm::GlobalValue::LinkageTypes::ExternalLinkage &&
!OP::IsDxilOpFunc(&function)) {
// collect unresolved dependencies per function
UpdateFunctionDependency(&function);
}
}
// Collect total groupshared memory potentially used by every function
const DataLayout &DL = M->getDataLayout();
ValueMap<const Function *, uint32_t> TGSMInFunc;
// Initialize all function TGSM usage to zero
for (auto &function : M->getFunctionList()) {
TGSMInFunc[&function] = 0;
}
for (GlobalVariable &GV : M->globals()) {
if (GV.getType()->getAddressSpace() == DXIL::kTGSMAddrSpace) {
SmallPtrSet<llvm::Function *, 8> completeFuncs;
SmallVector<User *, 16> WorkList;
uint32_t gvSize = DL.getTypeAllocSize(GV.getType()->getElementType());
WorkList.append(GV.user_begin(), GV.user_end());
while (!WorkList.empty()) {
User *U = WorkList.pop_back_val();
// If const, keep going until we find something we can use
if (isa<Constant>(U)) {
WorkList.append(U->user_begin(), U->user_end());
continue;
}
if (Instruction *I = dyn_cast<Instruction>(U)) {
llvm::Function *F = I->getParent()->getParent();
if (completeFuncs.insert(F).second) {
// If function is new, process it and its users
// Add users to the worklist
WorkList.append(F->user_begin(), F->user_end());
// Add groupshared size to function's total
TGSMInFunc[F] += gvSize;
}
}
}
}
}
for (auto &function : M->getFunctionList()) {
if (!function.isDeclaration()) {
StringRef mangled = function.getName();
StringRef unmangled =
hlsl::dxilutil::DemangleFunctionName(function.getName());
uint32_t mangledIndex = Builder.InsertString(mangled);
uint32_t unmangledIndex = Builder.InsertString(unmangled);
// Update resource Index
uint32_t resourceIndex = RDAT_NULL_REF;
uint32_t functionDependencies = RDAT_NULL_REF;
uint32_t payloadSizeInBytes = 0;
uint32_t attrSizeInBytes = 0;
DXIL::ShaderKind shaderKind = DXIL::ShaderKind::Library;
uint32_t shaderInfo = RDAT_NULL_REF;
if (m_FuncToResNameOffset.find(&function) !=
m_FuncToResNameOffset.end())
resourceIndex =
Builder.InsertArray(m_FuncToResNameOffset[&function].begin(),
m_FuncToResNameOffset[&function].end());
if (m_FuncToDependencies.find(&function) != m_FuncToDependencies.end())
functionDependencies =
Builder.InsertArray(m_FuncToDependencies[&function].begin(),
m_FuncToDependencies[&function].end());
RuntimeDataFunctionInfo2 info_latest = {};
RuntimeDataFunctionInfo &info = info_latest;
RuntimeDataFunctionInfo2 *pInfo2 = (sizeof(RuntimeDataFunctionInfo2) <=
m_pFunctionTable->GetRecordStride())
? &info_latest
: nullptr;
const DxilModule::ShaderCompatInfo &compatInfo =
*DM.GetCompatInfoForFunction(&function);
if (DM.HasDxilFunctionProps(&function)) {
const DxilFunctionProps &props = DM.GetDxilFunctionProps(&function);
if (props.IsClosestHit() || props.IsAnyHit()) {
payloadSizeInBytes = props.ShaderProps.Ray.payloadSizeInBytes;
attrSizeInBytes = props.ShaderProps.Ray.attributeSizeInBytes;
} else if (props.IsMiss()) {
payloadSizeInBytes = props.ShaderProps.Ray.payloadSizeInBytes;
} else if (props.IsCallable()) {
payloadSizeInBytes = props.ShaderProps.Ray.paramSizeInBytes;
}
shaderKind = props.shaderKind;
DxilWaveSize waveSize = props.WaveSize;
if (pInfo2 && DM.HasDxilEntryProps(&function)) {
const auto &entryProps = DM.GetDxilEntryProps(&function);
if (waveSize.IsDefined()) {
pInfo2->MinimumExpectedWaveLaneCount = (uint8_t)waveSize.Min;
pInfo2->MaximumExpectedWaveLaneCount =
(waveSize.IsRange()) ? (uint8_t)waveSize.Max
: (uint8_t)waveSize.Min;
}
pInfo2->ShaderFlags = 0;
if (entryProps.props.IsNode()) {
shaderInfo = AddShaderNodeInfo(DM, function, entryProps, *pInfo2,
TGSMInFunc[&function]);
} else if (DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 8) >
0) {
shaderInfo =
AddShaderInfo(function, entryProps, *pInfo2,
compatInfo.shaderFlags, TGSMInFunc[&function]);
}
}
}
info.Name = mangledIndex;
info.UnmangledName = unmangledIndex;
info.ShaderKind = static_cast<uint32_t>(shaderKind);
if (pInfo2)
pInfo2->RawShaderRef = shaderInfo;
info.Resources = resourceIndex;
info.FunctionDependencies = functionDependencies;
info.PayloadSizeInBytes = payloadSizeInBytes;
info.AttributeSizeInBytes = attrSizeInBytes;
info.SetFeatureFlags(compatInfo.shaderFlags.GetFeatureInfo());
info.ShaderStageFlag = compatInfo.mask;
info.MinShaderTarget =
EncodeVersion((DXIL::ShaderKind)shaderKind, compatInfo.minMajor,
compatInfo.minMinor);
m_pFunctionTable->Insert(info_latest);
}
}
}
void UpdateSubobjectInfo(const DxilModule &DM) {
if (!DM.GetSubobjects())
return;
for (auto &it : DM.GetSubobjects()->GetSubobjects()) {
auto &obj = *it.second;
RuntimeDataSubobjectInfo info = {};
info.Name = Builder.InsertString(obj.GetName());
info.Kind = (uint32_t)obj.GetKind();
bool bLocalRS = false;
switch (obj.GetKind()) {
case DXIL::SubobjectKind::StateObjectConfig:
obj.GetStateObjectConfig(info.StateObjectConfig.Flags);
break;
case DXIL::SubobjectKind::LocalRootSignature:
bLocalRS = true;
LLVM_FALLTHROUGH;
case DXIL::SubobjectKind::GlobalRootSignature: {
const void *Data;
obj.GetRootSignature(bLocalRS, Data, info.RootSignature.Data.Size);
info.RootSignature.Data.Offset = Builder.GetRawBytesPart().Insert(
Data, info.RootSignature.Data.Size);
break;
}
case DXIL::SubobjectKind::SubobjectToExportsAssociation: {
llvm::StringRef Subobject;
const char *const *Exports;
uint32_t NumExports;
std::vector<uint32_t> ExportIndices;
obj.GetSubobjectToExportsAssociation(Subobject, Exports, NumExports);
info.SubobjectToExportsAssociation.Subobject =
Builder.InsertString(Subobject);
ExportIndices.resize(NumExports);
for (unsigned i = 0; i < NumExports; ++i) {
ExportIndices[i] = Builder.InsertString(Exports[i]);
}
info.SubobjectToExportsAssociation.Exports =
Builder.InsertArray(ExportIndices.begin(), ExportIndices.end());
break;
}
case DXIL::SubobjectKind::RaytracingShaderConfig:
obj.GetRaytracingShaderConfig(
info.RaytracingShaderConfig.MaxPayloadSizeInBytes,
info.RaytracingShaderConfig.MaxAttributeSizeInBytes);
break;
case DXIL::SubobjectKind::RaytracingPipelineConfig:
obj.GetRaytracingPipelineConfig(
info.RaytracingPipelineConfig.MaxTraceRecursionDepth);
break;
case DXIL::SubobjectKind::HitGroup: {
HitGroupType hgType;
StringRef AnyHit;
StringRef ClosestHit;
StringRef Intersection;
obj.GetHitGroup(hgType, AnyHit, ClosestHit, Intersection);
info.HitGroup.Type = (uint32_t)hgType;
info.HitGroup.AnyHit = Builder.InsertString(AnyHit);
info.HitGroup.ClosestHit = Builder.InsertString(ClosestHit);
info.HitGroup.Intersection = Builder.InsertString(Intersection);
break;
}
case DXIL::SubobjectKind::RaytracingPipelineConfig1:
obj.GetRaytracingPipelineConfig1(
info.RaytracingPipelineConfig1.MaxTraceRecursionDepth,
info.RaytracingPipelineConfig1.Flags);
break;
}
m_pSubobjectTable->Insert(info);
}
}
static bool GetRecordDuplicationAllowed(const DxilModule &mod) {
unsigned valMajor, valMinor;
mod.GetValidatorVersion(valMajor, valMinor);
const bool bRecordDeduplicationEnabled =
DXIL::CompareVersions(valMajor, valMinor, 1, 7) >= 0;
return bRecordDeduplicationEnabled;
}
public:
DxilRDATWriter(DxilModule &mod) : Builder(GetRecordDuplicationAllowed(mod)) {
// Keep track of validator version so we can make a compatible RDAT
mod.GetValidatorVersion(m_ValMajor, m_ValMinor);
RDAT::RuntimeDataPartType maxAllowedType =
RDAT::MaxPartTypeForValVer(m_ValMajor, m_ValMinor);
mod.ComputeShaderCompatInfo();
// Instantiate the parts in the order that validator expects.
Builder.GetStringBufferPart();
m_pResourceTable = Builder.GetOrAddTable<RDAT::RuntimeDataResourceInfo>();
m_pFunctionTable = Builder.GetOrAddTable<RuntimeDataFunctionInfo>();
if (DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 8) >= 0) {
m_pFunctionTable->SetRecordStride(sizeof(RuntimeDataFunctionInfo2));
} else {
m_pFunctionTable->SetRecordStride(sizeof(RuntimeDataFunctionInfo));
}
Builder.GetIndexArraysPart();
Builder.GetRawBytesPart();
if (RDAT::RecordTraits<RuntimeDataSubobjectInfo>::PartType() <=
maxAllowedType)
m_pSubobjectTable = Builder.GetOrAddTable<RuntimeDataSubobjectInfo>();
// Once per table.
#define RDAT_STRUCT_TABLE(type, table) \
if (RDAT::RecordTraits<RDAT::type>::PartType() <= maxAllowedType) \
(void)Builder.GetOrAddTable<RDAT::type>();
#define DEF_RDAT_TYPES DEF_RDAT_DEFAULTS
#include "dxc/DxilContainer/RDAT_Macros.inl"
UpdateResourceInfo(mod);
UpdateFunctionInfo(mod);
if (m_pSubobjectTable)
UpdateSubobjectInfo(mod);
}
uint32_t size() const override { return Builder.size(); }
void write(AbstractMemoryStream *pStream) override {
StringRef data = Builder.FinalizeAndGetData();
ULONG uWritten = 0;
IFT(pStream->Write(data.data(), data.size(), &uWritten));
}
};
DxilPartWriter *hlsl::NewPSVWriter(const DxilModule &M, uint32_t PSVVersion) {
return new DxilPSVWriter(M, PSVVersion);
}
DxilPartWriter *hlsl::NewRDATWriter(DxilModule &M) {
return new DxilRDATWriter(M);
}
DxilPartWriter *hlsl::NewVersionWriter(IDxcVersionInfo *DXCVersionInfo) {
return new DxilVersionWriter(DXCVersionInfo);
}
class DxilContainerWriter_impl : public DxilContainerWriter {
private:
class DxilPart {
public:
DxilPartHeader Header;
WriteFn Write;
DxilPart(uint32_t fourCC, uint32_t size, WriteFn write) : Write(write) {
Header.PartFourCC = fourCC;
Header.PartSize = size;
}
};
llvm::SmallVector<DxilPart, 8> m_Parts;
bool m_bUnaligned;
bool m_bHasPrivateData;
public:
DxilContainerWriter_impl(bool bUnaligned)
: m_bUnaligned(bUnaligned), m_bHasPrivateData(false) {}
void AddPart(uint32_t FourCC, uint32_t Size, WriteFn Write) override {
// Alignment required for all parts except private data, which must be last.
IFTBOOL(!m_bHasPrivateData &&
"private data must be last, and cannot be added twice.",
DXC_E_CONTAINER_INVALID);
if (FourCC == DFCC_PrivateData) {
m_bHasPrivateData = true;
} else if (!m_bUnaligned) {
IFTBOOL((Size % sizeof(uint32_t)) == 0, DXC_E_CONTAINER_INVALID);
}
m_Parts.emplace_back(FourCC, Size, Write);
}
uint32_t size() const override {
uint32_t partSize = 0;
for (auto &part : m_Parts) {
partSize += part.Header.PartSize;
}
return (uint32_t)GetDxilContainerSizeFromParts((uint32_t)m_Parts.size(),
partSize);
}
void write(AbstractMemoryStream *pStream) override {
DxilContainerHeader header;
const uint32_t PartCount = (uint32_t)m_Parts.size();
uint32_t containerSizeInBytes = size();
InitDxilContainer(&header, PartCount, containerSizeInBytes);
IFT(pStream->Reserve(header.ContainerSizeInBytes));
IFT(WriteStreamValue(pStream, header));
uint32_t offset = sizeof(header) + (uint32_t)GetOffsetTableSize(PartCount);
for (auto &&part : m_Parts) {
IFT(WriteStreamValue(pStream, offset));
offset += sizeof(DxilPartHeader) + part.Header.PartSize;
}
for (auto &&part : m_Parts) {
IFT(WriteStreamValue(pStream, part.Header));
size_t start = pStream->GetPosition();
part.Write(pStream);
DXASSERT_LOCALVAR(
start, pStream->GetPosition() - start == (size_t)part.Header.PartSize,
"out of bound");
}
DXASSERT(containerSizeInBytes == (uint32_t)pStream->GetPosition(),
"else stream size is incorrect");
}
};
DxilContainerWriter *hlsl::NewDxilContainerWriter(bool bUnaligned) {
return new DxilContainerWriter_impl(bUnaligned);
}
static bool HasDebugInfoOrLineNumbers(const Module &M) {
return llvm::getDebugMetadataVersionFromModule(M) != 0 ||
llvm::hasDebugInfo(M);
}
static void GetPaddedProgramPartSize(AbstractMemoryStream *pStream,
uint32_t &bitcodeInUInt32,
uint32_t &bitcodePaddingBytes) {
bitcodeInUInt32 = pStream->GetPtrSize();
bitcodePaddingBytes = (bitcodeInUInt32 % 4);
bitcodeInUInt32 = (bitcodeInUInt32 / 4) + (bitcodePaddingBytes ? 1 : 0);
}
void hlsl::WriteProgramPart(const ShaderModel *pModel,
AbstractMemoryStream *pModuleBitcode,
IStream *pStream) {
DXASSERT(pModel != nullptr, "else generation should have failed");
DxilProgramHeader programHeader;
uint32_t shaderVersion =
EncodeVersion(pModel->GetKind(), pModel->GetMajor(), pModel->GetMinor());
unsigned dxilMajor, dxilMinor;
pModel->GetDxilVersion(dxilMajor, dxilMinor);
uint32_t dxilVersion = DXIL::MakeDxilVersion(dxilMajor, dxilMinor);
InitProgramHeader(programHeader, shaderVersion, dxilVersion,
pModuleBitcode->GetPtrSize());
uint32_t programInUInt32, programPaddingBytes;
GetPaddedProgramPartSize(pModuleBitcode, programInUInt32,
programPaddingBytes);
ULONG cbWritten;
IFT(WriteStreamValue(pStream, programHeader));
IFT(pStream->Write(pModuleBitcode->GetPtr(), pModuleBitcode->GetPtrSize(),
&cbWritten));
if (programPaddingBytes) {
uint32_t paddingValue = 0;
IFT(pStream->Write(&paddingValue, programPaddingBytes, &cbWritten));
}
}
namespace {
class RootSignatureWriter : public DxilPartWriter {
private:
std::vector<uint8_t> m_Sig;
public:
RootSignatureWriter(std::vector<uint8_t> &&S) : m_Sig(std::move(S)) {}
uint32_t size() const { return m_Sig.size(); }
void write(AbstractMemoryStream *pStream) {
ULONG cbWritten;
IFT(pStream->Write(m_Sig.data(), size(), &cbWritten));
}
};
} // namespace
void hlsl::ReEmitLatestReflectionData(llvm::Module *pM) {
// Retain usage information in metadata for reflection by:
// Upgrade validator version, re-emit metadata
// 0,0 = Not meant to be validated, support latest
DxilModule &DM = pM->GetOrCreateDxilModule();
DM.SetValidatorVersion(0, 0);
DM.ReEmitDxilResources();
DM.EmitDxilCounters();
}
static std::unique_ptr<Module> CloneModuleForReflection(Module *pM) {
DxilModule &DM = pM->GetOrCreateDxilModule();
unsigned ValMajor = 0, ValMinor = 0;
DM.GetValidatorVersion(ValMajor, ValMinor);
// Emit the latest reflection metadata
hlsl::ReEmitLatestReflectionData(pM);
// Clone module
std::unique_ptr<Module> reflectionModule(llvm::CloneModule(pM));
// Now restore validator version on main module and re-emit metadata.
DM.SetValidatorVersion(ValMajor, ValMinor);
DM.ReEmitDxilResources();
return reflectionModule;
}
void hlsl::StripAndCreateReflectionStream(
Module *pReflectionM, uint32_t *pReflectionPartSizeInBytes,
AbstractMemoryStream **ppReflectionStreamOut) {
for (Function &F : pReflectionM->functions()) {
if (!F.isDeclaration()) {
F.deleteBody();
}
}
uint32_t reflectPartSizeInBytes = 0;
CComPtr<AbstractMemoryStream> pReflectionBitcodeStream;
IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pReflectionBitcodeStream));
raw_stream_ostream outStream(pReflectionBitcodeStream.p);
WriteBitcodeToFile(pReflectionM, outStream, false);
outStream.flush();
uint32_t reflectInUInt32 = 0, reflectPaddingBytes = 0;
GetPaddedProgramPartSize(pReflectionBitcodeStream, reflectInUInt32,
reflectPaddingBytes);
reflectPartSizeInBytes =
reflectInUInt32 * sizeof(uint32_t) + sizeof(DxilProgramHeader);
*pReflectionPartSizeInBytes = reflectPartSizeInBytes;
*ppReflectionStreamOut = pReflectionBitcodeStream.Detach();
}
void hlsl::SerializeDxilContainerForModule(
DxilModule *pModule, AbstractMemoryStream *pModuleBitcode,
IDxcVersionInfo *DXCVersionInfo, AbstractMemoryStream *pFinalStream,
llvm::StringRef DebugName, SerializeDxilFlags Flags,
DxilShaderHash *pShaderHashOut, AbstractMemoryStream *pReflectionStreamOut,
AbstractMemoryStream *pRootSigStreamOut, void *pPrivateData,
size_t PrivateDataSize) {
// TODO: add a flag to update the module and remove information that is not
// part of DXIL proper and is used only to assemble the container.
DXASSERT_NOMSG(pModule != nullptr);
DXASSERT_NOMSG(pModuleBitcode != nullptr);
DXASSERT_NOMSG(pFinalStream != nullptr);
unsigned ValMajor, ValMinor;
pModule->GetValidatorVersion(ValMajor, ValMinor);
bool bValidatorAtLeast_1_8 =
DXIL::CompareVersions(ValMajor, ValMinor, 1, 8) >= 0;
if (DXIL::CompareVersions(ValMajor, ValMinor, 1, 1) < 0)
Flags &= ~SerializeDxilFlags::IncludeDebugNamePart;
bool bSupportsShaderHash =
DXIL::CompareVersions(ValMajor, ValMinor, 1, 5) >= 0;
bool bCompat_1_4 = DXIL::CompareVersions(ValMajor, ValMinor, 1, 5) < 0;
bool bUnaligned = DXIL::CompareVersions(ValMajor, ValMinor, 1, 7) < 0;
bool bEmitReflection =
Flags & SerializeDxilFlags::IncludeReflectionPart || pReflectionStreamOut;
DxilContainerWriter_impl writer(bUnaligned);
// Write the feature part.
DxilFeatureInfoWriter featureInfoWriter(*pModule);
writer.AddPart(
DFCC_FeatureInfo, featureInfoWriter.size(),
[&](AbstractMemoryStream *pStream) { featureInfoWriter.write(pStream); });
std::unique_ptr<DxilProgramSignatureWriter> pInputSigWriter = nullptr;
std::unique_ptr<DxilProgramSignatureWriter> pOutputSigWriter = nullptr;
std::unique_ptr<DxilProgramSignatureWriter> pPatchConstOrPrimSigWriter =
nullptr;
if (!pModule->GetShaderModel()->IsLib()) {
DXIL::TessellatorDomain domain = DXIL::TessellatorDomain::Undefined;
if (pModule->GetShaderModel()->IsHS() || pModule->GetShaderModel()->IsDS())
domain = pModule->GetTessellatorDomain();
pInputSigWriter = llvm::make_unique<DxilProgramSignatureWriter>(
pModule->GetInputSignature(), domain,
/*IsInput*/ true,
/*UseMinPrecision*/ pModule->GetUseMinPrecision(), bCompat_1_4,
bUnaligned);
pOutputSigWriter = llvm::make_unique<DxilProgramSignatureWriter>(
pModule->GetOutputSignature(), domain,
/*IsInput*/ false,
/*UseMinPrecision*/ pModule->GetUseMinPrecision(), bCompat_1_4,
bUnaligned);
// Write the input and output signature parts.
writer.AddPart(DFCC_InputSignature, pInputSigWriter->size(),
[&](AbstractMemoryStream *pStream) {
pInputSigWriter->write(pStream);
});
writer.AddPart(DFCC_OutputSignature, pOutputSigWriter->size(),
[&](AbstractMemoryStream *pStream) {
pOutputSigWriter->write(pStream);
});
pPatchConstOrPrimSigWriter = llvm::make_unique<DxilProgramSignatureWriter>(
pModule->GetPatchConstOrPrimSignature(), domain,
/*IsInput*/ pModule->GetShaderModel()->IsDS(),
/*UseMinPrecision*/ pModule->GetUseMinPrecision(), bCompat_1_4,
bUnaligned);
if (pModule->GetPatchConstOrPrimSignature().GetElements().size()) {
writer.AddPart(DFCC_PatchConstantSignature,
pPatchConstOrPrimSigWriter->size(),
[&](AbstractMemoryStream *pStream) {
pPatchConstOrPrimSigWriter->write(pStream);
});
}
}
std::unique_ptr<DxilVersionWriter> pVERSWriter = nullptr;
std::unique_ptr<DxilRDATWriter> pRDATWriter = nullptr;
std::unique_ptr<DxilPSVWriter> pPSVWriter = nullptr;
unsigned int major, minor;
pModule->GetDxilVersion(major, minor);
RootSignatureWriter rootSigWriter(
std::move(pModule->GetSerializedRootSignature())); // Grab RS here
DXASSERT_NOMSG(pModule->GetSerializedRootSignature().empty());
bool bMetadataStripped = false;
const hlsl::ShaderModel *pSM = pModule->GetShaderModel();
if (pSM->IsLib()) {
DXASSERT(
pModule->GetSerializedRootSignature().empty(),
"otherwise, library has root signature outside subobject definitions");
// Write the DxilCompilerVersion (VERS) part.
if (DXCVersionInfo && bValidatorAtLeast_1_8) {
pVERSWriter = llvm::make_unique<DxilVersionWriter>(DXCVersionInfo);
writer.AddPart(hlsl::DFCC_CompilerVersion, pVERSWriter->size(),
[&pVERSWriter](AbstractMemoryStream *pStream) {
pVERSWriter->write(pStream);
return S_OK;
});
}
// Write the DxilRuntimeData (RDAT) part.
pRDATWriter = llvm::make_unique<DxilRDATWriter>(*pModule);
writer.AddPart(
DFCC_RuntimeData, pRDATWriter->size(),
[&](AbstractMemoryStream *pStream) { pRDATWriter->write(pStream); });
bMetadataStripped |= pModule->StripSubobjectsFromMetadata();
pModule->ResetSubobjects(nullptr);
} else {
// Write the DxilPipelineStateValidation (PSV0) part.
pPSVWriter = llvm::make_unique<DxilPSVWriter>(*pModule);
writer.AddPart(
DFCC_PipelineStateValidation, pPSVWriter->size(),
[&](AbstractMemoryStream *pStream) { pPSVWriter->write(pStream); });
// Write the root signature (RTS0) part.
if (rootSigWriter.size()) {
if (pRootSigStreamOut) {
// Write root signature wrapped in container for separate output
// Root signature container should never be unaligned.
DxilContainerWriter_impl rootSigContainerWriter(false);
rootSigContainerWriter.AddPart(DFCC_RootSignature, rootSigWriter.size(),
[&](AbstractMemoryStream *pStream) {
rootSigWriter.write(pStream);
});
rootSigContainerWriter.write(pRootSigStreamOut);
}
if ((Flags & SerializeDxilFlags::StripRootSignature) == 0) {
// Write embedded root signature
writer.AddPart(DFCC_RootSignature, rootSigWriter.size(),
[&](AbstractMemoryStream *pStream) {
rootSigWriter.write(pStream);
});
}
bMetadataStripped |= pModule->StripRootSignatureFromMetadata();
}
}
// If metadata was stripped, re-serialize the input module.
CComPtr<AbstractMemoryStream> pInputProgramStream = pModuleBitcode;
if (bMetadataStripped) {
pInputProgramStream.Release();
IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pInputProgramStream));
raw_stream_ostream outStream(pInputProgramStream.p);
WriteBitcodeToFile(pModule->GetModule(), outStream, true);
}
// If we have debug information present, serialize it to a debug part, then
// use the stripped version as the canonical program version.
CComPtr<AbstractMemoryStream> pProgramStream = pInputProgramStream;
bool bModuleStripped = false;
if (HasDebugInfoOrLineNumbers(*pModule->GetModule())) {
uint32_t debugInUInt32, debugPaddingBytes;
GetPaddedProgramPartSize(pInputProgramStream, debugInUInt32,
debugPaddingBytes);
if (Flags & SerializeDxilFlags::IncludeDebugInfoPart) {
writer.AddPart(DFCC_ShaderDebugInfoDXIL,
debugInUInt32 * sizeof(uint32_t) +
sizeof(DxilProgramHeader),
[&](AbstractMemoryStream *pStream) {
hlsl::WriteProgramPart(pModule->GetShaderModel(),
pInputProgramStream, pStream);
});
}
llvm::StripDebugInfo(*pModule->GetModule());
pModule->StripDebugRelatedCode();
bModuleStripped = true;
} else {
// If no debug info, clear DebugNameDependOnSource
// (it's default, and this scenario can happen)
Flags &= ~SerializeDxilFlags::DebugNameDependOnSource;
}
uint32_t reflectPartSizeInBytes = 0;
CComPtr<AbstractMemoryStream> pReflectionBitcodeStream;
if (bEmitReflection) {
// Clone module for reflection
std::unique_ptr<Module> reflectionModule =
CloneModuleForReflection(pModule->GetModule());
hlsl::StripAndCreateReflectionStream(reflectionModule.get(),
&reflectPartSizeInBytes,
&pReflectionBitcodeStream);
}
if (pReflectionStreamOut) {
DxilPartHeader partSTAT;
partSTAT.PartFourCC = DFCC_ShaderStatistics;
partSTAT.PartSize = reflectPartSizeInBytes;
IFT(WriteStreamValue(pReflectionStreamOut, partSTAT));
WriteProgramPart(pModule->GetShaderModel(), pReflectionBitcodeStream,
pReflectionStreamOut);
// If library, we need RDAT part as well. For now, we just append it
if (pModule->GetShaderModel()->IsLib()) {
DxilPartHeader partRDAT;
partRDAT.PartFourCC = DFCC_RuntimeData;
partRDAT.PartSize = pRDATWriter->size();
IFT(WriteStreamValue(pReflectionStreamOut, partRDAT));
pRDATWriter->write(pReflectionStreamOut);
}
}
if (Flags & SerializeDxilFlags::IncludeReflectionPart) {
writer.AddPart(
DFCC_ShaderStatistics, reflectPartSizeInBytes,
[pModule, pReflectionBitcodeStream](AbstractMemoryStream *pStream) {
WriteProgramPart(pModule->GetShaderModel(), pReflectionBitcodeStream,
pStream);
});
}
if (Flags & SerializeDxilFlags::StripReflectionFromDxilPart) {
bModuleStripped |= pModule->StripReflection();
}
// If debug info or reflection was stripped, re-serialize the module.
if (bModuleStripped) {
pProgramStream.Release();
IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pProgramStream));
raw_stream_ostream outStream(pProgramStream.p);
WriteBitcodeToFile(pModule->GetModule(), outStream, false);
}
// Compute hash if needed.
DxilShaderHash HashContent;
SmallString<32> HashStr;
if (bSupportsShaderHash || pShaderHashOut ||
(Flags & SerializeDxilFlags::IncludeDebugNamePart && DebugName.empty())) {
// If the debug name should be specific to the sources, base the name on the
// debug bitcode, which will include the source references, line numbers,
// etc. Otherwise, do it exclusively on the target shader bitcode.
llvm::MD5 md5;
if (Flags & SerializeDxilFlags::DebugNameDependOnSource) {
md5.update(ArrayRef<uint8_t>(pModuleBitcode->GetPtr(),
pModuleBitcode->GetPtrSize()));
HashContent.Flags = (uint32_t)DxilShaderHashFlags::IncludesSource;
} else {
md5.update(ArrayRef<uint8_t>(pProgramStream->GetPtr(),
pProgramStream->GetPtrSize()));
HashContent.Flags = (uint32_t)DxilShaderHashFlags::None;
}
md5.final(HashContent.Digest);
md5.stringifyResult(HashContent.Digest, HashStr);
}
// Serialize debug name if requested.
std::string DebugNameStr; // Used if constructing name based on hash
if (Flags & SerializeDxilFlags::IncludeDebugNamePart) {
if (DebugName.empty()) {
DebugNameStr += HashStr;
DebugNameStr += ".pdb";
DebugName = DebugNameStr;
}
// Calculate the size of the blob part.
const uint32_t DebugInfoContentLen = PSVALIGN4(
sizeof(DxilShaderDebugName) + DebugName.size() + 1); // 1 for null
writer.AddPart(
DFCC_ShaderDebugName, DebugInfoContentLen,
[DebugName](AbstractMemoryStream *pStream) {
DxilShaderDebugName NameContent;
NameContent.Flags = 0;
NameContent.NameLength = DebugName.size();
IFT(WriteStreamValue(pStream, NameContent));
ULONG cbWritten;
IFT(pStream->Write(DebugName.begin(), DebugName.size(), &cbWritten));
const char Pad[] = {'\0', '\0', '\0', '\0'};
// Always writes at least one null to align size
unsigned padLen =
(4 - ((sizeof(DxilShaderDebugName) + cbWritten) & 0x3));
IFT(pStream->Write(Pad, padLen, &cbWritten));
});
}
// Add hash to container if supported by validator version.
if (bSupportsShaderHash) {
writer.AddPart(DFCC_ShaderHash, sizeof(HashContent),
[HashContent](AbstractMemoryStream *pStream) {
IFT(WriteStreamValue(pStream, HashContent));
});
}
// Write hash to separate output if requested.
if (pShaderHashOut) {
memcpy(pShaderHashOut, &HashContent, sizeof(DxilShaderHash));
}
// Compute padded bitcode size.
uint32_t programInUInt32, programPaddingBytes;
GetPaddedProgramPartSize(pProgramStream, programInUInt32,
programPaddingBytes);
// Write the program part.
writer.AddPart(
DFCC_DXIL, programInUInt32 * sizeof(uint32_t) + sizeof(DxilProgramHeader),
[&](AbstractMemoryStream *pStream) {
WriteProgramPart(pModule->GetShaderModel(), pProgramStream, pStream);
});
// Private data part should be added last when assembling the container
// becasue there is no garuntee of aligned size
if (pPrivateData) {
writer.AddPart(
hlsl::DFCC_PrivateData, PrivateDataSize,
[&](AbstractMemoryStream *pStream) {
ULONG cbWritten;
IFT(pStream->Write(pPrivateData, PrivateDataSize, &cbWritten));
});
}
writer.write(pFinalStream);
}
void hlsl::SerializeDxilContainerForRootSignature(
hlsl::RootSignatureHandle *pRootSigHandle,
AbstractMemoryStream *pFinalStream) {
DXASSERT_NOMSG(pRootSigHandle != nullptr);
DXASSERT_NOMSG(pFinalStream != nullptr);
// Root signature container should never be unaligned.
DxilContainerWriter_impl writer(false);
// Write the root signature (RTS0) part.
DxilProgramRootSignatureWriter rootSigWriter(*pRootSigHandle);
if (!pRootSigHandle->IsEmpty()) {
writer.AddPart(
DFCC_RootSignature, rootSigWriter.size(),
[&](AbstractMemoryStream *pStream) { rootSigWriter.write(pStream); });
}
writer.write(pFinalStream);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilContainer/DxcContainerBuilder.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// dxcontainerbuilder.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Implements the Dxil Container Builder //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DxilContainer/DxcContainerBuilder.h"
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/Support/ErrorCodes.h"
#include "dxc/Support/FileIOHelper.h"
#include "dxc/Support/dxcapi.impl.h"
#include "dxc/Support/microcom.h"
#include "dxc/dxcapi.h"
#include "llvm/ADT/SmallVector.h"
#include <algorithm>
// This declaration is used for the locally-linked validator.
HRESULT CreateDxcValidator(REFIID riid, LPVOID *ppv);
template <class TInterface>
HRESULT DxilLibCreateInstance(REFCLSID rclsid, TInterface **ppInterface);
using namespace hlsl;
HRESULT STDMETHODCALLTYPE DxcContainerBuilder::Load(IDxcBlob *pSource) {
DxcThreadMalloc TM(m_pMalloc);
try {
IFTBOOL(m_pContainer == nullptr && pSource != nullptr &&
IsDxilContainerLike(pSource->GetBufferPointer(),
pSource->GetBufferSize()),
E_INVALIDARG);
m_pContainer = pSource;
const DxilContainerHeader *pHeader =
(DxilContainerHeader *)pSource->GetBufferPointer();
for (DxilPartIterator it = begin(pHeader), itEnd = end(pHeader);
it != itEnd; ++it) {
const DxilPartHeader *pPartHeader = *it;
CComPtr<IDxcBlob> pBlob;
IFT(DxcCreateBlobFromPinned((const void *)(pPartHeader + 1),
pPartHeader->PartSize, &pBlob));
AddPart(DxilPart(pPartHeader->PartFourCC, pBlob));
}
// Collect hash function.
const DxilContainerHeader *Header =
(DxilContainerHeader *)pSource->GetBufferPointer();
DetermineHashFunctionFromContainerContents(Header);
return S_OK;
}
CATCH_CPP_RETURN_HRESULT();
}
HRESULT STDMETHODCALLTYPE DxcContainerBuilder::AddPart(UINT32 fourCC,
IDxcBlob *pSource) {
DxcThreadMalloc TM(m_pMalloc);
try {
IFTBOOL(pSource != nullptr &&
!IsDxilContainerLike(pSource->GetBufferPointer(),
pSource->GetBufferSize()),
E_INVALIDARG);
// You can only add debug info, debug info name, rootsignature, or private
// data blob
IFTBOOL(fourCC == DxilFourCC::DFCC_ShaderDebugInfoDXIL ||
fourCC == DxilFourCC::DFCC_ShaderDebugName ||
fourCC == DxilFourCC::DFCC_RootSignature ||
fourCC == DxilFourCC::DFCC_ShaderStatistics ||
fourCC == DxilFourCC::DFCC_PrivateData,
E_INVALIDARG);
AddPart(DxilPart(fourCC, pSource));
if (fourCC == DxilFourCC::DFCC_RootSignature) {
m_RequireValidation = true;
}
return S_OK;
}
CATCH_CPP_RETURN_HRESULT();
}
HRESULT STDMETHODCALLTYPE DxcContainerBuilder::RemovePart(UINT32 fourCC) {
DxcThreadMalloc TM(m_pMalloc);
try {
IFTBOOL(fourCC == DxilFourCC::DFCC_ShaderDebugInfoDXIL ||
fourCC == DxilFourCC::DFCC_ShaderDebugName ||
fourCC == DxilFourCC::DFCC_RootSignature ||
fourCC == DxilFourCC::DFCC_PrivateData ||
fourCC == DxilFourCC::DFCC_ShaderStatistics,
E_INVALIDARG); // You can only remove debug info, debug info name,
// rootsignature, or private data blob
PartList::iterator it =
std::find_if(m_parts.begin(), m_parts.end(),
[&](DxilPart part) { return part.m_fourCC == fourCC; });
IFTBOOL(it != m_parts.end(), DXC_E_MISSING_PART);
m_parts.erase(it);
if (fourCC == DxilFourCC::DFCC_PrivateData) {
m_HasPrivateData = false;
}
return S_OK;
}
CATCH_CPP_RETURN_HRESULT();
}
HRESULT STDMETHODCALLTYPE
DxcContainerBuilder::SerializeContainer(IDxcOperationResult **ppResult) {
DxcThreadMalloc TM(m_pMalloc);
try {
// Allocate memory for new dxil container.
uint32_t ContainerSize = ComputeContainerSize();
CComPtr<AbstractMemoryStream> pMemoryStream;
CComPtr<IDxcBlob> pResult;
IFT(CreateMemoryStream(m_pMalloc, &pMemoryStream));
IFT(pMemoryStream->QueryInterface(&pResult));
IFT(pMemoryStream->Reserve(ContainerSize))
// Update Dxil Container
IFT(UpdateContainerHeader(pMemoryStream, ContainerSize));
// Update offset Table
IFT(UpdateOffsetTable(pMemoryStream));
// Update Parts
IFT(UpdateParts(pMemoryStream));
CComPtr<IDxcBlobUtf8> pValErrorUtf8;
HRESULT valHR = S_OK;
if (m_RequireValidation) {
CComPtr<IDxcValidator> pValidator;
IFT(CreateDxcValidator(IID_PPV_ARGS(&pValidator)));
CComPtr<IDxcOperationResult> pValidationResult;
IFT(pValidator->Validate(pResult, DxcValidatorFlags_RootSignatureOnly,
&pValidationResult));
IFT(pValidationResult->GetStatus(&valHR));
if (FAILED(valHR)) {
CComPtr<IDxcBlobEncoding> pValError;
IFT(pValidationResult->GetErrorBuffer(&pValError));
if (pValError->GetBufferPointer() && pValError->GetBufferSize())
IFT(hlsl::DxcGetBlobAsUtf8(pValError, m_pMalloc, &pValErrorUtf8));
}
}
// Combine existing warnings and errors from validation
CComPtr<IDxcBlobEncoding> pErrorBlob;
CDxcMallocHeapPtr<char> errorHeap(m_pMalloc);
SIZE_T warningLength = m_warning ? strlen(m_warning) : 0;
SIZE_T valErrorLength =
pValErrorUtf8 ? pValErrorUtf8->GetStringLength() : 0;
SIZE_T totalErrorLength = warningLength + valErrorLength;
if (totalErrorLength) {
SIZE_T errorSizeInBytes = totalErrorLength + 1;
errorHeap.AllocateBytes(errorSizeInBytes);
if (warningLength)
memcpy(errorHeap.m_pData, m_warning, warningLength);
if (valErrorLength)
memcpy(errorHeap.m_pData + warningLength,
pValErrorUtf8->GetStringPointer(), valErrorLength);
errorHeap.m_pData[totalErrorLength] = L'\0';
IFT(hlsl::DxcCreateBlobWithEncodingOnMalloc(errorHeap.m_pData, m_pMalloc,
errorSizeInBytes, DXC_CP_UTF8,
&pErrorBlob));
errorHeap.Detach();
}
IFT(DxcResult::Create(
valHR, DXC_OUT_OBJECT,
{DxcOutputObject::DataOutput(DXC_OUT_OBJECT, pResult, DxcOutNoName),
DxcOutputObject::DataOutput(DXC_OUT_ERRORS, pErrorBlob, DxcOutNoName)},
ppResult));
}
CATCH_CPP_RETURN_HRESULT();
if (ppResult == nullptr || *ppResult == nullptr)
return S_OK;
HRESULT HR;
(*ppResult)->GetStatus(&HR);
if (FAILED(HR))
return HR;
CComPtr<IDxcBlob> pObject;
IFR((*ppResult)->GetResult(&pObject));
// Add Hash.
LPVOID PTR = pObject->GetBufferPointer();
if (IsDxilContainerLike(PTR, pObject->GetBufferSize()))
HashAndUpdate((DxilContainerHeader *)PTR);
return S_OK;
}
// Try hashing the source contained in ContainerHeader using retail and debug
// hashing functions. If either of them match the stored result, set the
// HashFunction to the matching variant. If neither match, set it to null.
void DxcContainerBuilder::DetermineHashFunctionFromContainerContents(
const DxilContainerHeader *ContainerHeader) {
DXASSERT(ContainerHeader != nullptr &&
IsDxilContainerLike(ContainerHeader,
ContainerHeader->ContainerSizeInBytes),
"otherwise load function should have returned an error.");
constexpr uint32_t HashStartOffset =
offsetof(struct DxilContainerHeader, Version);
auto *DataToHash = (const BYTE *)ContainerHeader + HashStartOffset;
UINT AmountToHash = ContainerHeader->ContainerSizeInBytes - HashStartOffset;
BYTE Result[DxilContainerHashSize];
ComputeHashRetail(DataToHash, AmountToHash, Result);
if (0 == memcmp(Result, ContainerHeader->Hash.Digest, sizeof(Result))) {
m_HashFunction = ComputeHashRetail;
} else {
ComputeHashDebug(DataToHash, AmountToHash, Result);
if (0 == memcmp(Result, ContainerHeader->Hash.Digest, sizeof(Result)))
m_HashFunction = ComputeHashDebug;
else
m_HashFunction = nullptr;
}
}
// For Internal hash function.
void DxcContainerBuilder::HashAndUpdate(DxilContainerHeader *ContainerHeader) {
if (m_HashFunction != nullptr) {
DXASSERT(ContainerHeader != nullptr,
"Otherwise serialization should have failed.");
static const UINT32 HashStartOffset =
offsetof(struct DxilContainerHeader, Version);
const BYTE *DataToHash = (const BYTE *)ContainerHeader + HashStartOffset;
UINT AmountToHash = ContainerHeader->ContainerSizeInBytes - HashStartOffset;
m_HashFunction(DataToHash, AmountToHash, ContainerHeader->Hash.Digest);
}
}
UINT32 DxcContainerBuilder::ComputeContainerSize() {
UINT32 partsSize = 0;
for (DxilPart part : m_parts) {
partsSize += part.m_Blob->GetBufferSize();
}
return GetDxilContainerSizeFromParts(m_parts.size(), partsSize);
}
HRESULT
DxcContainerBuilder::UpdateContainerHeader(AbstractMemoryStream *pStream,
uint32_t containerSize) {
DxilContainerHeader header;
InitDxilContainer(&header, m_parts.size(), containerSize);
ULONG cbWritten;
IFR(pStream->Write(&header, sizeof(DxilContainerHeader), &cbWritten));
if (cbWritten != sizeof(DxilContainerHeader)) {
return E_FAIL;
}
return S_OK;
}
HRESULT DxcContainerBuilder::UpdateOffsetTable(AbstractMemoryStream *pStream) {
UINT32 offset =
sizeof(DxilContainerHeader) + GetOffsetTableSize(m_parts.size());
for (size_t i = 0; i < m_parts.size(); ++i) {
ULONG cbWritten;
IFR(pStream->Write(&offset, sizeof(UINT32), &cbWritten));
if (cbWritten != sizeof(UINT32)) {
return E_FAIL;
}
offset += sizeof(DxilPartHeader) + m_parts[i].m_Blob->GetBufferSize();
}
return S_OK;
}
HRESULT DxcContainerBuilder::UpdateParts(AbstractMemoryStream *pStream) {
for (size_t i = 0; i < m_parts.size(); ++i) {
ULONG cbWritten;
CComPtr<IDxcBlob> pBlob = m_parts[i].m_Blob;
// Write part header
DxilPartHeader partHeader = {m_parts[i].m_fourCC,
(uint32_t)pBlob->GetBufferSize()};
IFR(pStream->Write(&partHeader, sizeof(DxilPartHeader), &cbWritten));
if (cbWritten != sizeof(DxilPartHeader)) {
return E_FAIL;
}
// Write part content
IFR(pStream->Write(pBlob->GetBufferPointer(), pBlob->GetBufferSize(),
&cbWritten));
if (cbWritten != pBlob->GetBufferSize()) {
return E_FAIL;
}
}
return S_OK;
}
void DxcContainerBuilder::AddPart(DxilPart &&part) {
PartList::iterator it =
std::find_if(m_parts.begin(), m_parts.end(), [&](DxilPart checkPart) {
return checkPart.m_fourCC == part.m_fourCC;
});
IFTBOOL(it == m_parts.end(), DXC_E_DUPLICATE_PART);
if (m_HasPrivateData) {
// Keep PrivateData at end, since it may have unaligned size.
m_parts.insert(m_parts.end() - 1, std::move(part));
} else {
m_parts.emplace_back(std::move(part));
}
if (part.m_fourCC == DxilFourCC::DFCC_PrivateData) {
m_HasPrivateData = true;
}
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilContainer/DxilContainerReader.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilContainerReader.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Helper class for reading from dxil container. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DxilContainer/DxilContainerReader.h"
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/Support/Global.h"
#include "dxc/WinAdapter.h"
namespace hlsl {
HRESULT DxilContainerReader::Load(const void *pContainer,
uint32_t containerSizeInBytes) {
if (pContainer == nullptr) {
return E_FAIL;
}
const DxilContainerHeader *pHeader =
IsDxilContainerLike(pContainer, containerSizeInBytes);
if (pHeader == nullptr) {
return E_FAIL;
}
if (!IsValidDxilContainer(pHeader, containerSizeInBytes)) {
return E_FAIL;
}
m_pContainer = pContainer;
m_uContainerSize = containerSizeInBytes;
m_pHeader = pHeader;
return S_OK;
}
HRESULT DxilContainerReader::GetVersion(DxilContainerVersion *pResult) {
if (pResult == nullptr)
return E_POINTER;
if (!IsLoaded())
return E_NOT_VALID_STATE;
*pResult = m_pHeader->Version;
return S_OK;
}
HRESULT DxilContainerReader::GetPartCount(uint32_t *pResult) {
if (pResult == nullptr)
return E_POINTER;
if (!IsLoaded())
return E_NOT_VALID_STATE;
*pResult = m_pHeader->PartCount;
return S_OK;
}
HRESULT DxilContainerReader::GetPartContent(uint32_t idx, const void **ppResult,
uint32_t *pResultSize) {
if (ppResult == nullptr)
return E_POINTER;
*ppResult = nullptr;
if (!IsLoaded())
return E_NOT_VALID_STATE;
if (idx >= m_pHeader->PartCount)
return E_BOUNDS;
const DxilPartHeader *pPart = GetDxilContainerPart(m_pHeader, idx);
*ppResult = GetDxilPartData(pPart);
if (pResultSize != nullptr) {
*pResultSize = pPart->PartSize;
}
return S_OK;
}
HRESULT DxilContainerReader::GetPartFourCC(uint32_t idx, uint32_t *pResult) {
if (pResult == nullptr)
return E_POINTER;
if (!IsLoaded())
return E_NOT_VALID_STATE;
if (idx >= m_pHeader->PartCount)
return E_BOUNDS;
const DxilPartHeader *pPart = GetDxilContainerPart(m_pHeader, idx);
*pResult = pPart->PartFourCC;
return S_OK;
}
HRESULT DxilContainerReader::FindFirstPartKind(uint32_t kind,
uint32_t *pResult) {
if (pResult == nullptr)
return E_POINTER;
*pResult = 0;
if (!IsLoaded())
return E_NOT_VALID_STATE;
DxilPartIterator it =
std::find_if(begin(m_pHeader), end(m_pHeader), DxilPartIsType(kind));
*pResult = (it == end(m_pHeader)) ? DXIL_CONTAINER_BLOB_NOT_FOUND : it.index;
return S_OK;
}
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/Option/Option.cpp | //===--- Option.cpp - Abstract Driver Options -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Option/Option.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
using namespace llvm;
using namespace llvm::opt;
Option::Option(const OptTable::Info *info, const OptTable *owner)
: Info(info), Owner(owner) {
// Multi-level aliases are not supported. This just simplifies option
// tracking, it is not an inherent limitation.
assert((!Info || !getAlias().isValid() || !getAlias().getAlias().isValid()) &&
"Multi-level aliases are not supported.");
if (Info && getAliasArgs()) {
assert(getAlias().isValid() && "Only alias options can have alias args.");
assert(getKind() == FlagClass && "Only Flag aliases can have alias args.");
assert(getAlias().getKind() != FlagClass &&
"Cannot provide alias args to a flag option.");
}
}
void Option::dump() const {
llvm::errs() << "<";
switch (getKind()) {
#define P(N) case N: llvm::errs() << #N; break
P(GroupClass);
P(InputClass);
P(UnknownClass);
P(FlagClass);
P(JoinedClass);
P(SeparateClass);
P(CommaJoinedClass);
P(MultiArgClass);
P(JoinedOrSeparateClass);
P(JoinedAndSeparateClass);
P(RemainingArgsClass);
#undef P
}
if (Info->Prefixes) {
llvm::errs() << " Prefixes:[";
for (const char * const *Pre = Info->Prefixes; *Pre != nullptr; ++Pre) {
llvm::errs() << '"' << *Pre << (*(Pre + 1) == nullptr ? "\"" : "\", ");
}
llvm::errs() << ']';
}
llvm::errs() << " Name:\"" << getName() << '"';
const Option Group = getGroup();
if (Group.isValid()) {
llvm::errs() << " Group:";
Group.dump();
}
const Option Alias = getAlias();
if (Alias.isValid()) {
llvm::errs() << " Alias:";
Alias.dump();
}
if (getKind() == MultiArgClass)
llvm::errs() << " NumArgs:" << getNumArgs();
llvm::errs() << ">\n";
}
bool Option::matches(OptSpecifier Opt) const {
// Aliases are never considered in matching, look through them.
const Option Alias = getAlias();
if (Alias.isValid())
return Alias.matches(Opt);
// Check exact match.
if (getID() == Opt.getID())
return true;
const Option Group = getGroup();
if (Group.isValid())
return Group.matches(Opt);
return false;
}
Arg *Option::accept(const ArgList &Args,
unsigned &Index,
unsigned ArgSize) const {
const Option &UnaliasedOption = getUnaliasedOption();
StringRef Spelling;
// If the option was an alias, get the spelling from the unaliased one.
if (getID() == UnaliasedOption.getID()) {
Spelling = StringRef(Args.getArgString(Index), ArgSize);
} else {
Spelling = Args.MakeArgString(Twine(UnaliasedOption.getPrefix()) +
Twine(UnaliasedOption.getName()));
}
// HLSL Change Start: Count spaces immediately after option name.
// This is to handle the case where the argument was provided as
// "-opt value" instead of two arguments: "-opt", "value"
unsigned JoinedSpaces = 0;
{
const char *Val = Args.getArgString(Index) + ArgSize;
while (*Val++ == ' ')
++JoinedSpaces;
}
// HLSL Change End
switch (getKind()) {
case FlagClass: {
if (ArgSize != strlen(Args.getArgString(Index)))
return nullptr;
Arg *A = new Arg(UnaliasedOption, Spelling, Index++);
if (getAliasArgs()) {
const char *Val = getAliasArgs();
while (*Val != '\0') {
A->getValues().push_back(Val);
// Move past the '\0' to the next argument.
Val += strlen(Val) + 1;
}
}
if (UnaliasedOption.getKind() == JoinedClass && !getAliasArgs())
// A Flag alias for a Joined option must provide an argument.
A->getValues().push_back("");
return A;
}
case JoinedClass: {
const char *Value = Args.getArgString(Index) + ArgSize;
return new Arg(UnaliasedOption, Spelling, Index++, Value);
}
case CommaJoinedClass: {
// Always matches.
const char *Str = Args.getArgString(Index) + ArgSize;
Arg *A = new Arg(UnaliasedOption, Spelling, Index++);
// Parse out the comma separated values.
const char *Prev = Str;
for (;; ++Str) {
char c = *Str;
if (!c || c == ',') {
if (Prev != Str) {
char *Value = new char[Str - Prev + 1];
memcpy(Value, Prev, Str - Prev);
Value[Str - Prev] = '\0';
A->getValues().push_back(Value);
}
if (!c)
break;
Prev = Str + 1;
}
}
A->setOwnsValues(true);
return A;
}
case SeparateClass:
// Matches iff this is an exact match.
// FIXME: Avoid strlen.
if (ArgSize != strlen(Args.getArgString(Index)))
{ // HLSL Change Begin: Except if value separated by spaces here
if (JoinedSpaces) {
const char *Value = Args.getArgString(Index) + ArgSize + JoinedSpaces;
if (*Value != '\0')
return new Arg(*this, Spelling, Index++, Value);
} else
// HLSL Change End
return nullptr;
}
Index += 2;
if (Index > Args.getNumInputArgStrings() ||
Args.getArgString(Index - 1) == nullptr)
return nullptr;
return new Arg(UnaliasedOption, Spelling,
Index - 2, Args.getArgString(Index - 1));
case MultiArgClass: {
// Matches iff this is an exact match.
// FIXME: Avoid strlen.
if (ArgSize != strlen(Args.getArgString(Index)))
return nullptr;
Index += 1 + getNumArgs();
if (Index > Args.getNumInputArgStrings())
return nullptr;
Arg *A = new Arg(UnaliasedOption, Spelling, Index - 1 - getNumArgs(),
Args.getArgString(Index - getNumArgs()));
for (unsigned i = 1; i != getNumArgs(); ++i)
A->getValues().push_back(Args.getArgString(Index - getNumArgs() + i));
return A;
}
case JoinedOrSeparateClass: {
// If this is not an exact match, it is a joined arg.
// FIXME: Avoid strlen.
if (ArgSize != strlen(Args.getArgString(Index))) {
const char *Value = Args.getArgString(Index) + ArgSize
+ JoinedSpaces; // HLSL Change: Skip spaces in joined case
// HLSL Change: don't interpret trailing spaces as empty value:
if (*Value != '\0')
return new Arg(*this, Spelling, Index++, Value);
}
// Otherwise it must be separate.
Index += 2;
if (Index > Args.getNumInputArgStrings() ||
Args.getArgString(Index - 1) == nullptr)
return nullptr;
return new Arg(UnaliasedOption, Spelling,
Index - 2, Args.getArgString(Index - 1));
}
case JoinedAndSeparateClass:
// Always matches.
Index += 2;
if (Index > Args.getNumInputArgStrings() ||
Args.getArgString(Index - 1) == nullptr)
return nullptr;
return new Arg(UnaliasedOption, Spelling, Index - 2,
Args.getArgString(Index - 2) + ArgSize,
Args.getArgString(Index - 1));
case RemainingArgsClass: {
// Matches iff this is an exact match.
// FIXME: Avoid strlen.
if (ArgSize != strlen(Args.getArgString(Index)))
return nullptr;
Arg *A = new Arg(UnaliasedOption, Spelling, Index++);
while (Index < Args.getNumInputArgStrings() &&
Args.getArgString(Index) != nullptr)
A->getValues().push_back(Args.getArgString(Index++));
return A;
}
default:
llvm_unreachable("Invalid option kind!");
}
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/Option/ArgList.cpp | //===--- ArgList.cpp - Argument List Management ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Option/ArgList.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::opt;
void arg_iterator::SkipToNextArg() {
for (; Current != Args.end(); ++Current) {
// Done if there are no filters.
if (!Id0.isValid())
break;
// Otherwise require a match.
const Option &O = (*Current)->getOption();
if (O.matches(Id0) ||
(Id1.isValid() && O.matches(Id1)) ||
(Id2.isValid() && O.matches(Id2)))
break;
}
}
void ArgList::append(Arg *A) {
Args.push_back(A);
}
void ArgList::eraseArg(OptSpecifier Id) {
Args.erase(std::remove_if(begin(), end(),
[=](Arg *A) { return A->getOption().matches(Id); }),
end());
}
Arg *ArgList::getLastArgNoClaim(OptSpecifier Id) const {
// FIXME: Make search efficient?
for (const_reverse_iterator it = rbegin(), ie = rend(); it != ie; ++it)
if ((*it)->getOption().matches(Id))
return *it;
return nullptr;
}
Arg *ArgList::getLastArgNoClaim(OptSpecifier Id0, OptSpecifier Id1) const {
// FIXME: Make search efficient?
for (const_reverse_iterator it = rbegin(), ie = rend(); it != ie; ++it)
if ((*it)->getOption().matches(Id0) ||
(*it)->getOption().matches(Id1))
return *it;
return nullptr;
}
Arg *ArgList::getLastArgNoClaim(OptSpecifier Id0, OptSpecifier Id1,
OptSpecifier Id2) const {
// FIXME: Make search efficient?
for (const_reverse_iterator it = rbegin(), ie = rend(); it != ie; ++it)
if ((*it)->getOption().matches(Id0) || (*it)->getOption().matches(Id1) ||
(*it)->getOption().matches(Id2))
return *it;
return nullptr;
}
Arg *ArgList::getLastArgNoClaim(OptSpecifier Id0, OptSpecifier Id1,
OptSpecifier Id2, OptSpecifier Id3) const {
// FIXME: Make search efficient?
for (const_reverse_iterator it = rbegin(), ie = rend(); it != ie; ++it)
if ((*it)->getOption().matches(Id0) || (*it)->getOption().matches(Id1) ||
(*it)->getOption().matches(Id2) || (*it)->getOption().matches(Id3))
return *it;
return nullptr;
}
Arg *ArgList::getLastArg(OptSpecifier Id) const {
Arg *Res = nullptr;
for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
if ((*it)->getOption().matches(Id)) {
Res = *it;
Res->claim();
}
}
return Res;
}
Arg *ArgList::getLastArg(OptSpecifier Id0, OptSpecifier Id1) const {
Arg *Res = nullptr;
for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
if ((*it)->getOption().matches(Id0) ||
(*it)->getOption().matches(Id1)) {
Res = *it;
Res->claim();
}
}
return Res;
}
Arg *ArgList::getLastArg(OptSpecifier Id0, OptSpecifier Id1,
OptSpecifier Id2) const {
Arg *Res = nullptr;
for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
if ((*it)->getOption().matches(Id0) ||
(*it)->getOption().matches(Id1) ||
(*it)->getOption().matches(Id2)) {
Res = *it;
Res->claim();
}
}
return Res;
}
Arg *ArgList::getLastArg(OptSpecifier Id0, OptSpecifier Id1,
OptSpecifier Id2, OptSpecifier Id3) const {
Arg *Res = nullptr;
for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
if ((*it)->getOption().matches(Id0) ||
(*it)->getOption().matches(Id1) ||
(*it)->getOption().matches(Id2) ||
(*it)->getOption().matches(Id3)) {
Res = *it;
Res->claim();
}
}
return Res;
}
Arg *ArgList::getLastArg(OptSpecifier Id0, OptSpecifier Id1,
OptSpecifier Id2, OptSpecifier Id3,
OptSpecifier Id4) const {
Arg *Res = nullptr;
for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
if ((*it)->getOption().matches(Id0) ||
(*it)->getOption().matches(Id1) ||
(*it)->getOption().matches(Id2) ||
(*it)->getOption().matches(Id3) ||
(*it)->getOption().matches(Id4)) {
Res = *it;
Res->claim();
}
}
return Res;
}
Arg *ArgList::getLastArg(OptSpecifier Id0, OptSpecifier Id1,
OptSpecifier Id2, OptSpecifier Id3,
OptSpecifier Id4, OptSpecifier Id5) const {
Arg *Res = nullptr;
for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
if ((*it)->getOption().matches(Id0) ||
(*it)->getOption().matches(Id1) ||
(*it)->getOption().matches(Id2) ||
(*it)->getOption().matches(Id3) ||
(*it)->getOption().matches(Id4) ||
(*it)->getOption().matches(Id5)) {
Res = *it;
Res->claim();
}
}
return Res;
}
Arg *ArgList::getLastArg(OptSpecifier Id0, OptSpecifier Id1,
OptSpecifier Id2, OptSpecifier Id3,
OptSpecifier Id4, OptSpecifier Id5,
OptSpecifier Id6) const {
Arg *Res = nullptr;
for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
if ((*it)->getOption().matches(Id0) ||
(*it)->getOption().matches(Id1) ||
(*it)->getOption().matches(Id2) ||
(*it)->getOption().matches(Id3) ||
(*it)->getOption().matches(Id4) ||
(*it)->getOption().matches(Id5) ||
(*it)->getOption().matches(Id6)) {
Res = *it;
Res->claim();
}
}
return Res;
}
Arg *ArgList::getLastArg(OptSpecifier Id0, OptSpecifier Id1,
OptSpecifier Id2, OptSpecifier Id3,
OptSpecifier Id4, OptSpecifier Id5,
OptSpecifier Id6, OptSpecifier Id7) const {
Arg *Res = nullptr;
for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
if ((*it)->getOption().matches(Id0) ||
(*it)->getOption().matches(Id1) ||
(*it)->getOption().matches(Id2) ||
(*it)->getOption().matches(Id3) ||
(*it)->getOption().matches(Id4) ||
(*it)->getOption().matches(Id5) ||
(*it)->getOption().matches(Id6) ||
(*it)->getOption().matches(Id7)) {
Res = *it;
Res->claim();
}
}
return Res;
}
bool ArgList::hasFlag(OptSpecifier Pos, OptSpecifier Neg, bool Default) const {
if (Arg *A = getLastArg(Pos, Neg))
return A->getOption().matches(Pos);
return Default;
}
bool ArgList::hasFlag(OptSpecifier Pos, OptSpecifier PosAlias, OptSpecifier Neg,
bool Default) const {
if (Arg *A = getLastArg(Pos, PosAlias, Neg))
return A->getOption().matches(Pos) || A->getOption().matches(PosAlias);
return Default;
}
StringRef ArgList::getLastArgValue(OptSpecifier Id,
StringRef Default) const {
if (Arg *A = getLastArg(Id))
return A->getValue();
return Default;
}
std::vector<std::string> ArgList::getAllArgValues(OptSpecifier Id) const {
SmallVector<const char *, 16> Values;
AddAllArgValues(Values, Id);
return std::vector<std::string>(Values.begin(), Values.end());
}
void ArgList::AddLastArg(ArgStringList &Output, OptSpecifier Id) const {
if (Arg *A = getLastArg(Id)) {
A->claim();
A->render(*this, Output);
}
}
void ArgList::AddLastArg(ArgStringList &Output, OptSpecifier Id0,
OptSpecifier Id1) const {
if (Arg *A = getLastArg(Id0, Id1)) {
A->claim();
A->render(*this, Output);
}
}
void ArgList::AddAllArgs(ArgStringList &Output, OptSpecifier Id0,
OptSpecifier Id1, OptSpecifier Id2) const {
for (auto Arg: filtered(Id0, Id1, Id2)) {
Arg->claim();
Arg->render(*this, Output);
}
}
void ArgList::AddAllArgValues(ArgStringList &Output, OptSpecifier Id0,
OptSpecifier Id1, OptSpecifier Id2) const {
for (auto Arg : filtered(Id0, Id1, Id2)) {
Arg->claim();
const auto &Values = Arg->getValues();
Output.append(Values.begin(), Values.end());
}
}
void ArgList::AddAllArgsTranslated(ArgStringList &Output, OptSpecifier Id0,
const char *Translation,
bool Joined) const {
for (auto Arg: filtered(Id0)) {
Arg->claim();
if (Joined) {
Output.push_back(MakeArgString(StringRef(Translation) +
Arg->getValue(0)));
} else {
Output.push_back(Translation);
Output.push_back(Arg->getValue(0));
}
}
}
void ArgList::ClaimAllArgs(OptSpecifier Id0) const {
for (auto Arg : filtered(Id0))
Arg->claim();
}
void ArgList::ClaimAllArgs() const {
for (const_iterator it = begin(), ie = end(); it != ie; ++it)
if (!(*it)->isClaimed())
(*it)->claim();
}
const char *ArgList::GetOrMakeJoinedArgString(unsigned Index,
StringRef LHS,
StringRef RHS) const {
StringRef Cur = getArgString(Index);
if (Cur.size() == LHS.size() + RHS.size() &&
Cur.startswith(LHS) && Cur.endswith(RHS))
return Cur.data();
return MakeArgString(LHS + RHS);
}
//
void InputArgList::releaseMemory() {
// An InputArgList always owns its arguments.
for (Arg *A : *this)
delete A;
}
InputArgList::InputArgList(const char* const *ArgBegin,
const char* const *ArgEnd)
: NumInputArgStrings(ArgEnd - ArgBegin) {
ArgStrings.append(ArgBegin, ArgEnd);
}
unsigned InputArgList::MakeIndex(StringRef String0) const {
unsigned Index = ArgStrings.size();
// Tuck away so we have a reliable const char *.
SynthesizedStrings.push_back(String0);
ArgStrings.push_back(SynthesizedStrings.back().c_str());
return Index;
}
unsigned InputArgList::MakeIndex(StringRef String0,
StringRef String1) const {
unsigned Index0 = MakeIndex(String0);
unsigned Index1 = MakeIndex(String1);
assert(Index0 + 1 == Index1 && "Unexpected non-consecutive indices!");
(void) Index1;
return Index0;
}
const char *InputArgList::MakeArgStringRef(StringRef Str) const {
return getArgString(MakeIndex(Str));
}
//
DerivedArgList::DerivedArgList(const InputArgList &BaseArgs)
: BaseArgs(BaseArgs) {}
const char *DerivedArgList::MakeArgStringRef(StringRef Str) const {
return BaseArgs.MakeArgString(Str);
}
void DerivedArgList::AddSynthesizedArg(Arg *A) {
SynthesizedArgs.push_back(std::unique_ptr<Arg>(A));
}
Arg *DerivedArgList::MakeFlagArg(const Arg *BaseArg, const Option Opt) const {
SynthesizedArgs.push_back(
make_unique<Arg>(Opt, MakeArgString(Opt.getPrefix() + Opt.getName()),
BaseArgs.MakeIndex(Opt.getName()), BaseArg));
return SynthesizedArgs.back().get();
}
Arg *DerivedArgList::MakePositionalArg(const Arg *BaseArg, const Option Opt,
StringRef Value) const {
unsigned Index = BaseArgs.MakeIndex(Value);
SynthesizedArgs.push_back(
make_unique<Arg>(Opt, MakeArgString(Opt.getPrefix() + Opt.getName()),
Index, BaseArgs.getArgString(Index), BaseArg));
return SynthesizedArgs.back().get();
}
Arg *DerivedArgList::MakeSeparateArg(const Arg *BaseArg, const Option Opt,
StringRef Value) const {
unsigned Index = BaseArgs.MakeIndex(Opt.getName(), Value);
SynthesizedArgs.push_back(
make_unique<Arg>(Opt, MakeArgString(Opt.getPrefix() + Opt.getName()),
Index, BaseArgs.getArgString(Index + 1), BaseArg));
return SynthesizedArgs.back().get();
}
Arg *DerivedArgList::MakeJoinedArg(const Arg *BaseArg, const Option Opt,
StringRef Value) const {
unsigned Index = BaseArgs.MakeIndex((Opt.getName() + Value).str());
SynthesizedArgs.push_back(make_unique<Arg>(
Opt, MakeArgString(Opt.getPrefix() + Opt.getName()), Index,
BaseArgs.getArgString(Index) + Opt.getName().size(), BaseArg));
return SynthesizedArgs.back().get();
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/Option/CMakeLists.txt | add_llvm_library(LLVMOption
Arg.cpp
ArgList.cpp
Option.cpp
OptTable.cpp
ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/Option
)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/Option/LLVMBuild.txt | ;===- ./lib/Option/LLVMBuild.txt -------------------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Library
name = Option
parent = Libraries
required_libraries = Support
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/Option/Arg.cpp | //===--- Arg.cpp - Argument Implementations -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Option/Arg.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::opt;
Arg::Arg(const Option Opt, StringRef S, unsigned Index, const Arg *BaseArg)
: Opt(Opt), BaseArg(BaseArg), Spelling(S), Index(Index), Claimed(false),
OwnsValues(false) {}
Arg::Arg(const Option Opt, StringRef S, unsigned Index, const char *Value0,
const Arg *BaseArg)
: Opt(Opt), BaseArg(BaseArg), Spelling(S), Index(Index), Claimed(false),
OwnsValues(false) {
Values.push_back(Value0);
}
Arg::Arg(const Option Opt, StringRef S, unsigned Index, const char *Value0,
const char *Value1, const Arg *BaseArg)
: Opt(Opt), BaseArg(BaseArg), Spelling(S), Index(Index), Claimed(false),
OwnsValues(false) {
Values.push_back(Value0);
Values.push_back(Value1);
}
Arg::~Arg() {
if (OwnsValues) {
for (unsigned i = 0, e = Values.size(); i != e; ++i)
delete[] Values[i];
}
}
void Arg::dump() const {
llvm::errs() << "<";
llvm::errs() << " Opt:";
Opt.dump();
llvm::errs() << " Index:" << Index;
llvm::errs() << " Values: [";
for (unsigned i = 0, e = Values.size(); i != e; ++i) {
if (i) llvm::errs() << ", ";
llvm::errs() << "'" << Values[i] << "'";
}
llvm::errs() << "]>\n";
}
std::string Arg::getAsString(const ArgList &Args) const {
SmallString<256> Res;
llvm::raw_svector_ostream OS(Res);
ArgStringList ASL;
render(Args, ASL);
for (ArgStringList::iterator
it = ASL.begin(), ie = ASL.end(); it != ie; ++it) {
if (it != ASL.begin())
OS << ' ';
OS << *it;
}
return OS.str();
}
void Arg::renderAsInput(const ArgList &Args, ArgStringList &Output) const {
if (!getOption().hasNoOptAsInput()) {
render(Args, Output);
return;
}
Output.append(Values.begin(), Values.end());
}
void Arg::render(const ArgList &Args, ArgStringList &Output) const {
switch (getOption().getRenderStyle()) {
case Option::RenderValuesStyle:
Output.append(Values.begin(), Values.end());
break;
case Option::RenderCommaJoinedStyle: {
SmallString<256> Res;
llvm::raw_svector_ostream OS(Res);
OS << getSpelling();
for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
if (i) OS << ',';
OS << getValue(i);
}
Output.push_back(Args.MakeArgString(OS.str()));
break;
}
case Option::RenderJoinedStyle:
Output.push_back(Args.GetOrMakeJoinedArgString(
getIndex(), getSpelling(), getValue(0)));
Output.append(Values.begin() + 1, Values.end());
break;
case Option::RenderSeparateStyle:
Output.push_back(Args.MakeArgString(getSpelling()));
Output.append(Values.begin(), Values.end());
break;
}
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/Option/OptTable.cpp | //===--- OptTable.cpp - Option Table Implementation -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cctype>
#include <map>
using namespace llvm;
using namespace llvm::opt;
namespace llvm {
namespace opt {
// Ordering on Info. The ordering is *almost* case-insensitive lexicographic,
// with an exceptions. '\0' comes at the end of the alphabet instead of the
// beginning (thus options precede any other options which prefix them).
static int StrCmpOptionNameIgnoreCase(const char *A, const char *B) {
const char *X = A, *Y = B;
char a = tolower(*A), b = tolower(*B);
while (a == b) {
if (a == '\0')
return 0;
a = tolower(*++X);
b = tolower(*++Y);
}
if (a == '\0') // A is a prefix of B.
return 1;
if (b == '\0') // B is a prefix of A.
return -1;
// Otherwise lexicographic.
return (a < b) ? -1 : 1;
}
#ifndef NDEBUG
static int StrCmpOptionName(const char *A, const char *B) {
if (int N = StrCmpOptionNameIgnoreCase(A, B))
return N;
return strcmp(A, B);
}
static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
if (&A == &B)
return false;
if (int N = StrCmpOptionName(A.Name, B.Name))
return N < 0;
for (const char * const *APre = A.Prefixes,
* const *BPre = B.Prefixes;
*APre != nullptr && *BPre != nullptr; ++APre, ++BPre){
if (int N = StrCmpOptionName(*APre, *BPre))
return N < 0;
}
// Names are the same, check that classes are in order; exactly one
// should be joined, and it should succeed the other.
assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
"Unexpected classes for options with same name.");
return B.Kind == Option::JoinedClass;
}
#endif
// Support lower_bound between info and an option name.
static inline bool operator<(const OptTable::Info &I, const char *Name) {
return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
}
}
}
OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
OptTable::OptTable(const Info *OptionInfos, unsigned NumOptionInfos,
bool IgnoreCase)
: OptionInfos(OptionInfos), NumOptionInfos(NumOptionInfos),
IgnoreCase(IgnoreCase), TheInputOptionID(0), TheUnknownOptionID(0),
FirstSearchableIndex(0) {
// Explicitly zero initialize the error to work around a bug in array
// value-initialization on MinGW with gcc 4.3.5.
// Find start of normal options.
for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
unsigned Kind = getInfo(i + 1).Kind;
if (Kind == Option::InputClass) {
assert(!TheInputOptionID && "Cannot have multiple input options!");
TheInputOptionID = getInfo(i + 1).ID;
} else if (Kind == Option::UnknownClass) {
assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
TheUnknownOptionID = getInfo(i + 1).ID;
} else if (Kind != Option::GroupClass) {
FirstSearchableIndex = i;
break;
}
}
assert(FirstSearchableIndex != 0 && "No searchable options?");
#ifndef NDEBUG
// Check that everything after the first searchable option is a
// regular option class.
for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
Kind != Option::GroupClass) &&
"Special options should be defined first!");
}
// Check that options are in order.
for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
if (!(getInfo(i) < getInfo(i + 1))) {
getOption(i).dump();
getOption(i + 1).dump();
llvm_unreachable("Options are not in order!");
}
}
#endif
// Build prefixes.
for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
i != e; ++i) {
if (const char *const *P = getInfo(i).Prefixes) {
for (; *P != nullptr; ++P) {
PrefixesUnion.insert(*P);
}
}
}
// Build prefix chars.
for (llvm::StringSet<>::const_iterator I = PrefixesUnion.begin(),
E = PrefixesUnion.end(); I != E; ++I) {
StringRef Prefix = I->getKey();
for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
C != CE; ++C)
if (std::find(PrefixChars.begin(), PrefixChars.end(), *C)
== PrefixChars.end())
PrefixChars.push_back(*C);
}
}
OptTable::~OptTable() {
}
const Option OptTable::getOption(OptSpecifier Opt) const {
unsigned id = Opt.getID();
if (id == 0)
return Option(nullptr, nullptr);
assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
return Option(&getInfo(id), this);
}
static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) {
if (Arg == "-")
return true;
for (llvm::StringSet<>::const_iterator I = Prefixes.begin(),
E = Prefixes.end(); I != E; ++I)
if (Arg.startswith(I->getKey()))
return false;
return true;
}
/// \returns Matched size. 0 means no match.
static unsigned matchOption(const OptTable::Info *I, StringRef Str,
bool IgnoreCase) {
for (const char * const *Pre = I->Prefixes; *Pre != nullptr; ++Pre) {
StringRef Prefix(*Pre);
if (Str.startswith(Prefix)) {
StringRef Rest = Str.substr(Prefix.size());
bool Matched = IgnoreCase
? Rest.startswith_lower(I->Name)
: Rest.startswith(I->Name);
if (Matched)
return Prefix.size() + StringRef(I->Name).size();
}
}
return 0;
}
// HLSL Change - begin
Option OptTable::findOption(const char *normalizedName, unsigned FlagsToInclude, unsigned FlagsToExclude) const {
const Info *Start = OptionInfos + FirstSearchableIndex;
const Info *End = OptionInfos + getNumOptions();
StringRef Str(normalizedName);
for (; Start != End; ++Start) {
// Scan for first option which is a proper prefix.
for (; Start != End; ++Start)
if (Str.startswith(Start->Name))
break;
if (Start == End)
break;
Option Opt(Start, this);
if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
continue;
if (Opt.hasFlag(FlagsToExclude))
continue;
return Opt;
}
return Option(nullptr, this);
}
// HLSL Change - end
Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
unsigned FlagsToInclude,
unsigned FlagsToExclude) const {
unsigned Prev = Index;
const char *Str = Args.getArgString(Index);
// Anything that doesn't start with PrefixesUnion is an input, as is '-'
// itself.
if (isInput(PrefixesUnion, Str))
return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
const Info *Start = OptionInfos + FirstSearchableIndex;
const Info *End = OptionInfos + getNumOptions();
StringRef Name = StringRef(Str).ltrim(PrefixChars);
// Search for the first next option which could be a prefix.
Start = std::lower_bound(Start, End, Name.data());
// Options are stored in sorted order, with '\0' at the end of the
// alphabet. Since the only options which can accept a string must
// prefix it, we iteratively search for the next option which could
// be a prefix.
//
// FIXME: This is searching much more than necessary, but I am
// blanking on the simplest way to make it fast. We can solve this
// problem when we move to TableGen.
for (; Start != End; ++Start) {
unsigned ArgSize = 0;
// Scan for first option which is a proper prefix.
for (; Start != End; ++Start)
if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
break;
if (Start == End)
break;
Option Opt(Start, this);
if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
continue;
if (Opt.hasFlag(FlagsToExclude))
continue;
// See if this option matches.
if (Arg *A = Opt.accept(Args, Index, ArgSize))
return A;
// Otherwise, see if this argument was missing values.
if (Prev != Index)
return nullptr;
}
// If we failed to find an option and this arg started with /, then it's
// probably an input path.
if (Str[0] == '/')
return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
}
InputArgList OptTable::ParseArgs(ArrayRef<const char *> ArgArr,
unsigned &MissingArgIndex,
unsigned &MissingArgCount,
unsigned FlagsToInclude,
unsigned FlagsToExclude) const {
InputArgList Args(ArgArr.begin(), ArgArr.end());
// FIXME: Handle '@' args (or at least error on them).
MissingArgIndex = MissingArgCount = 0;
unsigned Index = 0, End = ArgArr.size();
while (Index < End) {
// Ingore nullptrs, they are response file's EOL markers
if (Args.getArgString(Index) == nullptr) {
++Index;
continue;
}
// Ignore empty arguments (other things may still take them as arguments).
StringRef Str = Args.getArgString(Index);
if (Str == "") {
++Index;
continue;
}
unsigned Prev = Index;
Arg *A = ParseOneArg(Args, Index, FlagsToInclude, FlagsToExclude);
assert(Index > Prev && "Parser failed to consume argument.");
// Check for missing argument error.
if (!A) {
assert(Index >= End && "Unexpected parser error.");
assert(Index - Prev - 1 && "No missing arguments!");
MissingArgIndex = Prev;
MissingArgCount = Index - Prev - 1;
break;
}
Args.append(A);
}
return Args;
}
static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
const Option O = Opts.getOption(Id);
std::string Name = O.getPrefixedName();
// Add metavar, if used.
switch (O.getKind()) {
case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
llvm_unreachable("Invalid option with help text.");
case Option::MultiArgClass:
if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
// For MultiArgs, metavar is full list of all argument names.
Name += ' ';
Name += MetaVarName;
}
else {
// For MultiArgs<N>, if metavar not supplied, print <value> N times.
for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
Name += " <value>";
}
}
break;
case Option::FlagClass:
break;
case Option::SeparateClass: case Option::JoinedOrSeparateClass:
case Option::RemainingArgsClass:
Name += ' ';
LLVM_FALLTHROUGH; // HLSL Change
case Option::JoinedClass: case Option::CommaJoinedClass:
case Option::JoinedAndSeparateClass:
if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
Name += MetaVarName;
else
Name += "<value>";
break;
}
return Name;
}
static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
std::vector<std::pair<std::string,
const char*> > &OptionHelp) {
OS << Title << ":\n";
// Find the maximum option length.
unsigned OptionFieldWidth = 0;
for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
// Skip titles.
if (!OptionHelp[i].second)
continue;
// Limit the amount of padding we are willing to give up for alignment.
unsigned Length = OptionHelp[i].first.size();
if (Length <= 23)
OptionFieldWidth = std::max(OptionFieldWidth, Length);
}
const unsigned InitialPad = 2;
for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
const std::string &Option = OptionHelp[i].first;
int Pad = OptionFieldWidth - int(Option.size());
OS.indent(InitialPad) << Option;
// Break on long option names.
if (Pad < 0) {
OS << "\n";
Pad = OptionFieldWidth + InitialPad;
}
OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
}
}
static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
unsigned GroupID = Opts.getOptionGroupID(Id);
// If not in a group, return the default help group.
if (!GroupID)
return "OPTIONS";
// Abuse the help text of the option groups to store the "help group"
// name.
//
// FIXME: Split out option groups.
if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
return GroupHelp;
// Otherwise keep looking.
return getOptionHelpGroup(Opts, GroupID);
}
void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
const char *VersionInfo, bool ShowHidden) const {
PrintHelp(OS, Name, Title, VersionInfo, /*Include*/ 0, /*Exclude*/
(ShowHidden ? 0 : HelpHidden));
}
void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
const char *VersionInfo, unsigned FlagsToInclude,
unsigned FlagsToExclude) const {
OS << "OVERVIEW: " << Title << "\n";
OS << '\n';
OS << "Version: " << VersionInfo << "\n";
OS << '\n';
OS << "USAGE: " << Name << " [options] <inputs>\n";
OS << '\n';
// Render help text into a map of group-name to a list of (option, help)
// pairs.
typedef std::map<std::string,
std::vector<std::pair<std::string, const char*> > > helpmap_ty;
helpmap_ty GroupedOptionHelp;
for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
unsigned Id = i + 1;
// FIXME: Split out option groups.
if (getOptionKind(Id) == Option::GroupClass)
continue;
unsigned Flags = getInfo(Id).Flags;
if (FlagsToInclude && !(Flags & FlagsToInclude))
continue;
if (Flags & FlagsToExclude)
continue;
if (const char *Text = getOptionHelpText(Id)) {
const char *HelpGroup = getOptionHelpGroup(*this, Id);
const std::string &OptName = getOptionHelpName(*this, Id);
GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
}
}
for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
ie = GroupedOptionHelp.end(); it != ie; ++it) {
if (it != GroupedOptionHelp .begin())
OS << "\n";
PrintHelpOptionList(OS, it->first, it->second);
}
OS.flush();
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxrFallback/Reducibility.cpp | #include "Reducibility.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "LLVMUtils.h"
#include <fstream>
#include <map>
#include <vector>
#define DBGS errs
//#define DBGS dbgs
using namespace llvm;
struct Node {
SetVector<Node *> in;
SetVector<Node *> out;
SetVector<BasicBlock *> blocks; // block 0 dominates all others in this node
size_t numInstructions = 0;
Node() {}
Node(BasicBlock *B) { insert(B); }
void insert(BasicBlock *B) {
numInstructions += B->size();
blocks.insert(B);
}
};
static void printDotGraph(const std::vector<Node *> nodes,
const std::string &filename) {
DBGS() << "Writing " << filename << " ...";
std::ofstream out(filename);
if (!out) {
DBGS() << "FAILED\n";
return;
}
// Give nodes a numerical index to make the output cleaner
std::map<Node *, int> idxMap;
for (size_t i = 0; i < nodes.size(); ++i)
idxMap[nodes[i]] = i;
// Error check - make sure that all the out/in nodes are in the map
for (Node *N : nodes) {
for (Node *P : N->in) {
if (idxMap.find(P) == idxMap.end())
DBGS() << "MISSING INPUT NODE\n";
if (P->out.count(N) == 0)
DBGS() << "MISSING OUTGOING EDGE FROM PREDECESSOR.\n";
}
for (Node *S : N->out) {
if (idxMap.find(S) == idxMap.end())
DBGS() << "MISSING OUTPUT NODE\n";
if (S->in.count(N) == 0)
DBGS() << "MISSING INCOMING EDGE FROM SUCCESSOR.\n";
}
}
// Print header
out << "digraph g {\n";
out << "node [\n";
out << " fontsize = \"12\"\n";
out << " labeljust = \"l\"\n";
out << "]\n";
for (unsigned i = 0; i < nodes.size(); ++i) {
Node *N = nodes[i];
// node
out << " N" << i << " [shape=record,label=\"";
for (BasicBlock *B : N->blocks)
out << B->getName().str() << "\\n";
out << "\"];\n";
// out edges
for (Node *S : N->out)
out << " N" << i << " -> N" << idxMap[S] << ";\n";
// in edges
// for( Node* P : N->in )
// out << " N" << idxMap[P] << " -> N" << i << " [style=dotted];\n";
}
out << "}\n";
DBGS() << "\n";
}
static void printDotGraph(const std::vector<Node *> nodes, Function *F,
int step) {
printDotGraph(
nodes,
("red." + F->getName() + "_" + std::to_string(step) + ".dot").str());
}
static Node *split(Node *N, std::map<BasicBlock *, Node *> &bbToNode,
bool firstSplit) {
// Remove one predecessor P from N
assert(N->in.size() > 1);
Node *P = N->in.pop_back_val();
P->out.remove(N);
// Point P to the clone of N, Np
Node *Np = new Node();
P->out.insert(Np);
Np->in.insert(P);
// Copy successors of N to Np
for (Node *S : N->out) {
Np->out.insert(S);
S->in.insert(Np);
}
#if 1
// Run reg2mem on the whole function so we don't have to deal with phis
if (firstSplit) {
runPasses(N->blocks[0]->getParent(), {createDemoteRegisterToMemoryPass()});
}
// Clone N into Np
ValueToValueMapTy VMap;
for (BasicBlock *B : N->blocks) {
BasicBlock *Bp = CloneBasicBlock(B, VMap, ".c", B->getParent());
Np->insert(Bp);
VMap[B] = Bp;
}
for (BasicBlock *B : Np->blocks)
for (Instruction &I : *B)
RemapInstruction(&I, VMap,
RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
// Remap terminators of P from N to Np
for (BasicBlock *B : P->blocks)
RemapInstruction(B->getTerminator(), VMap,
RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
#else
// Clone N into Np
ValueToValueMapTy VMap;
for (BasicBlock *B : N->blocks) {
BasicBlock *Bp = CloneBasicBlock(B, VMap, ".c", B->getParent());
Np->insert(Bp);
VMap[B] = Bp;
}
for (BasicBlock *B : Np->blocks)
for (Instruction &I : *B)
RemapInstruction(&I, VMap,
RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
// Remove incoming values from phis in Np that don't come from actual
// predecessors
BasicBlock *NpEntry = Np->blocks[0];
std::set<BasicBlock *> predSet(pred_begin(NpEntry), pred_end(NpEntry));
auto I = NpEntry->begin();
while (PHINode *phi = dyn_cast<PHINode>(I++)) {
if (phi->getNumIncomingValues() == predSet.size())
continue;
for (unsigned i = 0; i < phi->getNumIncomingValues();) {
BasicBlock *B = phi->getIncomingBlock(i);
if (!predSet.count(B)) {
phi->removeIncomingValue(B);
continue;
}
++i;
}
}
// Remove phi references to P in N. (Do this before remapping terminators.)
BasicBlock *Nentry = N->blocks[0];
for (BasicBlock *PB : predecessors(Nentry)) {
if (P->blocks.count(PB))
Nentry->removePredecessor(PB);
}
// Remap terminators of P from N to Np
for (BasicBlock *B : P->blocks)
RemapInstruction(B->getTerminator(), VMap,
RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
// Update phis in successors of Np.
// There are several cases for a value Vs reaching S. Vs may be defined in N
// and a clone Vsp in Np or only passing through one or the other.
// Furthermore, Vs may either appear in a phi in the entry block of S or not.
// 1) Vs defined in N (and clone Vsp in Np) and in phi:
// Add incoming value [Vsp, Bp] for cloned value Vsp from predecessor basic
// block Bp in Np wherever [Vs, B] appears
// 2) Vs defined in N (and clone Vsp in Np) and not in phi:
// Add phi [Vs,B],[Vsp,Bp] if Vs reaches a use in or through S
// 3) Vs passing through N or Np and in phi
// Change [Vs,B] to [Vs,Bp] in phis in S if Vs reached S through P
// 4) Vs passing through N or Np and not in a phi
// Do nothing
//
// TODO: Only 1) is implemented below and it isn't checking for definition in
// N
for (Node *S : Np->out) {
BasicBlock *Sentry = S->blocks[0];
auto I = Sentry->begin();
while (PHINode *phi = dyn_cast<PHINode>(I++)) {
for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
BasicBlock *B = phi->getIncomingBlock(i);
if (N->blocks.count(B)) {
Value *V = phi->getIncomingValue(i);
Value *Vp = VMap[V];
if (!Vp)
Vp = V; // Def not in N
BasicBlock *Bp = dyn_cast<BasicBlock>(VMap[B]);
phi->addIncoming(Vp, Bp);
}
}
}
}
#endif
return Np;
}
// Returns the number of splits
int makeReducible(Function *F) {
// Break critical edges now in case we need to do mem2reg in split(). mem2reg
// will break critical edges and the CFG needs to remain unchanged.
runPasses(F, {createBreakCriticalEdgesPass()});
// initialize nodes
std::vector<Node *> nodes;
std::map<BasicBlock *, Node *> bbToNode;
for (BasicBlock &B : *F) {
nodes.push_back(new Node(&B));
bbToNode[&B] = nodes.back();
}
// initialize edges
for (Node *N : nodes) {
for (BasicBlock *B : successors(N->blocks[0])) {
Node *BN = bbToNode[B];
N->out.insert(BN);
BN->in.insert(N);
}
}
int step = 0;
bool print = false;
if (print)
printDotGraph(nodes, F, step++);
int numSplits = 0;
while (!nodes.empty()) {
bool changed;
do {
// It might more efficient to use a worklist based implementation instead
// of iterating over the vector.
changed = false;
for (size_t i = 0; i < nodes.size();) {
Node *N = nodes[i];
// Remove self references
if (N->in.count(N)) {
N->in.remove(N);
N->out.remove(N);
changed = true;
}
// Remove singletons
if (N->in.size() == 0 && N->out.size() == 0) {
nodes.erase(nodes.begin() + i);
changed = true;
if (print)
printDotGraph(nodes, F, step++);
continue;
}
// Remove nodes with only one incoming edge
if (N->in.size() == 1) {
// fold into predecessor
Node *P = N->in.back();
P->blocks.insert(N->blocks.begin(), N->blocks.end());
P->out.remove(N);
for (Node *S : N->out) {
S->in.remove(N);
P->out.insert(S);
S->in.insert(P);
}
P->numInstructions += N->numInstructions;
nodes.erase(nodes.begin() + i);
changed = true;
if (print)
printDotGraph(nodes, F, step++);
continue;
}
i++;
}
} while (changed);
if (!nodes.empty()) {
// Duplicate the smallest node with more than one incoming edge. Better
// methods exist for picking the node to split, e.g. "Making Graphs
// Reducible with Controlled Node Splitting" by Janssen and Corporaal.
size_t idxMin = ~0;
for (size_t i = 0; i < nodes.size(); ++i) {
if (nodes[i]->in.size() <= 1)
continue;
if (idxMin == ~0u ||
nodes[i]->numInstructions < nodes[idxMin]->numInstructions)
idxMin = i;
}
nodes.push_back(split(nodes[idxMin], bbToNode, numSplits == 0));
numSplits++;
if (print)
printDotGraph(nodes, F, step++);
}
}
return numSplits;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxrFallback/LLVMUtils.h | #pragma once
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace llvm {
class CallInst;
class ConstantInt;
class Function;
class FunctionType;
class Instruction;
class LLVMContext;
class Module;
class Pass;
} // namespace llvm
std::vector<llvm::CallInst *>
getCallsToFunction(llvm::Function *callee,
const llvm::Function *caller = nullptr);
llvm::Function *getOrCreateFunction(
const std::string &name, llvm::Module *module, llvm::FunctionType *funcType,
std::map<llvm::FunctionType *, llvm::Function *> &typeToFuncMap);
llvm::ConstantInt *makeInt32(int val, llvm::LLVMContext &context);
llvm::Instruction *getInstructionAfter(llvm::Instruction *inst);
std::unique_ptr<llvm::Module>
loadModuleFromAsmFile(llvm::LLVMContext &context, const std::string &filename);
std::unique_ptr<llvm::Module>
loadModuleFromAsmString(llvm::LLVMContext &context, const std::string &str);
void saveModuleToAsmFile(const llvm::Module *module,
const std::string &filename);
void dumpCFG(const llvm::Function *F, const std::string &suffix);
void runPasses(llvm::Function *, const std::vector<llvm::Pass *> &passes);
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxrFallback/LiveValues.h | #pragma once
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/IR/BasicBlock.h"
#include <map>
#include <set>
#include <vector>
namespace llvm {
class AllocaInst;
class BasicBlock;
class Function;
class Instruction;
class Use;
class Value;
} // namespace llvm
typedef std::set<llvm::BasicBlock *> BasicBlockSet;
typedef llvm::SetVector<llvm::Instruction *> InstructionSetVector;
// Compute live values at specified instructions.
class LiveValues {
public:
LiveValues(llvm::ArrayRef<llvm::Instruction *> computeLiveAt);
// Compute live values at specified instructions (computeLiveAt)
void run();
// Returns all values that are live at the index.
const InstructionSetVector &getLiveValues(unsigned int index) const {
return m_liveSets[index];
}
// Returns all live values, excluding allocas.
const InstructionSetVector &getAllLiveValues() const { return m_allLiveSet; }
// Update the live sets using the map
void remapLiveValues(
llvm::DenseMap<llvm::Instruction *, llvm::Instruction *> &imap);
typedef llvm::SetVector<unsigned int> Indices;
// Return all indices at which the given value is live.
const Indices *getIndicesWhereLive(const llvm::Value *value) const;
// For the two given values, check if they are both live at any of the
// marker instructions. This does not perform a true "lifetime overlap"
// test, it considers values to be disjoint if they have disjoint sets of
// markers.
// For example, value A is live at call sites 0, 1, 2, value B is live at
// 3, 4, where A is used for the last time between 2 and 3 and B is defined
// before that use. A and B will be considered "disjoint" in the sense of
// this method, even though the lifetimes of their values overlap.
bool liveInDisjointRegions(const llvm::Value *valueA,
const llvm::Value *valueB) const;
// Return true if the given value is live at the given index.
bool getLiveAtIndex(const llvm::Value *value, unsigned int index) const;
// Update the analysis manually. Use only if you know exactly what you are
// doing and document the reason thoroughly.
void setLiveAtIndex(llvm::Value *value, unsigned int index, bool live);
void setLiveAtAllIndices(llvm::Value *value, bool live);
void setIndicesWhereLive(llvm::Value *value, const Indices *indices);
private:
llvm::Function *m_function = nullptr;
std::vector<InstructionSetVector> m_liveSets;
InstructionSetVector m_allLiveSet;
llvm::SmallSet<llvm::BasicBlock *, 8> m_activeBlocks;
llvm::DenseMap<llvm::Instruction *, unsigned int> m_computeLiveAtIndex;
llvm::DenseMap<const llvm::Value *, Indices> m_liveAtIndices;
typedef llvm::SmallSet<llvm::BasicBlock *, 8> BlockSet;
void markLiveRange(llvm::Instruction *value, llvm::BasicBlock::iterator begin,
llvm::BasicBlock::iterator end);
void upAndMark(llvm::Instruction *v, llvm::Use &use, BlockSet &scanned);
};
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxrFallback/LiveValues.cpp | #include "LiveValues.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
using namespace llvm;
static void
applyMapping(InstructionSetVector &iset,
llvm::DenseMap<llvm::Instruction *, llvm::Instruction *> &imap) {
// There will be probably be few entries in the imap, so apply them one at a
// time to the iset.
for (auto &kv : imap) {
if (iset.count(kv.first) != 0) {
iset.remove(kv.first);
iset.insert(kv.second);
}
}
}
// Compute liveness of a value at basic blocks. Roughly based on
// Algorithm 6 & 7 from the paper "Computing Liveness Sets for SSA-
// Form Programs" by Brander et al., 2011.
LiveValues::LiveValues(ArrayRef<Instruction *> computeLiveAt) {
m_liveSets.resize(computeLiveAt.size());
// Build index and set of active blocks
for (unsigned int i = 0; i < computeLiveAt.size(); i++) {
Instruction *v = computeLiveAt[i];
m_computeLiveAtIndex.insert(std::make_pair(v, i));
m_activeBlocks.insert(v->getParent());
}
if (computeLiveAt.size() > 0) {
m_function = computeLiveAt[0]->getParent()->getParent();
}
}
// Go over all the instructions between begin (included) and end (excluded) and
// mark the given value live for code locations contained in the given range.
void LiveValues::markLiveRange(Instruction *value, BasicBlock::iterator begin,
BasicBlock::iterator end) {
BasicBlock *B = begin->getParent();
if (m_activeBlocks.count(B) == 0)
return; // Nothing to mark in this block
for (BasicBlock::iterator I = begin; I != end; ++I) {
if (m_computeLiveAtIndex.count(I)) {
// Mark this value
unsigned int index = m_computeLiveAtIndex[I];
m_liveSets[index].insert(value);
m_allLiveSet.insert(value);
// Also store for each value where it is live.
m_liveAtIndices[value].insert(index);
}
}
}
void LiveValues::upAndMark(Instruction *def, Use &use, BlockSet &scanned) {
// Determine the starting point for the backwards search.
// (Remember that Use represents an edge between the definition of a value and
// its use) In the case in which the user of the use is a phi node we start
// the search from the terminator of the preceding block. This allows to avoid
// going through loop back-edges in cases like these:
// |
// | (y)
// v
// -----------------
// (x) | z = phi(x, y) |
// ----> | ... |
// | | x = z + 1 |
// | -----------------
// | |
// | |
// | |
// | v
// | -----------------
// | | |
// ------| INDIRECT CALL |
// | |
// -----------------
// | (Start the search for the definition of x (backwards)
// from here!)
// v
//
// Notice that here x is live across the call. This case is tricky because the
// def comes 'after' the use. The def still dominates the use because phi
// nodes logically use their input values on the edges, i.e. on the terminator
// of the preceding blocks.
//
// This has the advantage of being able to traverse edges strictly backwards.
Instruction *startingPoint = dyn_cast<Instruction>(use.getUser());
if (PHINode *usePHI = dyn_cast<PHINode>(startingPoint)) {
BasicBlock *predecessor = usePHI->getIncomingBlock(use);
startingPoint = predecessor->getTerminator();
}
BasicBlock *startingPointBB = startingPoint->getParent();
BasicBlock *defBB = def->getParent();
// Start a bottom-up recursive search from startingPoint to the definition of
// the current value. Mark all the code ranges that we encounter on the way a
// having the current value 'live'. 'scanned' contains the blocks that we have
// scanned to the bottom of the block and the we know already having the
// current value 'live'.
SmallVector<BasicBlock *, 16> worklist;
worklist.push_back(startingPointBB);
BlockSet visited;
while (!worklist.empty()) {
BasicBlock *B = worklist.pop_back_val();
if (scanned.count(B) != 0)
continue;
// We have reached the block that contains the definition of the value. We
// are done for this branch of the search.
if (B == defBB) {
if (defBB == startingPointBB) {
// If the first block that we visit is also the last mark only the range
// of instructions between the def and the starting point.
// -----------------
// | |
// | x = // def | <--
// | | !
// | | ! This is the range in which x is live.
// | | !
// | = x // use | <--
// | |
// -----------------
markLiveRange(def, ++BasicBlock::iterator(def),
BasicBlock::iterator(startingPoint));
} else {
markLiveRange(def, ++BasicBlock::iterator(def), defBB->end());
scanned.insert(B);
}
} else {
if (B == startingPointBB) {
// We are in the starting-point block.
// This can mean two things:
// 1. We are in the first iteration, mark the range between begin and
// starting point as live.
if (visited.count(B) == 0) {
markLiveRange(def, B->begin(), BasicBlock::iterator(startingPoint));
}
// 2. We came back here because the starting point is in a loop.
// In this case mark the whole block as live range and don't come back
// anymore.
else {
markLiveRange(def, B->begin(), B->end());
scanned.insert(B);
}
// The if statement above allows to manage situations like this:
// BB0
// -----------------
// | x = ... |
// -----------------
// |
// |
// |
// BB1 v
// -----------------<-- <--
// | | ! !
// ----->| | ! First range marked !
// | | | ! !
// | | ... = x |<-- ! Second and final
// range marked | | | ! | |
// INDIRECT CALL | ! | | | !
// | ----------------- <--
// | |
// ---------------
// x is defined outside a loop and used inside a loop. This means that
// it is live inside the whole loop. So, we first mark the range from
// the use of x to the top of BB1 and, when we visit BB1 again (because
// BB1 is a predecessor of BB1) we mark the whole block as live range.
// <rant>
// This case could have been managed much more easily and efficiently if
// we had access to LLVM LoopInfo analysis pass. We could have done the
// following: x is uses in a loop and defined outside of it => mark the
// whole loop body as live range.
// </rant>
} else {
// We are in an intermediate block on the way to the definition mark it,
// all as live range.
markLiveRange(def, B->begin(), B->end());
scanned.insert(B);
}
visited.insert(B);
for (pred_iterator P = pred_begin(B), PE = pred_end(B); P != PE; ++P) {
worklist.push_back(*P);
}
}
}
}
void LiveValues::run() {
if (m_computeLiveAtIndex.empty())
return;
// for each variable v do
for (inst_iterator I = inst_begin(m_function), E = inst_end(m_function);
I != E; ++I) {
Instruction *v = &*I;
assert(v->getParent()->getParent() == m_function);
// for each block B where v is used do
BlockSet scanned;
for (Value::use_iterator U = v->use_begin(), UE = v->use_end(); U != UE;
++U) {
Instruction *user = cast<Instruction>(U->getUser());
assert(user->getParent()->getParent() == m_function);
(void)user;
upAndMark(v, *U, scanned);
}
}
}
void LiveValues::remapLiveValues(
llvm::DenseMap<llvm::Instruction *, llvm::Instruction *> &imap) {
applyMapping(m_allLiveSet, imap);
for (auto &liveSet : m_liveSets)
applyMapping(liveSet, imap);
}
const LiveValues::Indices *
LiveValues::getIndicesWhereLive(const Value *value) const {
const auto &iter = m_liveAtIndices.find(value);
if (iter == m_liveAtIndices.end())
return nullptr;
return &iter->second;
}
void LiveValues::setIndicesWhereLive(Value *value, const Indices *indices) {
for (unsigned int idx : *indices)
setLiveAtIndex(value, idx, true);
}
bool LiveValues::liveInDisjointRegions(const Value *valueA,
const Value *valueB) const {
const Indices *indicesA = getIndicesWhereLive(valueA);
if (!indicesA)
return true;
const Indices *indicesB = getIndicesWhereLive(valueB);
if (!indicesB)
return true;
for (const unsigned int index : *indicesA) {
if (indicesB->count(index))
return false;
}
return true;
}
void LiveValues::setLiveAtIndex(Value *value, unsigned int index, bool live) {
assert(index <= m_computeLiveAtIndex.size());
if (live) {
m_liveAtIndices[value].insert(index);
Instruction *inst = cast<Instruction>(value);
m_liveSets[index].insert(inst);
m_allLiveSet.insert(inst);
} else {
m_liveAtIndices[value].remove(index);
Instruction *inst = cast<Instruction>(value);
m_liveSets[index].remove(inst);
if (m_liveAtIndices[value].empty())
m_allLiveSet.remove(inst);
}
}
void LiveValues::setLiveAtAllIndices(llvm::Value *value, bool live) {
Instruction *inst = cast<Instruction>(value);
if (live) {
for (unsigned int index = 0; index < m_computeLiveAtIndex.size(); ++index) {
m_liveAtIndices[value].insert(index);
m_liveSets[index].insert(inst);
}
m_allLiveSet.insert(inst);
} else {
for (unsigned int index = 0; index < m_computeLiveAtIndex.size(); ++index) {
m_liveAtIndices[value].remove(index);
m_liveSets[index].remove(inst);
}
if (m_liveAtIndices[value].empty())
m_allLiveSet.remove(inst);
}
}
bool LiveValues::getLiveAtIndex(const Value *value, unsigned int index) const {
assert(index <= m_computeLiveAtIndex.size());
const auto &it = m_liveAtIndices.find(value);
if (it == m_liveAtIndices.end())
return false;
return (it->second.count(index) != 0);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxrFallback/StateFunctionTransform.cpp | #include "StateFunctionTransform.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/ValueMap.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/Local.h"
#include "FunctionBuilder.h"
#include "LLVMUtils.h"
#include "LiveValues.h"
#include "Reducibility.h"
#define DBGS dbgs
//#define DBGS errs
using namespace llvm;
static const char *CALL_INDIRECT_NAME = "\x1?Fallback_CallIndirect@@YAXH@Z";
static const char *SET_PENDING_ATTR_PREFIX = "\x1?Fallback_SetPendingAttr@@";
// Create a string with printf-like arguments
inline std::string stringf(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
#ifdef WIN32
int size = _vscprintf(fmt, args);
#else
int size = vsnprintf(0, 0, fmt, args);
#endif
va_end(args);
std::string ret;
if (size > 0) {
ret.resize(size);
va_start(args, fmt);
vsnprintf(const_cast<char *>(ret.data()), size + 1, fmt, args);
va_end(args);
}
return ret;
}
// Remove ELF mangling
static std::string cleanName(StringRef name) {
if (!name.startswith("\x1?"))
return name;
size_t pos = name.find("@@");
if (pos == name.npos)
return name;
std::string newName = name.substr(2, pos - 2);
return newName;
}
// Utility to append the suffix to the name of the value, but returns
// an empty string if name is empty. This is to avoid names like ".ptr".
static std::string addSuffix(StringRef valueName, StringRef suffix) {
if (!valueName.empty()) {
if (valueName.back() == '.' && suffix.front() == '.') // avoid double dots
return (valueName + suffix.substr(1)).str();
else
return (valueName + suffix).str();
} else
return valueName.str();
}
// Remove suffix from name.
static std::string stripSuffix(StringRef name, StringRef suffix) {
size_t pos = name.rfind(suffix);
if (pos != name.npos)
return name.substr(0, pos).str();
else
return name.str();
}
// Insert str before the final "." in filename.
static std::string insertBeforeExtension(const std::string &filename,
const std::string &str) {
std::string ret = filename;
size_t pos = filename.rfind('.');
if (pos != std::string::npos)
ret.insert(pos, str);
else
ret += str;
return ret;
}
// Inserts <functionName>-<id>-<suffix> before the extension in baseName
static std::string createDumpPath(const std::string &baseName, unsigned id,
const std::string &suffix,
const std::string &functionName) {
std::string s;
if (!functionName.empty())
s = "-" + functionName;
s += stringf("-%02d-", id) + suffix;
return insertBeforeExtension(baseName, s);
}
// Return byte offset aligned to the alignment required by inst.
static uint64_t align(uint64_t offset, Instruction *inst, DataLayout &DL) {
unsigned alignment = 0;
if (AllocaInst *ai = dyn_cast<AllocaInst>(inst))
alignment = ai->getAlignment();
if (alignment == 0)
alignment = DL.getPrefTypeAlignment(inst->getType());
return RoundUpToAlignment(offset, alignment);
}
template <class T> // T can be Value* or Instruction*
T createCastForStack(T ptr, llvm::Type *targetPtrElemType,
llvm::Instruction *insertBefore) {
llvm::PointerType *requiredType = llvm::PointerType::get(
targetPtrElemType, ptr->getType()->getPointerAddressSpace());
if (ptr->getType() == requiredType)
return ptr;
return new llvm::BitCastInst(ptr, requiredType, ptr->getName(), insertBefore);
}
static Value *createCastToInt(Value *val, Instruction *insertBefore) {
Type *i32Ty = Type::getInt32Ty(val->getContext());
if (val->getType() == i32Ty)
return val;
if (val->getType() == Type::getInt1Ty(val->getContext()))
return new ZExtInst(val, i32Ty, addSuffix(val->getName(), ".int"),
insertBefore);
Value *intVal = new BitCastInst(val, i32Ty, addSuffix(val->getName(), ".int"),
insertBefore);
return intVal;
}
static Value *createCastFromInt(Value *intVal, Type *ty,
Instruction *insertBefore) {
Type *i32Ty = Type::getInt32Ty(intVal->getContext());
if (ty == i32Ty)
return intVal;
std::string name = intVal->getName();
intVal->setName(addSuffix(name, ".int"));
// Create boolean with compare
if (ty == Type::getInt1Ty(intVal->getContext()))
return new ICmpInst(insertBefore, CmpInst::ICMP_SGT, intVal,
makeInt32(0, intVal->getContext()), name);
return new BitCastInst(intVal, ty, name, insertBefore);
}
// Gives every value in the given function a name. This can aid in debugging.
static void dbgNameUnnamedVals(Function *func) {
Type *voidTy = Type::getVoidTy(func->getContext());
for (auto &I : inst_range(func)) {
if (!I.hasName() && I.getType() != voidTy)
I.setName("v"); // LLVM will uniquify the name by adding a numeric suffix
}
}
// Returns an iterator for the instruction after the last alloca in the entry
// block (assuming that allocas are at the top of the entry block).
static BasicBlock::iterator afterEntryBlockAllocas(Function *function) {
BasicBlock::iterator insertBefore = function->getEntryBlock().begin();
while (isa<AllocaInst>(insertBefore))
++insertBefore;
return insertBefore;
}
// Return all the blocks reachable from entryBlock.
static BasicBlockVector getReachableBlocks(BasicBlock *entryBlock) {
BasicBlockVector blocks;
std::deque<BasicBlock *> stack = {entryBlock};
::BasicBlockSet visited = {entryBlock};
while (!stack.empty()) {
BasicBlock *block = stack.front();
stack.pop_front();
blocks.push_back(block);
TerminatorInst *termInst = block->getTerminator();
for (unsigned int succ = 0, succEnd = termInst->getNumSuccessors();
succ != succEnd; ++succ) {
BasicBlock *succBlock = termInst->getSuccessor(succ);
if (visited.insert(succBlock).second)
stack.push_front(succBlock);
}
}
return blocks;
}
// Creates a new function with the same arguments and attributes as oldFunction
static Function *cloneFunctionPrototype(const Function *oldFunction,
ValueToValueMapTy &VMap) {
std::vector<Type *> argTypes;
for (auto I = oldFunction->arg_begin(), E = oldFunction->arg_end(); I != E;
++I)
argTypes.push_back(I->getType());
FunctionType *FTy =
FunctionType::get(oldFunction->getFunctionType()->getReturnType(),
argTypes, oldFunction->getFunctionType()->isVarArg());
Function *newFunction =
Function::Create(FTy, oldFunction->getLinkage(), oldFunction->getName());
Function::arg_iterator destI = newFunction->arg_begin();
for (auto I = oldFunction->arg_begin(), E = oldFunction->arg_end(); I != E;
++I, ++destI) {
destI->setName(I->getName());
VMap[I] = destI;
}
AttributeSet oldAttrs = oldFunction->getAttributes();
for (auto I = oldFunction->arg_begin(), E = oldFunction->arg_end(); I != E;
++I) {
if (Argument *Anew = dyn_cast<Argument>(VMap[I])) {
AttributeSet attrs = oldAttrs.getParamAttributes(I->getArgNo() + 1);
if (attrs.getNumSlots() > 0)
Anew->addAttr(attrs);
}
}
newFunction->setAttributes(newFunction->getAttributes().addAttributes(
newFunction->getContext(), AttributeSet::ReturnIndex,
oldAttrs.getRetAttributes()));
newFunction->setAttributes(newFunction->getAttributes().addAttributes(
newFunction->getContext(), AttributeSet::FunctionIndex,
oldAttrs.getFnAttributes()));
return newFunction;
}
// Creates a new function by cloning blocks reachable from entryBlock
static Function *cloneBlocksReachableFrom(BasicBlock *entryBlock,
ValueToValueMapTy &VMap) {
Function *oldFunction = entryBlock->getParent();
Function *newFunction = cloneFunctionPrototype(oldFunction, VMap);
// Insert a clone of the entry block into the function.
BasicBlock *newEntry = CloneBasicBlock(entryBlock, VMap, "", newFunction);
VMap[entryBlock] = newEntry;
// Clone all other blocks.
BasicBlockVector blocks = getReachableBlocks(entryBlock);
for (auto block : blocks) {
if (block == entryBlock)
continue;
BasicBlock *clonedBlock = CloneBasicBlock(block, VMap, "", newFunction);
VMap[block] = clonedBlock;
}
// Remap new instructions to reference blocks and instructions of the new
// function.
for (auto block : blocks) {
auto clonedBlock = cast<BasicBlock>(VMap[block]);
for (BasicBlock::iterator I = clonedBlock->begin(); I != clonedBlock->end();
++I) {
RemapInstruction(I, VMap,
RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
}
}
// Remove phi operands incoming from blocks that are not present in the new
// function anymore.
for (auto &block : *newFunction) {
PHINode *firstPHI = dyn_cast<PHINode>(block.begin());
if (firstPHI == nullptr)
continue; // phi instructions only at beginning
// Create set of actual predecessors
BasicBlockSet preds(pred_begin(&block), pred_end(&block));
if (preds.size() == firstPHI->getNumIncomingValues())
continue;
// Remove phi incoming blocks not in preds
for (auto iter = block.begin(); isa<PHINode>(iter); ++iter) {
std::vector<unsigned int> toRemove;
PHINode *phi = cast<PHINode>(iter);
for (unsigned int op = 0, opEnd = phi->getNumIncomingValues();
op != opEnd; ++op) {
BasicBlock *pred = phi->getIncomingBlock(op);
if (preds.count(pred) == 0) {
toRemove.push_back(op);
}
}
for (auto I = toRemove.rbegin(), E = toRemove.rend(); I != E; ++I)
phi->removeIncomingValue(*I, false);
}
}
return newFunction;
}
// Replace and remove calls to func with val
static void replaceValAndRemoveUnusedDummyFunc(Value *oldVal, Value *newVal,
Function *caller) {
CallInst *call = dyn_cast<CallInst>(oldVal);
assert(call != nullptr && "Must be a call");
Function *func = call->getCalledFunction();
for (CallInst *CI : getCallsToFunction(func, caller)) {
CI->replaceAllUsesWith(newVal);
CI->eraseFromParent();
}
if (func->getNumUses() == 0)
func->eraseFromParent();
}
// Get the integer value of val. If val is not a ConstantInt return false.
static bool getConstantValue(int &constant, const Value *val) {
const ConstantInt *CI = dyn_cast<ConstantInt>(val);
if (!CI)
return false;
if (CI->getBitWidth() > 32)
return false;
constant = static_cast<int>(CI->getSExtValue());
return true;
}
static int getConstantValue(const Value *val) {
const ConstantInt *CI = dyn_cast<ConstantInt>(val);
assert(CI && CI->getBitWidth() <= 32);
return static_cast<int>(CI->getSExtValue());
}
struct StoreInfo {
Function *stackIntPtrFunc;
Value *runtimeDataArg;
Value *baseOffset;
Instruction *insertBefore;
Value *val;
std::vector<Value *> idxList;
};
// Takes the offset at which to store the next value.
// Returns the next available offset.
static int store(int offset, StoreInfo &SI, Type *ty) {
if (StructType *STy = dyn_cast<StructType>(ty)) {
SI.idxList.push_back(nullptr);
int elIdx = 0;
for (auto &elTy : STy->elements()) {
SI.idxList.back() = makeInt32(elIdx++, ty->getContext());
offset = store(offset, SI, elTy);
}
SI.idxList.pop_back();
} else if (ArrayType *ATy = dyn_cast<ArrayType>(ty)) {
Type *elTy = ATy->getArrayElementType();
SI.idxList.push_back(nullptr);
for (int elIdx = 0; elIdx < (int)ATy->getArrayNumElements(); ++elIdx) {
SI.idxList.back() = makeInt32(elIdx, ty->getContext());
offset = store(offset, SI, elTy);
}
SI.idxList.pop_back();
} else if (PointerType *PTy = dyn_cast<PointerType>(ty)) {
SI.idxList.push_back(makeInt32(0, ty->getContext()));
offset = store(offset, SI, PTy->getPointerElementType());
SI.idxList.pop_back();
} else {
Value *val = SI.val;
if (!SI.idxList.empty()) {
Value *gep = GetElementPtrInst::CreateInBounds(SI.val, SI.idxList, "",
SI.insertBefore);
val = new LoadInst(gep, "", SI.insertBefore);
}
if (VectorType *VTy = dyn_cast<VectorType>(ty)) {
std::vector<Value *> idxList = std::move(SI.idxList);
Type *elTy = VTy->getVectorElementType();
for (int elIdx = 0; elIdx < (int)VTy->getVectorNumElements(); ++elIdx) {
Value *idxVal = makeInt32(elIdx, ty->getContext());
Value *el =
ExtractElementInst::Create(val, idxVal, "", SI.insertBefore);
SI.val = el;
offset = store(offset, SI, elTy);
}
SI.idxList = std::move(idxList);
} else {
Value *idxVal = makeInt32(offset, val->getContext());
Value *intVal = createCastToInt(val, SI.insertBefore);
Value *intPtr = CallInst::Create(
SI.stackIntPtrFunc, {SI.runtimeDataArg, SI.baseOffset, idxVal},
addSuffix(val->getName(), ".ptr"), SI.insertBefore);
new StoreInst(intVal, intPtr, SI.insertBefore);
offset += 1;
}
}
return offset;
}
// Store value to the stack at given baseOffset + offset. Will flatten
// aggregates and vectors. Returns the offset where writing left off. For
// pointer vals stores what is pointed to.
static int store(Value *val, Function *stackIntPtrFunc, Value *runtimeDataArg,
Value *baseOffset, int offset, Instruction *insertBefore) {
StoreInfo SI;
SI.stackIntPtrFunc = stackIntPtrFunc;
SI.runtimeDataArg = runtimeDataArg;
SI.baseOffset = baseOffset;
SI.insertBefore = insertBefore;
SI.val = val;
return store(offset, SI, val->getType());
}
static Value *load(llvm::Function *m_stackIntPtrFunc, Value *runtimeDataArg,
Value *offset, Value *idx, const std::string &name, Type *ty,
Instruction *insertBefore) {
if (VectorType *VTy = dyn_cast<VectorType>(ty)) {
LLVMContext &C = ty->getContext();
int baseIdx = getConstantValue(idx);
Type *elTy = VTy->getVectorElementType();
Value *vec = UndefValue::get(VTy);
for (int i = 0; i < (int)VTy->getVectorNumElements(); ++i) {
std::string elName = stringf("el%d.", i);
Value *intPtr =
CallInst::Create(m_stackIntPtrFunc,
{runtimeDataArg, offset, makeInt32(baseIdx + i, C)},
elName + "ptr", insertBefore);
Value *intEl = new LoadInst(intPtr, elName, insertBefore);
Value *el = createCastFromInt(intEl, elTy, insertBefore);
vec = InsertElementInst::Create(vec, el, makeInt32(i, C), "tmpvec",
insertBefore);
}
vec->setName(name);
return vec;
} else {
Value *intPtr =
CallInst::Create(m_stackIntPtrFunc, {runtimeDataArg, offset, idx},
addSuffix(name, ".ptr"), insertBefore);
Value *intVal = new LoadInst(intPtr, name, insertBefore);
Value *val = createCastFromInt(intVal, ty, insertBefore);
return val;
}
}
static void reg2Mem(DenseMap<Instruction *, AllocaInst *> &valToAlloca,
DenseMap<AllocaInst *, Instruction *> &allocaToVal,
Instruction *inst) {
if (valToAlloca.count(inst))
return;
// Convert the value to an alloca
AllocaInst *allocaPtr = DemoteRegToStack(*inst, false);
if (allocaPtr) {
valToAlloca[inst] = allocaPtr;
allocaToVal[allocaPtr] = inst;
}
}
// Utility class for rematerializing values at a callsite
class Rematerializer {
public:
Rematerializer(DenseMap<AllocaInst *, Instruction *> &allocaToVal,
const InstructionSetVector &liveHere,
const std::set<Value *> &resources)
: m_allocaToVal(allocaToVal), m_liveHere(liveHere),
m_resources(resources) {}
// Returns true if inst can be rematerialized.
bool canRematerialize(Instruction *inst) {
if (CallInst *call = dyn_cast<CallInst>(inst)) {
StringRef funcName = call->getCalledFunction()->getName();
if (funcName.startswith("dummyStackFrameSize"))
return true;
if (funcName.startswith("stack.ptr"))
return true;
if (funcName.startswith("stack.load"))
return true;
if (funcName.startswith("dx.op.createHandle"))
return true;
} else if (LoadInst *load = dyn_cast<LoadInst>(inst)) {
Value *op = load->getOperand(0);
if (GetElementPtrInst *gep =
dyn_cast<GetElementPtrInst>(op)) // for descriptor tables
op = gep->getOperand(0);
if (m_resources.count(op))
return true;
} else if (GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(inst)) {
assert(gep->hasAllConstantIndices() &&
"Unhandled non-constant index"); // Should have been changed to
// stack.ptr
return true;
}
return false;
}
// Rematerialize the given instruction and its dependency graph, adding
// any nonrematerializable values that are live in the function, but not
// at this callsite to the work list to insure that their values are restored.
Instruction *rematerialize(Instruction *inst,
std::vector<Instruction *> workList,
Instruction *insertBefore, int depth = 0) {
// Signal if we hit a complex case. Deep rematerialization needs more
// analysis. To make this robust we would need to make it possible to run
// the current value through the live value handling pipeline: figure out
// where it is live, reg2mem, save/restore at appropriate callsites, etc.
assert(depth < 8);
// Reuse an already rematerialized value?
auto it = m_rematMap.find(inst);
if (it != m_rematMap.end())
return it->second;
// Handle allocas
if (AllocaInst *alloc = dyn_cast<AllocaInst>(inst)) {
assert(depth >
0); // Should only be an operand to another rematerialized value
auto it = m_allocaToVal.find(alloc);
if (it != m_allocaToVal.end()) // Is it a value that is live at some
// callsite (and reg2mem'd)?
{
Instruction *val = it->second;
if (canRematerialize(val)) {
// Rematerialize here and store to the alloca. We may have already
// rematerialized a load from the alloca. Any future uses will use the
// rematerialized value directly.
Instruction *remat =
rematerialize(val, workList, insertBefore, depth + 1);
new StoreInst(remat, alloc, insertBefore);
} else {
// Value has to be restored, but it rematerialization may have
// extended the liveness of this value to this callsite. Make sure it
// gets restored.
if (!m_liveHere.count(val))
workList.push_back(val);
}
}
// Allocas are not cloned.
return inst;
}
Instruction *clone = inst->clone();
clone->setName(addSuffix(inst->getName(), ".remat"));
for (unsigned i = 0; i < inst->getNumOperands(); ++i) {
Value *op = inst->getOperand(i);
if (Instruction *opInst = dyn_cast<Instruction>(op))
clone->setOperand(
i, rematerialize(opInst, workList, insertBefore, depth + 1));
else
clone->setOperand(i, op);
}
clone->insertBefore(
insertBefore); // insert after any instructions cloned for operands
m_rematMap[inst] = clone;
return clone;
}
Instruction *getRematerializedValueFor(Instruction *val) {
auto it = m_rematMap.find(val);
if (it != m_rematMap.end())
return it->second;
else
return nullptr;
}
private:
DenseMap<Instruction *, Instruction *>
m_rematMap; // Map instructions to their rematerialized counterparts
DenseMap<AllocaInst *, Instruction *>
&m_allocaToVal; // Map allocas for reg2mem'd live values back to the value
const InstructionSetVector &m_liveHere; // Values live at this callsite
const std::set<Value *>
&m_resources; // Values for resources like SRVs, UAVs, etc.
};
StateFunctionTransform::StateFunctionTransform(
Function *func, const std::vector<std::string> &candidateFuncNames,
Type *runtimeDataArgTy)
: m_function(func), m_candidateFuncNames(candidateFuncNames),
m_runtimeDataArgTy(runtimeDataArgTy) {
m_functionName = cleanName(m_function->getName());
auto it = std::find(m_candidateFuncNames.begin(), m_candidateFuncNames.end(),
m_functionName);
assert(it != m_candidateFuncNames.end());
m_functionIdx = it - m_candidateFuncNames.begin();
}
void StateFunctionTransform::setAttributeSize(int size) {
m_attributeSizeInBytes = size;
}
void StateFunctionTransform::setParameterInfo(
const std::vector<ParameterSemanticType> ¶mTypes,
bool useCommittedAttr) {
m_paramTypes = paramTypes;
m_useCommittedAttr = useCommittedAttr;
}
void StateFunctionTransform::setResourceGlobals(
const std::set<llvm::Value *> &resources) {
m_resources = &resources;
}
Function *
StateFunctionTransform::createDummyRuntimeDataArgFunc(Module *mod,
Type *runtimeDataArgTy) {
return FunctionBuilder(mod, "dummyRuntimeDataArg")
.type(runtimeDataArgTy)
.build();
}
void StateFunctionTransform::setVerbose(bool val) { m_verbose = val; }
void StateFunctionTransform::setDumpFilename(const std::string &dumpFilename) {
m_dumpFilename = dumpFilename;
}
void StateFunctionTransform::run(std::vector<Function *> &stateFunctions,
unsigned int &shaderStackSize) {
printFunction("Initial");
init();
printFunction("AfterInit");
changeCallingConvention();
printFunction("AfterCallingConvention");
preserveLiveValuesAcrossCallsites(shaderStackSize);
printFunction("AfterPreserveLiveValues");
createSubstateFunctions(stateFunctions);
printFunctions(stateFunctions, "AfterSubstateFunctions");
lowerStackFuncs();
printFunctions(stateFunctions, "AfterLowerStackFuncs");
}
void StateFunctionTransform::finalizeStateIds(
llvm::Module *mod, const std::vector<int> &candidateFuncEntryStateIds) {
LLVMContext &context = mod->getContext();
Function *func = mod->getFunction("dummyStateId");
if (!func)
return;
std::vector<Instruction *> toRemove;
for (User *U : func->users()) {
CallInst *call = dyn_cast<CallInst>(U);
if (!call)
continue;
int functionIdx = 0;
int substate = 0;
getConstantValue(functionIdx, call->getArgOperand(0));
getConstantValue(substate, call->getArgOperand(1));
int stateId = candidateFuncEntryStateIds[functionIdx] + substate;
call->replaceAllUsesWith(makeInt32(stateId, context));
toRemove.push_back(call);
}
for (Instruction *v : toRemove)
v->eraseFromParent();
func->eraseFromParent();
}
void StateFunctionTransform::init() {
Module *mod = m_function->getParent();
m_function->setName(cleanName(m_function->getName()));
// Run preparatory passes
runPasses(m_function, {// createBreakCriticalEdgesPass(),
// createLoopSimplifyPass(),
// createLCSSAPass(),
createPromoteMemoryToRegisterPass()});
// Make debugging a little easier by giving things names
dbgNameUnnamedVals(m_function);
findCallSitesIntrinsicsAndReturns();
// Create a bunch of functions that we are going to need
m_stackIntPtrFunc = FunctionBuilder(mod, "stackIntPtr")
.i32Ptr()
.type(m_runtimeDataArgTy, "runtimeData")
.i32("baseOffset")
.i32("offset")
.build();
Instruction *insertBefore = afterEntryBlockAllocas(m_function);
Function *runtimeDataArgFunc =
createDummyRuntimeDataArgFunc(mod, m_runtimeDataArgTy);
m_runtimeDataArg =
CallInst::Create(runtimeDataArgFunc, "runtimeData", insertBefore);
Function *stackFrameSizeFunc =
FunctionBuilder(mod, "dummyStackFrameSize").i32().build();
m_stackFrameSizeVal =
CallInst::Create(stackFrameSizeFunc, "stackFrame.size", insertBefore);
// TODO only create the values that are actually needed
Function *payloadOffsetFunc = FunctionBuilder(mod, "payloadOffset")
.i32()
.type(m_runtimeDataArgTy, "runtimeData")
.build();
m_payloadOffset = CallInst::Create(payloadOffsetFunc, {m_runtimeDataArg},
"payload.offset", insertBefore);
Function *committedAttrOffsetFunc =
FunctionBuilder(mod, "committedAttrOffset")
.i32()
.type(m_runtimeDataArgTy, "runtimeData")
.build();
m_committedAttrOffset =
CallInst::Create(committedAttrOffsetFunc, {m_runtimeDataArg},
"committedAttr.offset", insertBefore);
Function *pendingAttrOffsetFunc = FunctionBuilder(mod, "pendingAttrOffset")
.i32()
.type(m_runtimeDataArgTy, "runtimeData")
.build();
m_pendingAttrOffset =
CallInst::Create(pendingAttrOffsetFunc, {m_runtimeDataArg},
"pendingAttr.offset", insertBefore);
Function *stackFrameOffsetFunc = FunctionBuilder(mod, "stackFrameOffset")
.i32()
.type(m_runtimeDataArgTy, "runtimeData")
.build();
m_stackFrameOffset =
CallInst::Create(stackFrameOffsetFunc, {m_runtimeDataArg},
"stackFrame.offset", insertBefore);
// lower SetPendingAttr() now
for (CallInst *call : m_setPendingAttrCalls) {
// Get the current pending attribute offset. It can change when a hit is
// committed
Instruction *insertBefore = call;
Value *currentPendingAttrOffset =
CallInst::Create(pendingAttrOffsetFunc, {m_runtimeDataArg},
"cur.pendingAttr.offset", insertBefore);
Value *attr = call->getArgOperand(0);
createStackStore(currentPendingAttrOffset, attr, 0, insertBefore);
call->eraseFromParent();
}
}
void StateFunctionTransform::findCallSitesIntrinsicsAndReturns() {
// Create a map for log N lookup
std::map<std::string, int> candidateFuncMap;
for (int i = 0; i < (int)m_candidateFuncNames.size(); ++i)
candidateFuncMap[m_candidateFuncNames[i]] = i;
for (auto &I : inst_range(m_function)) {
if (CallInst *call = dyn_cast<CallInst>(&I)) {
StringRef calledFuncName = call->getCalledFunction()->getName();
if (calledFuncName.startswith(SET_PENDING_ATTR_PREFIX))
m_setPendingAttrCalls.push_back(call);
else if (calledFuncName.startswith("movePayloadToStack"))
m_movePayloadToStackCalls.push_back(call);
else if (calledFuncName == CALL_INDIRECT_NAME)
m_callSites.push_back(call);
else {
auto it = candidateFuncMap.find(cleanName(calledFuncName));
if (it == candidateFuncMap.end())
continue;
assert(call->getCalledFunction()->getReturnType() ==
Type::getVoidTy(call->getContext()) &&
"Continuations with returns not supported");
m_callSites.push_back(call);
m_callSiteFunctionIdx.push_back(it->second);
}
} else if (ReturnInst *ret = dyn_cast<ReturnInst>(&I)) {
m_returns.push_back(ret);
}
}
}
void StateFunctionTransform::changeCallingConvention() {
if (!m_callSites.empty() || m_attributeSizeInBytes >= 0)
allocateStackFrame();
if (m_attributeSizeInBytes >= 0)
allocateTraceFrame();
createArgFrames();
changeFunctionSignature();
}
static bool isCallToStackPtr(Value *inst) {
CallInst *call = dyn_cast<CallInst>(inst);
if (call && call->getCalledFunction()->getName().startswith("stack.ptr"))
return true;
return false;
}
static void extendAllocaLifetimes(LiveValues &lv) {
for (Instruction *inst : lv.getAllLiveValues()) {
if (!inst->getType()->isPointerTy())
continue;
if (isa<AllocaInst>(inst) || isCallToStackPtr(inst))
continue;
GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(inst);
assert(gep && "Unhandled live pointer");
Value *ptr = gep->getPointerOperand();
if (isCallToStackPtr(ptr))
continue;
AllocaInst *alloc = dyn_cast<AllocaInst>(gep->getPointerOperand());
assert(alloc && "GEP of non-alloca pointer");
// TODO: We need to set indices of the uses of the gep, not the gep itself
const LiveValues::Indices *gepIndices = lv.getIndicesWhereLive(gep);
const LiveValues::Indices *allocIndices = lv.getIndicesWhereLive(alloc);
if (!allocIndices || *allocIndices != *gepIndices)
lv.setIndicesWhereLive(alloc, gepIndices);
}
}
void StateFunctionTransform::preserveLiveValuesAcrossCallsites(
unsigned int &shaderStackSize) {
if (m_callSites.empty()) {
// No stack frame. Nothing to do.
rewriteDummyStackSize(0);
return;
}
SetVector<Instruction *> stackOffsets;
stackOffsets.insert(m_stackFrameOffset);
if (m_payloadOffset && !m_payloadOffset->user_empty())
stackOffsets.insert(m_payloadOffset);
if (m_committedAttrOffset && !m_committedAttrOffset->user_empty())
stackOffsets.insert(m_committedAttrOffset);
if (m_pendingAttrOffset && !m_pendingAttrOffset->user_empty())
stackOffsets.insert(m_pendingAttrOffset);
// Do liveness analysis
ArrayRef<Instruction *> instructions((Instruction **)m_callSites.data(),
m_callSites.size());
LiveValues lv(instructions);
lv.run();
// Make sure alloca lifetimes match their uses
extendAllocaLifetimes(lv);
// Make sure stack offsets get included
for (auto o : stackOffsets)
lv.setLiveAtAllIndices(o, true);
// Add payload allocas, if any
for (CallInst *call : m_movePayloadToStackCalls) {
if (AllocaInst *payloadAlloca =
dyn_cast<AllocaInst>(call->getArgOperand(0)))
lv.setLiveAtAllIndices(payloadAlloca, true);
}
printSet(lv.getAllLiveValues(), "live values");
//
// Carve up the stack frame.
//
uint64_t offsetInBytes = 0;
// ... argument frame
offsetInBytes += m_maxCallerArgFrameSizeInBytes;
// ... live allocas.
Module *mod = m_function->getParent();
DataLayout DL(mod);
DenseMap<Instruction *, Instruction *> allocaToStack;
Instruction *insertBefore = getInstructionAfter(m_stackFrameOffset);
for (Instruction *inst : lv.getAllLiveValues()) {
AllocaInst *alloc = dyn_cast<AllocaInst>(inst);
if (!alloc)
continue;
// Allocate a slot in the stack frame for the alloca
offsetInBytes = align(offsetInBytes, inst, DL);
Instruction *stackAlloca =
createStackPtr(m_stackFrameOffset, alloc, offsetInBytes, insertBefore);
alloc->replaceAllUsesWith(stackAlloca);
allocaToStack[inst] = stackAlloca;
offsetInBytes += DL.getTypeAllocSize(alloc->getAllocatedType());
}
lv.remapLiveValues(allocaToStack); // replace old allocas with stackAllocas
for (auto &kv : allocaToStack)
kv.first->eraseFromParent(); // delete old allocas
// Set payload offsets now that they are all on the stack
for (CallInst *call : m_movePayloadToStackCalls) {
CallInst *payloadStackPtr = dyn_cast<CallInst>(call->getArgOperand(0));
assert(payloadStackPtr->getCalledFunction()->getName().startswith(
"stack.ptr"));
Value *baseOffset = payloadStackPtr->getArgOperand(0);
Value *idx = payloadStackPtr->getArgOperand(1);
Value *payloadOffset =
BinaryOperator::Create(Instruction::Add, baseOffset, idx, "", call);
call->replaceAllUsesWith(payloadOffset);
payloadOffset->takeName(call);
call->eraseFromParent();
}
// printFunction("AfterStackAllocas");
// ... saves/restores for each call site
// Create allocas for live values. This makes it easier to generate code
// because we don't have to maintain the use-def chains of SSA form. We can
// just load/store from/to the alloca for a particular value. A subsequent
// mem2reg pass will rebuild the SSA form.
DenseMap<Instruction *, AllocaInst *> valToAlloca;
DenseMap<AllocaInst *, Instruction *> allocaToVal;
for (Instruction *inst : lv.getAllLiveValues())
reg2Mem(valToAlloca, allocaToVal, inst);
// printFunction("AfterReg2Mem");
uint64_t baseOffsetInBytes = offsetInBytes;
uint64_t maxOffsetInBytes = offsetInBytes;
for (size_t i = 0; i < m_callSites.size(); ++i) {
offsetInBytes = baseOffsetInBytes;
const InstructionSetVector &liveHere = lv.getLiveValues(i);
std::vector<Instruction *> workList(liveHere.begin(), liveHere.end());
std::set<Instruction *> visited;
Rematerializer R(allocaToVal, liveHere, *m_resources);
Instruction *saveInsertBefore = m_callSites[i];
Instruction *restoreInsertBefore = getInstructionAfter(m_callSites[i]);
Instruction *rematInsertBefore = nullptr; // create only if needed
// Rematerialize stack offsets after the continuation before other restores
for (Instruction *inst : stackOffsets) {
visited.insert(inst);
Instruction *remat = R.rematerialize(inst, workList, restoreInsertBefore);
new StoreInst(remat, valToAlloca[inst], restoreInsertBefore);
}
Instruction *saveStackFrameOffset = new LoadInst(
valToAlloca[m_stackFrameOffset], "stackFrame.offset", saveInsertBefore);
Instruction *restoreStackFrameOffset =
R.getRematerializedValueFor(m_stackFrameOffset);
while (!workList.empty()) {
Instruction *inst = workList.back();
workList.pop_back();
if (!visited.insert(inst).second)
continue;
if (!R.canRematerialize(inst)) {
assert(!inst->getType()->isPointerTy() && "Can not save pointers");
offsetInBytes = align(offsetInBytes, inst, DL);
AllocaInst *alloca = valToAlloca[inst];
Value *saveVal = new LoadInst(
alloca, addSuffix(inst->getName(), ".save"), saveInsertBefore);
createStackStore(saveStackFrameOffset, saveVal, offsetInBytes,
saveInsertBefore);
Value *restoreVal = createStackLoad(restoreStackFrameOffset, inst,
offsetInBytes, restoreInsertBefore);
new StoreInst(restoreVal, alloca, restoreInsertBefore);
offsetInBytes += DL.getTypeAllocSize(inst->getType());
} else if (R.getRematerializedValueFor(inst) == nullptr) {
if (!rematInsertBefore) {
// Create a new block after restores for rematerialized values. This
// ensures that we can use restored values (through their allocas)
// even if we haven't generated the actual restore yet.
rematInsertBefore =
restoreInsertBefore->getParent()
->splitBasicBlock(restoreInsertBefore, "remat_begin")
->begin();
restoreInsertBefore = m_callSites[i]->getParent()->getTerminator();
}
Instruction *remat = R.rematerialize(inst, workList, rematInsertBefore);
new StoreInst(remat, valToAlloca[inst], rematInsertBefore);
}
}
// Take the max offset over all call sites
maxOffsetInBytes = std::max(maxOffsetInBytes, offsetInBytes);
}
// ... traceFrame (if any)
maxOffsetInBytes += m_traceFrameSizeInBytes;
// Set the stack size
rewriteDummyStackSize(maxOffsetInBytes);
shaderStackSize = maxOffsetInBytes;
}
void StateFunctionTransform::createSubstateFunctions(
std::vector<Function *> &stateFunctions) {
// The runtime perf of split() depends on the number of blocks in the
// function. Simplifying the CFG before the split helps reduce the cost of
// that operation.
runPasses(m_function, {createCFGSimplificationPass()});
stateFunctions.resize(m_callSites.size() + 1);
BasicBlockVector substateEntryBlocks = replaceCallSites();
for (size_t i = 0, e = stateFunctions.size(); i < e; ++i) {
stateFunctions[i] = split(m_function, substateEntryBlocks[i], i);
// Add an attribute so we can detect when an intrinsic is not being called
// from a state function, and thus doesn't have access to the runtimeData
// pointer.
stateFunctions[i]->addFnAttr("state_function", "true");
}
// Erase base function
m_function->eraseFromParent();
m_function = nullptr;
}
void StateFunctionTransform::allocateStackFrame() {
Module *mod = m_function->getParent();
// Push stack frame in entry block.
Instruction *insertBefore = m_stackFrameOffset;
Function *stackFramePushFunc = FunctionBuilder(mod, "stackFramePush")
.voidTy()
.type(m_runtimeDataArgTy, "runtimeData")
.i32("size")
.build();
m_stackFramePush = CallInst::Create(stackFramePushFunc,
{m_runtimeDataArg, m_stackFrameSizeVal},
"", insertBefore);
// Pop the stack frame just before returns.
Function *stackFramePop = FunctionBuilder(mod, "stackFramePop")
.voidTy()
.type(m_runtimeDataArgTy, "runtimeData")
.i32("size")
.build();
for (Instruction *insertBefore : m_returns)
CallInst::Create(stackFramePop, {m_runtimeDataArg, m_stackFrameSizeVal}, "",
insertBefore);
}
void StateFunctionTransform::allocateTraceFrame() {
assert(m_attributeSizeInBytes >= 0 &&
"Attribute size has not been specified");
m_traceFrameSizeInBytes =
2 * m_attributeSizeInBytes // committed and pending attributes
+ 2 * sizeof(int); // old committed/pending attribute offsets
int attrSizeInInts = m_attributeSizeInBytes / sizeof(int);
// Push the trace frame first thing so that the runtime
// can do setup relative to the entry stack offset.
Module *mod = m_function->getParent();
Instruction *insertBefore = afterEntryBlockAllocas(m_function);
Value *attrSize = makeInt32(attrSizeInInts, mod->getContext());
Function *traceFramePushFunc = FunctionBuilder(mod, "traceFramePush")
.voidTy()
.type(m_runtimeDataArgTy, "runtimeData")
.i32("attrSize")
.build();
CallInst::Create(traceFramePushFunc, {m_runtimeDataArg, attrSize}, "",
insertBefore);
// Pop the trace frame just before returns.
Function *traceFramePopFunc = FunctionBuilder(mod, "traceFramePop")
.voidTy()
.type(m_runtimeDataArgTy, "runtimeData")
.build();
for (Instruction *insertBefore : m_returns)
CallInst::Create(traceFramePopFunc, {m_runtimeDataArg}, "", insertBefore);
}
bool isTemporaryAlloca(Value *op) {
// TODO: Need to some analysis to figure this out. We can put the alloca on
// the caller stack if:
// there is only a single callsite OR
// if no callsite between stores/loads and this callsite
return true;
}
void StateFunctionTransform::createArgFrames() {
Module *mod = m_function->getParent();
DataLayout DL(mod);
Instruction *stackAllocaInsertBefore =
getInstructionAfter(m_stackFrameOffset);
// Retrieve this function's arguments from the stack
if (m_function->getFunctionType()->getNumParams() > 0) {
if (m_paramTypes.empty())
m_paramTypes.assign(m_function->getFunctionType()->getNumParams(),
PST_NONE); // assume standard argument types
static_assert(PST_COUNT == 3, "Expected 3 parameter semantic types");
int offsetInBytes[PST_COUNT] = {0, 0, 0};
Value *baseOffset[PST_COUNT] = {nullptr, nullptr, nullptr};
Instruction *insertBefore = stackAllocaInsertBefore;
for (auto pst : m_paramTypes) {
if (baseOffset[pst])
continue;
if (pst == PST_NONE) {
baseOffset[pst] = BinaryOperator::Create(
Instruction::Add, m_stackFrameOffset, m_stackFrameSizeVal,
"callerArgFrame.offset", insertBefore);
offsetInBytes[pst] = sizeof(
int); // skip the first element in caller arg frame (returnStateID)
} else if (pst == PST_PAYLOAD) {
baseOffset[pst] = m_payloadOffset;
} else if (pst == PST_ATTRIBUTE) {
baseOffset[pst] =
(m_useCommittedAttr) ? m_committedAttrOffset : m_pendingAttrOffset;
} else {
assert(0 && "Bad parameter type");
}
}
int argIdx = 0;
for (auto &arg : m_function->args()) {
ParameterSemanticType pst = m_paramTypes[argIdx];
Value *val = nullptr;
if (arg.getType()->isPointerTy()) {
// Assume that pointed to memory is on the stack.
val = createStackPtr(baseOffset[pst], &arg, offsetInBytes[pst],
insertBefore);
offsetInBytes[pst] +=
DL.getTypeAllocSize(arg.getType()->getPointerElementType());
} else {
val = createStackLoad(baseOffset[pst], &arg, offsetInBytes[pst],
insertBefore);
offsetInBytes[pst] += DL.getTypeAllocSize(arg.getType());
}
// Replace use of the argument with the loaded value
if (arg.hasName())
val->takeName(&arg);
else
val->setName("arg" + std::to_string(argIdx));
arg.replaceAllUsesWith(val);
argIdx++;
}
}
// Process function arguments for each call site
m_maxCallerArgFrameSizeInBytes = 0;
for (size_t i = 0; i < m_callSites.size(); ++i) {
int offsetInBytes = 0;
CallInst *call = m_callSites[i];
FunctionType *FT = call->getCalledFunction()->getFunctionType();
StringRef calledFuncName = call->getCalledFunction()->getName();
Instruction *insertBefore = call;
// Set the return stateId (next substate of this function)
int nextSubstate = i + 1;
Value *nextStateId =
getDummyStateId(m_functionIdx, nextSubstate, insertBefore);
createStackStore(m_stackFrameOffset, nextStateId, offsetInBytes,
insertBefore);
offsetInBytes += DL.getTypeAllocSize(nextStateId->getType());
if (FT->getNumParams() && calledFuncName != CALL_INDIRECT_NAME) {
for (unsigned index = 0; index < FT->getNumParams(); ++index) {
// Save the argument from the argFrame
Value *op = call->getArgOperand(index);
Type *opTy = op->getType();
if (opTy->isPointerTy()) {
// TODO: Until we have callable shaders we should not get here except
// in tests.
if (isTemporaryAlloca(op)) {
// We can just replace the alloca with space in the arg frame
assert(isa<AllocaInst>(op));
Value *stackAlloca = createStackPtr(
m_stackFrameOffset, op, offsetInBytes, stackAllocaInsertBefore);
op->replaceAllUsesWith(stackAlloca);
cast<AllocaInst>(op)->eraseFromParent();
} else {
// copy in/out
assert(0);
}
offsetInBytes += DL.getTypeAllocSize(opTy->getPointerElementType());
} else {
createStackStore(m_stackFrameOffset, op, offsetInBytes, insertBefore);
offsetInBytes += DL.getTypeAllocSize(opTy);
}
// Replace use of the argument with undef
call->setArgOperand(index, UndefValue::get(opTy));
}
}
if (offsetInBytes > m_maxCallerArgFrameSizeInBytes)
m_maxCallerArgFrameSizeInBytes = offsetInBytes;
}
}
void StateFunctionTransform::changeFunctionSignature() {
// Create a new function that takes a state object pointer and returns next
// state ID and splice in the body of the old function into the new one.
Function *newFunc =
FunctionBuilder(m_function->getParent(), m_functionName + "_tmp")
.i32()
.type(m_runtimeDataArgTy, "runtimeData")
.build();
newFunc->getBasicBlockList().splice(newFunc->begin(),
m_function->getBasicBlockList());
m_function = newFunc;
// Set the runtime data pointer and remove the dummy function .
Value *runtimeDataArg = m_function->arg_begin();
replaceValAndRemoveUnusedDummyFunc(m_runtimeDataArg, runtimeDataArg,
m_function);
m_runtimeDataArg = runtimeDataArg;
// Get return stateID from stack on each return.
LLVMContext &context = m_function->getContext();
Value *zero = makeInt32(0, context);
CallInst *retStackFrameOffset = m_stackFrameOffset;
for (ReturnInst *&ret : m_returns) {
Instruction *insertBefore = ret;
if (m_stackFramePush)
retStackFrameOffset = CallInst::Create(
m_stackFrameOffset->getCalledFunction(), {m_runtimeDataArg},
"ret.stackFrame.offset", insertBefore);
Instruction *returnStateIdPtr = CallInst::Create(
m_stackIntPtrFunc, {m_runtimeDataArg, retStackFrameOffset, zero},
"ret.stateId.ptr", insertBefore);
Value *returnStateId =
new LoadInst(returnStateIdPtr, "ret.stateId", insertBefore);
ReturnInst *newRet = ReturnInst::Create(context, returnStateId);
ReplaceInstWithInst(ret, newRet);
ret = newRet; // update reference
}
}
void StateFunctionTransform::rewriteDummyStackSize(uint64_t frameSizeInBytes) {
assert(frameSizeInBytes % sizeof(int) == 0);
Value *frameSizeVal =
makeInt32(frameSizeInBytes / sizeof(int), m_function->getContext());
replaceValAndRemoveUnusedDummyFunc(m_stackFrameSizeVal, frameSizeVal,
m_function);
m_stackFrameSizeVal = frameSizeVal;
}
void StateFunctionTransform::createStackStore(Value *baseOffset, Value *val,
int offsetInBytes,
Instruction *insertBefore) {
assert(offsetInBytes % sizeof(int) == 0);
Value *intIndex =
makeInt32(offsetInBytes / sizeof(int), insertBefore->getContext());
Value *args[] = {val, baseOffset, intIndex};
Type *argTypes[] = {args[0]->getType(), args[1]->getType(),
args[2]->getType()};
FunctionType *FT =
FunctionType::get(Type::getVoidTy(val->getContext()), argTypes, false);
Function *F = getOrCreateFunction("stack.store", insertBefore->getModule(),
FT, m_stackStoreFuncs);
CallInst::Create(F, args, "", insertBefore);
}
Instruction *
StateFunctionTransform::createStackLoad(Value *baseOffset, Value *val,
int offsetInBytes,
Instruction *insertBefore) {
assert(offsetInBytes % sizeof(int) == 0);
Value *intIndex =
makeInt32(offsetInBytes / sizeof(int), insertBefore->getContext());
Value *args[] = {baseOffset, intIndex};
Type *argTypes[] = {args[0]->getType(), args[1]->getType()};
FunctionType *FT = FunctionType::get(val->getType(), argTypes, false);
Function *F = getOrCreateFunction("stack.load", insertBefore->getModule(), FT,
m_stackLoadFuncs);
return CallInst::Create(F, args, addSuffix(val->getName(), ".restore"),
insertBefore);
}
Instruction *StateFunctionTransform::createStackPtr(Value *baseOffset,
Type *valTy,
Value *intIndex,
Instruction *insertBefore) {
Value *args[] = {baseOffset, intIndex};
Type *argTypes[] = {args[0]->getType(), args[1]->getType()};
FunctionType *FT = FunctionType::get(valTy, argTypes, false);
Function *F = getOrCreateFunction("stack.ptr", insertBefore->getModule(), FT,
m_stackPtrFuncs);
CallInst *call = CallInst::Create(F, args, "", insertBefore);
return call;
}
Instruction *StateFunctionTransform::createStackPtr(Value *baseOffset,
Value *val,
int offsetInBytes,
Instruction *insertBefore) {
assert(offsetInBytes % sizeof(int) == 0);
Value *intIndex =
makeInt32(offsetInBytes / sizeof(int), insertBefore->getContext());
Instruction *ptr =
createStackPtr(baseOffset, val->getType(), intIndex, insertBefore);
ptr->takeName(val);
return ptr;
}
static bool isStackIntPtr(Value *val) {
CallInst *call = dyn_cast<CallInst>(val);
return call && call->getCalledFunction()->getName().startswith("stack.ptr");
}
// This code adapted from GetElementPtrInst::accumulateConstantOffset().
// TODO: Use a single function for both constant and dynamic offsets? Could do
// some constant folding along the way for dynamic offsets.
Value *accumulateDynamicOffset(GetElementPtrInst *gep, const DataLayout &DL) {
LLVMContext &C = gep->getContext();
Instruction *insertBefore = gep;
Value *offset = makeInt32(0, C);
for (gep_type_iterator GTI = gep_type_begin(gep), GTE = gep_type_end(gep);
GTI != GTE; ++GTI) {
ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
if (OpC && OpC->isZero())
continue;
// Handle a struct index, which adds its field offset to the pointer.
Value *elementOffset = nullptr;
if (StructType *STy = dyn_cast<StructType>(*GTI)) {
assert(OpC && "Structure indices must be constant");
unsigned ElementIdx = OpC->getZExtValue();
const StructLayout *SL = DL.getStructLayout(STy);
elementOffset =
makeInt32(SL->getElementOffset(ElementIdx) / sizeof(int), C);
} else {
// For array or vector indices, scale the index by the size of the type.
Value *stride =
makeInt32(DL.getTypeAllocSize(GTI.getIndexedType()) / sizeof(int), C);
elementOffset = BinaryOperator::Create(Instruction::Mul, GTI.getOperand(),
stride, "elOffs", insertBefore);
}
offset = BinaryOperator::Create(Instruction::Add, offset, elementOffset,
"offs", insertBefore);
}
return offset;
}
// Adds gep offset to offsetVal and returns the result
static Value *accumulateGepOffset(GetElementPtrInst *gep, Value *offsetVal) {
Module *M = gep->getModule();
const DataLayout &DL = M->getDataLayout();
Value *elementOffsetVal = nullptr;
APInt constOffset(DL.getPointerSizeInBits(), 0);
if (gep->accumulateConstantOffset(DL, constOffset))
elementOffsetVal = makeInt32((int)constOffset.getZExtValue() / sizeof(int),
M->getContext());
else
elementOffsetVal = accumulateDynamicOffset(gep, DL);
elementOffsetVal = BinaryOperator::Create(Instruction::Add, offsetVal,
elementOffsetVal, "offs", gep);
return elementOffsetVal;
}
// Turn GEPs on a stack.ptr of aggregate type into stack.ptrs of scalar type
void StateFunctionTransform::flattenGepsOnValue(Value *val, Value *baseOffset,
Value *offsetVal) {
for (auto U = val->user_begin(), UE = val->user_end(); U != UE;) {
User *user = *U++;
if (CallInst *call = dyn_cast<CallInst>(user)) {
// inline the call to expose GEPs and restart the loop.
InlineFunctionInfo IFI;
bool success = InlineFunction(call, IFI, false);
assert(success);
(void)success;
U = val->user_begin();
UE = val->user_end();
continue;
}
GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(user);
if (!gep)
continue;
Value *elementOffsetVal = accumulateGepOffset(gep, offsetVal);
Type *gepElTy = gep->getType()->getPointerElementType();
if (gepElTy->isAggregateType()) {
// flatten geps on this gep
flattenGepsOnValue(gep, baseOffset, elementOffsetVal);
} else if (isa<VectorType>(gepElTy))
scalarizeVectorStackAccess(gep, baseOffset, elementOffsetVal);
else {
Value *ptr =
createStackPtr(baseOffset, gep->getType(), elementOffsetVal, gep);
ptr->takeName(
gep); // could use a name that encodes the gep type and indices
gep->replaceAllUsesWith(ptr);
}
gep->eraseFromParent();
}
}
void StateFunctionTransform::scalarizeVectorStackAccess(Instruction *vecPtr,
Value *baseOffset,
Value *offsetVal) {
std::vector<Value *> elPtrs;
Type *VTy = vecPtr->getType()->getPointerElementType();
Type *elTy = VTy->getVectorElementType();
LLVMContext &C = vecPtr->getContext();
Value *curOffsetVal = offsetVal;
Value *one = makeInt32(1, C);
offsetVal->setName("offs0.");
for (unsigned i = 0; i < VTy->getVectorNumElements(); ++i) {
// TODO: If offsetVal is a constant we could just create constants instead
// of add instructions
if (i > 0)
curOffsetVal = BinaryOperator::Create(Instruction::Add, curOffsetVal, one,
stringf("offs%d.", i), vecPtr);
elPtrs.push_back(
createStackPtr(baseOffset, elTy->getPointerTo(), curOffsetVal, vecPtr));
elPtrs.back()->setName(addSuffix(vecPtr->getName(), stringf(".el%d.", i)));
}
// Scalarize load/stores
for (auto U = vecPtr->user_begin(), UE = vecPtr->user_end(); U != UE;) {
User *user = *U++;
if (LoadInst *load = dyn_cast<LoadInst>(user)) {
Value *vec = UndefValue::get(VTy);
for (size_t i = 0; i < elPtrs.size(); ++i) {
Value *el = new LoadInst(elPtrs[i], stringf("el%d.", i), load);
vec = InsertElementInst::Create(vec, el, makeInt32(i, C), "vec", load);
}
load->replaceAllUsesWith(vec);
load->eraseFromParent();
} else if (StoreInst *store = dyn_cast<StoreInst>(user)) {
Value *vec = store->getOperand(0);
for (size_t i = 0; i < elPtrs.size(); ++i) {
Value *el = ExtractElementInst::Create(vec, makeInt32(i, C),
stringf("el%d.", i), store);
new StoreInst(el, elPtrs[i], store);
}
store->eraseFromParent();
} else {
assert(0 && "Unhandled user");
}
}
}
void StateFunctionTransform::lowerStackFuncs() {
LLVMContext &C = m_stackIntPtrFunc->getContext();
const DataLayout &DL = m_stackIntPtrFunc->getParent()->getDataLayout();
// stack.store functions
for (auto &kv : m_stackStoreFuncs) {
Function *F = kv.second;
for (auto U = F->user_begin(); U != F->user_end();) {
CallInst *call = dyn_cast<CallInst>(*(U++));
assert(call);
Value *runtimeDataArg = call->getParent()->getParent()->arg_begin();
Value *val = call->getArgOperand(0);
Value *offset = call->getArgOperand(1);
int idx = getConstantValue(call->getArgOperand(2));
Instruction *insertBefore = call;
if (isStackIntPtr(val)) {
// Copy from one part of the stack to another
CallInst *valCall = dyn_cast<CallInst>(val);
Value *srcOffset = valCall->getArgOperand(0);
int srcIdx = getConstantValue(valCall->getArgOperand(1));
Value *dstOffset = offset;
int dstIdx = idx;
int intCount =
(int)DL.getTypeAllocSize(val->getType()->getPointerElementType()) /
sizeof(int);
for (int i = 0; i < intCount; ++i) {
std::string idxStr = stringf("%d.", i);
Value *srcPtr = CallInst::Create(
m_stackIntPtrFunc,
{runtimeDataArg, srcOffset, makeInt32(srcIdx + i, C)},
addSuffix(val->getName(), ".ptr" + idxStr), insertBefore);
Value *dstPtr = CallInst::Create(
m_stackIntPtrFunc,
{runtimeDataArg, dstOffset, makeInt32(dstIdx + i, C)},
"dst.ptr" + idxStr, insertBefore);
Value *intVal =
new LoadInst(srcPtr, "copy.val" + idxStr, insertBefore);
new StoreInst(intVal, dstPtr, insertBefore);
}
} else {
store(val, m_stackIntPtrFunc, runtimeDataArg, offset, idx,
insertBefore);
}
call->eraseFromParent();
}
F->eraseFromParent();
}
// stack.load functions
for (auto &kv : m_stackLoadFuncs) {
Function *F = kv.second;
for (auto U = F->user_begin(); U != F->user_end();) {
CallInst *call = dyn_cast<CallInst>(*(U++));
assert(call);
std::string name = stripSuffix(call->getName(), ".restore");
call->setName("");
Value *runtimeDataArg = call->getParent()->getParent()->arg_begin();
Value *offset = call->getArgOperand(0);
Value *idx = call->getArgOperand(1);
Instruction *insertBefore = call;
Value *val = load(m_stackIntPtrFunc, runtimeDataArg, offset, idx, name,
call->getType(), insertBefore);
call->replaceAllUsesWith(val);
call->eraseFromParent();
}
F->eraseFromParent();
}
// Scalarize accesses based on a stack.ptr func
for (auto &kv : m_stackPtrFuncs) {
Function *F = kv.second;
if (!F->getReturnType()->getPointerElementType()->isAggregateType())
continue;
for (auto U = F->user_begin(), UE = F->user_end(); U != UE;) {
CallInst *call = dyn_cast<CallInst>(*(U++));
assert(call);
Value *offset = call->getArgOperand(0);
Value *idx = call->getArgOperand(1);
flattenGepsOnValue(call, offset, idx);
call->eraseFromParent();
}
}
// stack.ptr functions
for (auto &kv : m_stackPtrFuncs) {
Function *F = kv.second;
for (auto U = F->user_begin(); U != F->user_end();) {
CallInst *call = dyn_cast<CallInst>(*(U++));
assert(call);
std::string name = call->getName();
Value *runtimeDataArg = call->getParent()->getParent()->arg_begin();
Value *offset = call->getArgOperand(0);
Value *idx = call->getArgOperand(1);
Instruction *insertBefore = call;
Value *ptr =
CallInst::Create(m_stackIntPtrFunc, {runtimeDataArg, offset, idx},
addSuffix(name, ".ptr"), insertBefore);
if (ptr->getType() != call->getType())
ptr = new BitCastInst(ptr, call->getType(), "", insertBefore);
ptr->takeName(call);
call->replaceAllUsesWith(ptr);
call->eraseFromParent();
}
F->eraseFromParent();
}
}
Function *StateFunctionTransform::split(Function *baseFunc,
BasicBlock *substateEntryBlock,
int substateIndex) {
ValueToValueMapTy VMap;
Function *substateFunc = cloneBlocksReachableFrom(substateEntryBlock, VMap);
Module *mod = baseFunc->getParent();
mod->getFunctionList().push_back(substateFunc);
substateFunc->setName(m_functionName + ".ss_" +
std::to_string(substateIndex));
if (substateIndex != 0) {
// Collect allocas from entry block
SmallVector<Instruction *, 16> allocasToClone;
for (auto &I : baseFunc->getEntryBlock().getInstList()) {
if (isa<AllocaInst>(&I))
allocasToClone.push_back(&I);
}
// Clone collected allocas
BasicBlock *newEntryBlock = &substateFunc->getEntryBlock();
for (auto I : allocasToClone) {
// Collect users of original instruction in substateFunc
std::vector<Instruction *> users;
for (auto U : I->users()) {
Instruction *inst = dyn_cast<Instruction>(U);
if (inst->getParent()->getParent() == substateFunc)
users.push_back(inst);
}
if (users.empty())
continue;
// Clone instruction
Instruction *clone = I->clone();
if (I->hasName())
clone->setName(I->getName());
clone->insertBefore(
newEntryBlock->getFirstInsertionPt()); // allocas first in entry block
RemapInstruction(clone, VMap,
RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
// Replaces uses
for (auto user : users)
user->replaceUsesOfWith(I, clone);
}
}
// printFunction( substateFunc, substateFunc->getName().str() +
// "-BeforeSplittingOpt", m_dumpId++ );
makeReducible(substateFunc);
// Undo the reg2mem done in preserveLiveValuesAcrossCallSites()
runPasses(substateFunc,
{createVerifierPass(), createPromoteMemoryToRegisterPass()});
// printFunction( substateFunc, substateFunc->getName().str() +
// "-AfterSplitting", m_dumpId++ );
return substateFunc;
}
BasicBlockVector StateFunctionTransform::replaceCallSites() {
LLVMContext &context = m_function->getContext();
BasicBlockVector substateEntryPoints{&m_function->getEntryBlock()};
substateEntryPoints[0]->setName(m_functionName + ".BB0");
// Add other substates by splitting blocks at call sites.
for (size_t i = 0; i < m_callSites.size(); ++i) {
CallInst *call = m_callSites[i];
BasicBlock *block = call->getParent();
StringRef calledFuncName = call->getCalledFunction()->getName();
BasicBlock *nextBlock = block->splitBasicBlock(
call->getNextNode(), m_functionName + ".BB" + std::to_string(i + 1) +
".from." + cleanName(calledFuncName));
substateEntryPoints.push_back(nextBlock);
// Return state id for entry state of the function being called
Instruction *insertBefore = call;
Value *returnStateId = nullptr;
if (calledFuncName == CALL_INDIRECT_NAME)
returnStateId = call->getArgOperand(0);
else
returnStateId =
getDummyStateId(m_callSiteFunctionIdx[i], 0, insertBefore);
ReplaceInstWithInst(call->getParent()->getTerminator(),
ReturnInst::Create(context, returnStateId));
call->eraseFromParent();
}
return substateEntryPoints;
}
llvm::Value *
StateFunctionTransform::getDummyStateId(int functionIdx, int substate,
llvm::Instruction *insertBefore) {
if (!m_dummyStateIdFunc) {
Module *M = m_function->getParent();
m_dummyStateIdFunc = FunctionBuilder(M, "dummyStateId")
.i32()
.i32("functionIdx")
.i32("substate")
.build();
}
LLVMContext &context = insertBefore->getContext();
Value *functionIdxVal = makeInt32(functionIdx, context);
Value *substateVal = makeInt32(substate, context);
return CallInst::Create(m_dummyStateIdFunc, {functionIdxVal, substateVal},
"stateId", insertBefore);
}
raw_ostream &
StateFunctionTransform::getOutputStream(const std::string functionName,
const std::string &suffix,
unsigned int dumpId) {
if (m_dumpFilename.empty())
return DBGS();
const std::string filename =
createDumpPath(m_dumpFilename, dumpId, suffix, functionName);
std::error_code errorCode;
raw_ostream *out =
new raw_fd_ostream(filename, errorCode, sys::fs::OpenFlags::F_None);
if (errorCode) {
DBGS() << "Failed to open " << filename << " for writing sft output. "
<< errorCode.message() << "\n";
delete out;
return DBGS();
}
return *out;
}
void StateFunctionTransform::printFunction(const Function *function,
const std::string &suffix,
unsigned int dumpId) {
if (!m_verbose)
return;
raw_ostream &out = getOutputStream(m_functionName, suffix, dumpId);
out << "; ########################### " << suffix << "\n";
out << *function << "\n";
if (&out != &DBGS())
delete &out;
}
void StateFunctionTransform::printFunction(const std::string &suffix) {
printFunction(m_function, suffix, m_dumpId++);
}
void StateFunctionTransform::printFunctions(
const std::vector<Function *> &funcs, const char *suffix) {
if (!m_verbose)
return;
raw_ostream &out = getOutputStream(m_functionName, suffix, m_dumpId++);
out << "; ########################### " << suffix << "\n";
for (Function *F : funcs)
out << *F << "\n";
if (&out != &DBGS())
delete &out;
}
void StateFunctionTransform::printModule(const Module *mod,
const std::string &suffix) {
if (!m_verbose)
return;
raw_ostream &out = getOutputStream("module", suffix, m_dumpId++);
out << "; ########################### " << suffix << "\n";
out << *mod << "\n";
}
void StateFunctionTransform::printSet(const InstructionSetVector &vals,
const char *msg) {
if (!m_verbose)
return;
raw_ostream &out = DBGS();
if (msg)
out << msg << " --------------------\n";
uint64_t totalBytes = 0;
if (vals.size() > 0) {
Module *mod = m_function->getParent();
DataLayout DL(mod);
for (InstructionSetVector::const_iterator I = vals.begin(), IE = vals.end();
I != IE; ++I) {
const Instruction *inst = *I;
uint64_t size = DL.getTypeAllocSize(inst->getType());
out << stringf("%3dB: ", size) << *inst << '\n';
totalBytes += size;
}
}
out << "Count:" << vals.size() << " Bytes:" << totalBytes << "\n\n";
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxrFallback/StateFunctionTransform.h | #pragma once
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SetVector.h"
#include <map>
#include <string>
#include <vector>
namespace llvm {
class AllocaInst;
class BasicBlock;
class CallInst;
class Function;
class FunctionType;
class Instruction;
class Module;
class raw_ostream;
class ReturnInst;
class StructType;
class Type;
class Value;
} // namespace llvm
class LiveValues;
typedef std::vector<llvm::BasicBlock *> BasicBlockVector;
typedef llvm::SetVector<llvm::Instruction *> InstructionSetVector;
//==============================================================================
// Transforms the given function into a number of state functions to be
// used in a state machine.
//
// State functions have the following signature:
// int (<RuntimeDataTy> runtimeData).
// They take an runtime data argument with a given type used by the runtime and
// return the state ID of the next state. If the function contains calls to
// other candidate functions that are to be transformed into state functions,
// the function is split into multiple substate functions at call sites and the
// calls are replaced with continuations. For example candidate funcA() calling
// candidate funcB():
// void funcA(int param0)
// {
// // code moved to funcA_ss0()
// int foo = 10;
// ...
//
// funcB(arg0, arg1);
//
// // code moved to funcA_ss1()
// int bar = someFunc(foo);
//
// }
// will be split into two substate functions, funcA_ss0() and funcA_ss1().
// funcA_ss0() pushes the stateID for funcA_ss1() onto the stack, and
// returns the state ID for the entry substate of funcB, funcB_ss0().
// A substate of funcB will eventually pop the stack and return the state ID
// for funcA_ss1(). funcA_ss1() in turn pops the stack to get the state ID
// placed there by its caller.
//
// If candidate functions, like funcB(), have arguments they are moved to the
// stack. Any values that are live across continuations, like foo in this
// example, must also be saved to the stack before the continuation and restored
// before use. Some values, like DXIL buffer handles should not be saved and
// must be rematerialized after a continuation. The stack frame in a state
// function has the following layout:
//
// | |
// +---------------+
// | argN |
// | ... |
// | arg0 |
// | returnStateID | caller arg frame
// +---------------+ <-- entry stack pointer
// | |
// | saved values |
// | |
// +---------------+
// | argN |
// | ... |
// | arg0 |
// | returnStateID | callee arg frame
// +---------------+ <-- stack frame pointer
// |
// V stack grows downward towards smaller addresses
//
// The return state ID is stored at the base of the argument frame, followed by
// function arguments, if any. The saved values follow the argument frame.
// Instead of adjusting the size of the stack frame for the saved values and
// argument frames of each continuation a single allocation is made with enough
// space to accommodate all continuations in the function.
//
// Several placeholder functions are used during the process of the state
// function transform to break dependency cycles. A placeholder for the runtime
// data pointer is used to allocate the stack frame before the function
// signature is changed and the pointer parameter is created. The stack frame is
// also allocated before its size has been determined, so a placeholder is used.
// The state IDs corresponding to function entry substates may also not be known
// before the transform has been run on all the candidate functions. Therefore a
// placeholder is used for state IDs as well. These are replaced by calling
// StateFunctionTransform::finalizeStateIds() after all the candidate functions
// have been transformed.
//
// If the intrinsic Internal_CallIndirect(int stateId) appears in the body of
// the function then it is treated as a continuation with a transition to the
// specified stateId.
//
// When an attribute size is specified, space is allocated on the stack frame
// for committed/pending attributes, as well as the previous offsets for the
// committed/ pending attributes. The attribute size should be set if the
// function is TraceRay(). The payload offset needs to be set by the caller. The
// stack frame for TraceRay() has the following layout:
//
// | |
// +-------------------------+
// | |
// | TraceRay() args |
// | |
// +-------------------------+
// | returnStateID | caller arg frame
// +-------------------------+ <-- entry stack offset
// | old committed attr offs |
// | old pending attr offset |
// +-------------------------+
// | |
// | committed attributes |
// | |
// +-------------------------+ <-- new committed attribute offset
// | |
// | pending attributes |
// | |
// +-------------------------+ <-- new pending attribute offset
// | |
// | saved values |
// | |
// +-------------------------+
// | argN |
// | ... |
// | arg0 |
// | returnStateID | callee arg frame
// +-------------------------+ <-- stack frame offset
//
// The arguments to some functions (e.g. closesthit, anyhit, and miss shaders)
// come from the payload or attributes. The positions of these arguments can be
// specified to SFT, which will redirect the defs from the args to corresponding
// values on the stack.
//
// The following runtime (LLVM) functions are used by SFT (all sizes and offsets
// are in terms of ints):
// void stackFramePush(<RuntimeDataTy> runtimeData, i32 size)
// void stackFramePop(<RuntimeDataTy> runtimeData, i32 size)
//
// i32 stackFrameOffset(<RuntimeDataTy> runtimeData)
// i32 payloadOffset(<RuntimeDataTy> runtimeData)
// i32 committedAttrOffset(<RuntimeDataTy> runtimeData)
// i32 pendingAttrOffset(<RuntimeDataTy> runtimeData)
//
// i32* stackIntPtr(<RuntimeDataTy> runtimeData, i32 baseOffset, i32 offset)
//
// Called before/after stackFramePush()/stackFramePop():
// void traceFramePush(<RuntimeDataTy> runtimeData, i32 attrSize)
// void traceFramePop(<RuntimeDataTy> runtimeData)
class StateFunctionTransform {
public:
enum ParameterSemanticType {
PST_NONE = 0,
PST_PAYLOAD,
PST_ATTRIBUTE,
PST_COUNT
};
// func is the function to be transformed. candidateFuncNames is a list of all
// functions that which have been or will be transformed to state functions,
// including func. The runtimeDataArgTy is the type to use for the first
// argument in state functions.
StateFunctionTransform(llvm::Function *func,
const std::vector<std::string> &candidateFuncNames,
llvm::Type *runtimeDataArgTy);
// Optional parameters to be specified before run()
void setAttributeSize(int sizeInBytes); // needed for TraceRay()
void setParameterInfo(const std::vector<ParameterSemanticType> ¶mTypes,
bool useCommittedAttr = true);
void setResourceGlobals(const std::set<llvm::Value *> &resources);
static llvm::Function *
createDummyRuntimeDataArgFunc(llvm::Module *M, llvm::Type *runtimeDataArgTy);
// Generates state functions from func into the same module. The original
// function is left only as a declaration.
void run(std::vector<llvm::Function *> &stateFunctions,
unsigned int &shaderStackSize);
// candidateFuncEntryStateIds corresponding to the candidateFuncNames passed
// to the constructor. stateIDs are computed as
// candidateFuncEntryStateIds[functionIdx]
// + substateIdx, where functionIdx and substateIdx come from the arguments to
// the placeholder stateID function.
static void
finalizeStateIds(llvm::Module *module,
const std::vector<int> &candidateFuncEntryStateIds);
// Outputs detailed diagnostic information if set to true.
void setVerbose(bool val);
void setDumpFilename(const std::string &dumpFilename);
private:
// Function to transform
llvm::Function *m_function = nullptr;
// Name of the function to transform
std::string m_functionName;
// Index of the function to transform in m_candidateFuncNames
int m_functionIdx = 0;
// cadidateFuncNames is a list of all functions that which have been or will
// be transformed to state functions. Used to create function index used
// by the stateID placeholder function.
const std::vector<std::string> &m_candidateFuncNames;
llvm::Type *m_runtimeDataArgTy = nullptr;
llvm::Value *m_runtimeDataArg =
nullptr; // set in init() and changeFunctionSignature()
llvm::Value *m_stackFrameSizeVal =
nullptr; // set in init() and preserveLiveValuesAcrossCallsites()
int m_attributeSizeInBytes = -1;
std::vector<ParameterSemanticType> m_paramTypes;
bool m_useCommittedAttr = false;
const std::set<llvm::Value *> *m_resources;
std::vector<llvm::CallInst *> m_callSites;
std::vector<int> m_callSiteFunctionIdx;
std::vector<llvm::CallInst *> m_movePayloadToStackCalls;
std::vector<llvm::CallInst *> m_setPendingAttrCalls;
std::vector<llvm::ReturnInst *> m_returns;
bool m_verbose = false;
std::string m_dumpFilename;
unsigned int m_dumpId = 0;
llvm::Function *m_stackIntPtrFunc = nullptr;
llvm::CallInst *m_stackFramePush = nullptr;
llvm::CallInst *m_stackFrameOffset = nullptr;
llvm::CallInst *m_payloadOffset = nullptr; // Offset at beginning of function
llvm::CallInst *m_committedAttrOffset =
nullptr; // Offset at beginning of function
llvm::CallInst *m_pendingAttrOffset =
nullptr; // Offset at beginning of function
// Placeholder function taking constant values functionIdx and substate.
// These are later translated to a stateId by finalizeStateIds().
llvm::Function *m_dummyStateIdFunc = nullptr;
int m_maxCallerArgFrameSizeInBytes = 0;
int m_traceFrameSizeInBytes = 0;
// Functions used to abstract stack operations. These make intermediate stages
// in the transform a little bit cleaner.
std::map<llvm::FunctionType *, llvm::Function *> m_stackStoreFuncs;
std::map<llvm::FunctionType *, llvm::Function *> m_stackLoadFuncs;
std::map<llvm::FunctionType *, llvm::Function *> m_stackPtrFuncs;
// Main stages of the transformation
void init();
void findCallSitesIntrinsicsAndReturns();
void changeCallingConvention();
void preserveLiveValuesAcrossCallsites(unsigned int &shaderStackSize);
void createSubstateFunctions(std::vector<llvm::Function *> &stateFunctions);
void lowerStackFuncs();
llvm::Value *getDummyStateId(int functionIdx, int substate,
llvm::Instruction *insertBefore);
void allocateStackFrame();
void allocateTraceFrame();
void createArgFrames();
void changeFunctionSignature();
void createStackStore(llvm::Value *baseOffset, llvm::Value *val,
int offsetInBytes, llvm::Instruction *insertBefore);
llvm::Instruction *createStackLoad(llvm::Value *baseOffset, llvm::Value *val,
int offsetInBytes,
llvm::Instruction *insertBefore);
llvm::Instruction *createStackPtr(llvm::Value *baseOffset, llvm::Value *val,
int offsetInBytes,
llvm::Instruction *insertBefore);
llvm::Instruction *createStackPtr(llvm::Value *baseOffset, llvm::Type *valTy,
llvm::Value *intIndex,
llvm::Instruction *insertBefore);
void rewriteDummyStackSize(uint64_t frameSizeInBytes);
BasicBlockVector replaceCallSites();
llvm::Function *split(llvm::Function *baseFunc,
llvm::BasicBlock *subStateEntryBlock,
int substateIndex);
void flattenGepsOnValue(llvm::Value *val, llvm::Value *baseOffset,
llvm::Value *offset);
void scalarizeVectorStackAccess(llvm::Instruction *vecPtr,
llvm::Value *baseOffset,
llvm::Value *offsetVal);
// Diagnostic printing functions
llvm::raw_ostream &getOutputStream(const std::string functionName,
const std::string &suffix,
unsigned int dumpId);
void printFunction(const llvm::Function *function, const std::string &suffix,
unsigned int dumpId);
void printFunction(const std::string &suffix);
void printFunctions(const std::vector<llvm::Function *> &funcs,
const char *suffix);
void printModule(const llvm::Module *module, const std::string &suffix);
void printSet(const InstructionSetVector &vals, const char *msg = nullptr);
};
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxrFallback/CMakeLists.txt | set(LLVM_LINK_COMPONENTS
passprinters
)
add_llvm_library(LLVMDxrFallback
DxrFallbackCompiler.cpp
FunctionBuilder.h
LiveValues.cpp
LiveValues.h
LLVMUtils.cpp
LLVMUtils.h
Reducibility.h
Reducibility.cpp
StateFunctionTransform.cpp
StateFunctionTransform.h
)
add_dependencies(LLVMDxrFallback intrinsics_gen)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxrFallback/LLVMUtils.cpp | #include "llvm/Analysis/CFGPrinter.h" // needed for DOTGraphTraits<const Function*>
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
std::vector<CallInst *> getCallsToFunction(Function *callee,
const Function *caller) {
std::vector<CallInst *> calls;
if (callee == nullptr)
return calls;
for (auto U = callee->user_begin(), UE = callee->user_end(); U != UE; ++U) {
CallInst *CI = dyn_cast<CallInst>(*U);
if (!CI) // We are not interested in uses that are not calls
continue;
assert(CI->getCalledFunction() == callee);
if (caller == nullptr || CI->getParent()->getParent() == caller)
calls.push_back(CI);
}
return calls;
}
ConstantInt *makeInt32(int val, LLVMContext &context) {
return ConstantInt::get(Type::getInt32Ty(context), val);
}
Instruction *getInstructionAfter(Instruction *inst) {
return ++BasicBlock::iterator(inst);
}
std::unique_ptr<Module> loadModuleFromAsmFile(LLVMContext &context,
const std::string &filename) {
SMDiagnostic err;
std::unique_ptr<Module> mod = parseIRFile(filename, err, context);
if (!mod) {
err.print(filename.c_str(), errs());
exit(1);
}
return mod;
}
std::unique_ptr<Module> loadModuleFromAsmString(LLVMContext &context,
const std::string &str) {
SMDiagnostic err;
MemoryBufferRef memBuffer(str, "id");
std::unique_ptr<Module> mod = parseIR(memBuffer, err, context);
return mod;
}
void saveModuleToAsmFile(const llvm::Module *mod, const std::string &filename) {
std::error_code EC;
raw_fd_ostream out(filename, EC, sys::fs::F_Text);
if (!out.has_error()) {
mod->print(out, 0);
out.close();
}
if (out.has_error()) {
errs() << "Error saving to " << filename << "\n";
exit(1);
}
}
void dumpCFG(const Function *F, const std::string &suffix) {
std::string filename = ("cfg." + F->getName() + "." + suffix + ".dot").str();
std::error_code EC;
raw_fd_ostream out(filename, EC, sys::fs::F_Text);
if (!out.has_error()) {
errs() << "Writing '" << filename << "'...\n";
WriteGraph(out, F, true, F->getName());
out.close();
}
if (out.has_error()) {
errs() << "Error saving to " << filename << "\n";
exit(1);
}
}
Function *
getOrCreateFunction(const std::string &name, Module *mod,
FunctionType *funcType,
std::map<FunctionType *, Function *> &typeToFuncMap) {
auto it = typeToFuncMap.find(funcType);
if (it != typeToFuncMap.end())
return it->second;
// Give name a numerical suffix to make it unique
std::string uniqueName = name + std::to_string(typeToFuncMap.size());
Function *F =
dyn_cast<Function>(mod->getOrInsertFunction(uniqueName, funcType));
typeToFuncMap[funcType] = F;
return F;
}
void runPasses(llvm::Function *F, const std::vector<llvm::Pass *> &passes) {
legacy::FunctionPassManager FPM(F->getParent());
for (Pass *pass : passes)
FPM.add(pass);
FPM.doInitialization();
FPM.run(*F);
FPM.doFinalization();
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxrFallback/LLVMBuild.txt | ; Copyright (C) Microsoft Corporation. All rights reserved.
; This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details.
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Library
name = DxrFallback
parent = Libraries
required_libraries = Core Support
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxrFallback/DxrFallbackCompiler.cpp | #include "dxc/DxrFallback/DxrFallbackCompiler.h"
#include "dxc/DXIL/DxilFunctionProps.h"
#include "dxc/DXIL/DxilInstructions.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/HLSL/DxilLinker.h"
#include "dxc/Support/FileIOHelper.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/Unicode.h"
#include "dxc/Support/WinIncludes.h"
#include "dxc/Support/dxcapi.impl.h"
#include "dxc/Support/dxcapi.use.h"
#include "dxc/dxcapi.h"
#include "dxc/dxcdxrfallbackcompiler.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/Linker/Linker.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "FunctionBuilder.h"
#include "LLVMUtils.h"
#include "StateFunctionTransform.h"
#include "runtime.h"
#include <queue>
using namespace hlsl;
using namespace llvm;
static std::vector<Function *>
getFunctionsWithPrefix(Module *mod, const std::string &prefix) {
std::vector<Function *> functions;
for (auto F = mod->begin(), E = mod->end(); F != E; ++F) {
StringRef name = F->getName();
if (name.startswith(prefix))
functions.push_back(F);
}
return functions;
}
static bool inlineFunc(CallInst *call, Function *Fimpl) {
// Note. LLVM inlining may not be sufficient if the function references DX
// resources because the corresponding metadata is not created if the function
// comes from another module.
// Make sure that we have a definition for the called function in this module
Function *F = call->getCalledFunction();
Module *dstM = F->getParent();
if (F->isDeclaration()) {
// Map called functions in impl module to functions in this one (because the
// cloning step doesn't do this automatically)
ValueToValueMapTy VMap;
for (auto &I : inst_range(Fimpl)) {
if (CallInst *c = dyn_cast<CallInst>(&I)) {
Function *calledFimpl = c->getCalledFunction();
if (VMap.count(calledFimpl))
continue;
Constant *calledF = dstM->getOrInsertFunction(
calledFimpl->getName(), calledFimpl->getFunctionType(),
calledFimpl->getAttributes());
VMap[calledFimpl] = calledF;
}
}
// Map arguments
for (auto SI = Fimpl->arg_begin(), SE = Fimpl->arg_end(),
DI = F->arg_begin();
SI != SE; ++SI, ++DI)
VMap[SI] = DI;
SmallVector<ReturnInst *, 4> returns;
CloneFunctionInto(F, Fimpl, VMap, true, returns);
F->setLinkage(GlobalValue::InternalLinkage);
}
InlineFunctionInfo IFI;
return InlineFunction(call, IFI, false);
}
// Remove ELF mangling
static std::string cleanName(StringRef name) {
if (!name.startswith("\x1?"))
return name;
size_t pos = name.find("@@");
if (pos == name.npos)
return name;
std::string newName = name.substr(2, pos - 2);
return newName;
}
static inline Function *getOrInsertFunction(Module *mod, Function *F) {
return dyn_cast<Function>(
mod->getOrInsertFunction(F->getName(), F->getFunctionType()));
}
template <typename K, typename V>
V get(std::map<K, V> &theMap, const K &key,
V defaultVal = static_cast<V>(nullptr)) {
auto it = theMap.find(key);
if (it == theMap.end())
return defaultVal;
else
return it->second;
}
DxrFallbackCompiler::DxrFallbackCompiler(
llvm::Module *mod, const std::vector<std::string> &shaderNames,
unsigned maxAttributeSize, unsigned stackSizeInBytes,
bool findCalledShaders /*= false*/)
: m_module(mod), m_entryShaderNames(shaderNames),
m_stackSizeInBytes(stackSizeInBytes),
m_maxAttributeSize(maxAttributeSize),
m_findCalledShaders(findCalledShaders) {}
void DxrFallbackCompiler::compile(std::vector<int> &shaderEntryStateIds,
std::vector<unsigned int> &shaderStackSizes,
IntToFuncNameMap *pCachedMap) {
std::vector<std::string> shaderNames = m_entryShaderNames;
initShaderMap(shaderNames);
// Bring in runtime so we can get the runtime data type
linkRuntime();
Type *runtimeDataArgTy = getRuntimeDataArgType();
// Make sure all calls to intrinsics and shaders are at function scope and
// fix up control flow.
lowerAnyHitControlFlowFuncs();
lowerReportHit();
lowerTraceRay(runtimeDataArgTy);
// Create state functions
IntToFuncMap stateFunctionMap; // stateID -> state function
const int baseStateId =
1000; // could be anything but this makes stateIds more recognizable
createStateFunctions(stateFunctionMap, shaderEntryStateIds, shaderStackSizes,
baseStateId, shaderNames, runtimeDataArgTy);
if (pCachedMap) {
for (auto &entry : stateFunctionMap) {
(*pCachedMap)[entry.first] = entry.second->getName().str();
}
}
}
void DxrFallbackCompiler::link(std::vector<int> &shaderEntryStateIds,
std::vector<unsigned int> &shaderStackSizes,
IntToFuncNameMap *pCachedMap) {
IntToFuncMap stateFunctionMap; // stateID -> state function
if (pCachedMap) {
for (auto entry : *pCachedMap) {
stateFunctionMap[entry.first] = m_module->getFunction(entry.second);
}
} else {
for (UINT i = 0; i < shaderEntryStateIds.size(); i++) {
UINT substateIndex = 0;
UINT baseStateId = shaderEntryStateIds[i];
while (true) {
auto substateName =
m_entryShaderNames[i] + ".ss_" + std::to_string(substateIndex);
auto function = m_module->getFunction(substateName);
if (!function)
break;
stateFunctionMap[baseStateId + substateIndex] =
m_module->getFunction(substateName);
substateIndex++;
}
}
}
// Fix up scheduler
Function *schedulerFunc = m_module->getFunction("fb_Fallback_Scheduler");
createLaunchParams(schedulerFunc);
Type *runtimeDataArgTy = getRuntimeDataArgType();
createStateDispatch(schedulerFunc, stateFunctionMap, runtimeDataArgTy);
createStack(schedulerFunc);
lowerIntrinsics();
}
void DxrFallbackCompiler::setDebugOutputLevel(int val) {
m_debugOutputLevel = val;
}
static bool isShader(Function *F) {
if (F->hasFnAttribute("exp-shader"))
return true;
DxilModule &DM = F->getParent()->GetDxilModule();
return (DM.HasDxilFunctionProps(F) && DM.GetDxilFunctionProps(F).IsRay());
}
DXIL::ShaderKind getRayShaderKind(Function *F) {
if (F->hasFnAttribute("exp-shader"))
return DXIL::ShaderKind::RayGeneration;
DxilModule &DM = F->getParent()->GetDxilModule();
if (DM.HasDxilFunctionProps(F) && DM.GetDxilFunctionProps(F).IsRay())
return DM.GetDxilFunctionProps(F).shaderKind;
return DXIL::ShaderKind::Invalid;
}
// Some shaders should use the "pending" values of intrinsics instead of the
// committed ones. In particular anyhit and intersection shaders use the
// pending values with the exception that the committed rayTCurrent should be
// used in intersection.
static bool shouldUsePendingValue(Function *F, StringRef instrinsicName) {
DxilModule &DM = F->getParent()->GetDxilModule();
if (!DM.HasDxilFunctionProps(F))
return false;
const hlsl::DxilFunctionProps &props = DM.GetDxilFunctionProps(F);
return props.IsAnyHit() ||
(props.IsIntersection() && instrinsicName != "rayTCurrent");
}
void DxrFallbackCompiler::initShaderMap(std::vector<std::string> &shaderNames) {
// Clean names and initialize shaderMap
StringToFuncMap allShadersMap;
for (Function &F : m_module->functions()) {
if (isShader(&F)) {
if (!F.isDeclaration())
allShadersMap[cleanName(F.getName())] = &F;
}
F.removeFnAttr(Attribute::NoInline);
}
for (auto &name : shaderNames)
m_shaderMap[name] = allShadersMap[name];
if (!m_findCalledShaders)
return;
// Create a map from shader name to CallGraphNode
CallGraph callGraph(*m_module);
std::map<std::string, CallGraphNode *> allShaderNodes;
for (auto &kv : m_shaderMap) {
const std::string &name = kv.first;
Function *func = kv.second;
allShaderNodes[name] = callGraph[func];
}
// Start traversing the call graph from given shaderNames
std::deque<CallGraphNode *> workList;
for (auto &name : shaderNames)
workList.push_back(allShaderNodes[name]);
while (!workList.empty()) {
CallGraphNode *cur = workList.front();
workList.pop_front();
for (size_t i = 0; i < cur->size(); ++i) {
Function *nextFunc = (*cur)[i]->getFunction();
if (!nextFunc)
continue;
if (isShader(nextFunc)) {
const std::string nextName = cleanName(nextFunc->getName());
if (m_shaderMap.count(nextName) == 0) // not in the shaderMap yet?
{
workList.push_back(allShaderNodes[nextName]);
shaderNames.push_back(nextName);
m_shaderMap[nextName] = workList.back()->getFunction();
}
}
}
}
}
void DxrFallbackCompiler::linkRuntime() {
Linker linker(m_module);
std::unique_ptr<Module> runtimeModule =
loadModuleFromAsmString(m_module->getContext(), getRuntimeString());
bool linkErr = linker.linkInModule(runtimeModule.get());
assert(!linkErr && "Error linking runtime");
UNREFERENCED_PARAMETER(linkErr);
}
static void inlineFuncAndAddRet(CallInst *call, Function *F) {
// Add a return after the function call.
// Should be followed immediately by "unreachable". Turn that into a "ret
// void".
Instruction *ret = ReturnInst::Create(call->getContext());
ReplaceInstWithInst(call->getParent()->getTerminator(), ret);
bool success = inlineFunc(call, F);
assert(success);
UNREFERENCED_PARAMETER(success);
}
void DxrFallbackCompiler::lowerAnyHitControlFlowFuncs() {
std::vector<CallInst *> callsToIgnoreHit =
getCallsInShadersToFunction("dx.op.ignoreHit");
if (!callsToIgnoreHit.empty()) {
Function *ignoreHitFunc =
m_module->getFunction("\x1?Fallback_IgnoreHit@@YAXXZ");
assert(ignoreHitFunc && "IgnoreHit() implementation not found");
for (CallInst *call : callsToIgnoreHit)
inlineFuncAndAddRet(call, ignoreHitFunc);
}
std::vector<CallInst *> callsToAcceptHitAndEndSearch =
getCallsInShadersToFunction("dx.op.acceptHitAndEndSearch");
if (!callsToAcceptHitAndEndSearch.empty()) {
Function *acceptHitAndEndSearchFunc =
m_module->getFunction("\x1?Fallback_AcceptHitAndEndSearch@@YAXXZ");
assert(acceptHitAndEndSearchFunc &&
"AcceptHitAndEndSearch() implementation not found");
for (CallInst *call : callsToAcceptHitAndEndSearch)
inlineFuncAndAddRet(call, acceptHitAndEndSearchFunc);
}
}
void DxrFallbackCompiler::lowerReportHit() {
std::vector<CallInst *> callsToReportHit =
getCallsInShadersToFunctionWithPrefix("dx.op.reportHit");
if (callsToReportHit.empty())
return;
Function *reportHitFunc =
m_module->getFunction("\x1?Fallback_ReportHit@@YAHMI@Z");
assert(reportHitFunc && "ReportHit() implementation not found");
LLVMContext &C = m_module->getContext();
for (CallInst *call : callsToReportHit) {
// Wrap attribute arguments in Fallback_SetPendingAttr() call
Instruction *insertBefore = call;
hlsl::DxilInst_ReportHit reportHitCall(call);
Value *attr = reportHitCall.get_Attributes();
Function *setPendingAttrFunc =
FunctionBuilder(m_module, "\x1?Fallback_SetPendingAttr@@")
.voidTy()
.type(attr->getType(), "attr")
.build();
CallInst::Create(setPendingAttrFunc, {attr}, "", insertBefore);
// Make call to implementation and load result
CallInst *callImpl = CallInst::Create(
reportHitFunc, {reportHitCall.get_THit(), reportHitCall.get_HitKind()},
"reportHit.result", insertBefore);
Value *result = callImpl;
// Result < 0 ==> ret
Value *zero = makeInt32(0, C);
Value *ltz = new ICmpInst(insertBefore, CmpInst::ICMP_SLT, result, zero,
"endSearch");
BasicBlock *prevBlock = call->getParent();
BasicBlock *retBlock = prevBlock->splitBasicBlock(call, "endSearch");
BasicBlock *nextBlock = retBlock->splitBasicBlock(call, "afterReportHit");
ReplaceInstWithInst(prevBlock->getTerminator(),
BranchInst::Create(retBlock, nextBlock, ltz));
ReplaceInstWithInst(retBlock->getTerminator(), ReturnInst::Create(C));
// Compare result to zero and store into original result
Value *gtz =
new ICmpInst(insertBefore, CmpInst::ICMP_SGT, result, zero, "accepted");
call->replaceAllUsesWith(gtz);
bool success = inlineFunc(callImpl, reportHitFunc);
assert(success);
(void)success;
call->eraseFromParent();
}
}
void DxrFallbackCompiler::lowerTraceRay(Type *runtimeDataArgTy) {
std::vector<CallInst *> callsToTraceRay =
getCallsInShadersToFunctionWithPrefix("dx.op.traceRay");
if (callsToTraceRay.empty()) {
// TODO: It might be worth dropping this from the tests eventually
callsToTraceRay =
getCallsInShadersToFunctionWithPrefix("\x1?TraceRayTest@@");
if (callsToTraceRay.empty())
return;
}
std::vector<Function *> traceRayImpl =
getFunctionsWithPrefix(m_module, "\x1?Fallback_TraceRay@@");
assert(traceRayImpl.size() == 1 &&
"Could not find Fallback_TraceRay() implementation");
enum { CLOSEST_HIT = 0, MISS = 1 };
Function *traceRaySave[] = {m_module->getFunction("traceRaySave_ClosestHit"),
m_module->getFunction("traceRaySave_Miss")};
Function *traceRayRestore[] = {
m_module->getFunction("traceRayRestore_ClosestHit"),
m_module->getFunction("traceRayRestore_Miss")};
assert(traceRaySave[CLOSEST_HIT] && traceRayRestore[CLOSEST_HIT] &&
traceRaySave[MISS] && traceRayRestore[MISS] &&
"Could not find TraceRay spill functions");
Function *dummyRuntimeDataArgFunc =
StateFunctionTransform::createDummyRuntimeDataArgFunc(m_module,
runtimeDataArgTy);
assert(dummyRuntimeDataArgFunc &&
"dummyRuntimeDataArg function could not be created.");
// Process calls
LLVMContext &C = m_module->getContext();
Type *int32Ty = Type::getInt32Ty(C);
std::map<FunctionType *, Function *> movePayloadToStackFuncs;
std::map<Function *, AllocaInst *> funcToSpillAlloca;
for (CallInst *call : callsToTraceRay) {
Instruction *insertBefore = call;
// Spill runtime data values, if necessary (closesthit and miss shaders)
Function *caller = call->getParent()->getParent();
DXIL::ShaderKind kind = getRayShaderKind(caller);
if (kind == DXIL::ShaderKind::ClosestHit ||
kind == DXIL::ShaderKind::Miss) {
int sh = (kind == DXIL::ShaderKind::ClosestHit) ? CLOSEST_HIT : MISS;
AllocaInst *spillAlloca = get(funcToSpillAlloca, caller);
if (!spillAlloca) {
Argument *spillAllocaArg = (++traceRaySave[sh]->arg_begin());
Type *spillAllocaTy =
spillAllocaArg->getType()->getPointerElementType();
spillAlloca = new AllocaInst(spillAllocaTy, "spill.alloca",
caller->getEntryBlock().begin());
funcToSpillAlloca[caller] = spillAlloca;
}
// Create calls. SFT will inline them.
Value *runtimeDataArg = CallInst::Create(dummyRuntimeDataArgFunc,
"runtimeData", insertBefore);
CallInst::Create(traceRaySave[sh], {runtimeDataArg, spillAlloca}, "",
insertBefore);
CallInst::Create(traceRayRestore[sh], {runtimeDataArg, spillAlloca}, "",
getInstructionAfter(call));
}
// Get the payload offset to pass to trace implementation
// hlsl::DxilInst_TraceRay traceRayCall(call);
// TODO: Avoiding the intrinsic to support the test's use of TraceRayTest
Value *payload = call->getOperand(call->getNumArgOperands() - 1);
FunctionType *funcType =
FunctionType::get(int32Ty, {payload->getType()}, false);
Function *movePayloadToStackFunc = getOrCreateFunction(
"movePayloadToStack", m_module, funcType, movePayloadToStackFuncs);
Value *newPayloadOffset = CallInst::Create(
movePayloadToStackFunc, {payload}, "new.payload.offset", insertBefore);
// Call implementation
unsigned i = 0;
if (call->getCalledFunction()->getName().startswith("dx.op"))
i += 2; // skip intrinsic number and acceleration structure (for now)
std::vector<Value *> args;
for (; i < call->getNumArgOperands() - 1; ++i)
args.push_back(call->getArgOperand(i));
args.push_back(newPayloadOffset);
CallInst::Create(traceRayImpl[0], args, "", insertBefore);
call->eraseFromParent();
}
}
static std::vector<StateFunctionTransform::ParameterSemanticType>
getParameterTypes(Function *F, DXIL::ShaderKind shaderKind) {
std::vector<StateFunctionTransform::ParameterSemanticType> paramTypes;
if (shaderKind == DXIL::ShaderKind::AnyHit ||
shaderKind == DXIL::ShaderKind::ClosestHit) {
paramTypes.push_back(StateFunctionTransform::PST_PAYLOAD);
paramTypes.push_back(StateFunctionTransform::PST_ATTRIBUTE);
} else if (shaderKind == DXIL::ShaderKind::Miss) {
paramTypes.push_back(StateFunctionTransform::PST_PAYLOAD);
} else {
paramTypes.assign(F->getNumOperands(), StateFunctionTransform::PST_NONE);
}
return paramTypes;
}
static void collectResources(DxilModule &DM, std::set<Value *> &resources) {
for (auto &r : DM.GetCBuffers())
resources.insert(r->GetGlobalSymbol());
for (auto &r : DM.GetUAVs())
resources.insert(r->GetGlobalSymbol());
for (auto &r : DM.GetSRVs())
resources.insert(r->GetGlobalSymbol());
for (auto &r : DM.GetSamplers())
resources.insert(r->GetGlobalSymbol());
}
void DxrFallbackCompiler::createStateFunctions(
IntToFuncMap &stateFunctionMap, std::vector<int> &shaderEntryStateIds,
std::vector<unsigned int> &shaderStackSizes, int baseStateId,
const std::vector<std::string> &shaderNames, Type *runtimeDataArgTy) {
for (auto &kv : m_shaderMap) {
if (kv.second == nullptr)
errs() << "Function not found for shader " << kv.first << "\n";
}
DxilModule &DM = m_module->GetOrCreateDxilModule();
std::set<Value *> resources;
collectResources(DM, resources);
shaderEntryStateIds.clear();
shaderStackSizes.clear();
int stateId = baseStateId;
for (auto &shader : shaderNames) {
std::vector<Function *> stateFunctions;
Function *F = m_shaderMap[shader];
StateFunctionTransform sft(F, shaderNames, runtimeDataArgTy);
if (m_debugOutputLevel >= 2)
sft.setVerbose(true);
if (m_debugOutputLevel >= 3)
sft.setDumpFilename("dump.ll");
if (shader == "Fallback_TraceRay")
sft.setAttributeSize(m_maxAttributeSize);
DXIL::ShaderKind shaderKind = getRayShaderKind(F);
if (shaderKind != DXIL::ShaderKind::Invalid)
sft.setParameterInfo(getParameterTypes(F, shaderKind),
shaderKind == DXIL::ShaderKind::ClosestHit);
sft.setResourceGlobals(resources);
UINT shaderStackSize = 0;
sft.run(stateFunctions, shaderStackSize);
shaderEntryStateIds.push_back(stateId);
shaderStackSizes.push_back(shaderStackSize);
for (Function *stateF : stateFunctions) {
stateFunctionMap[stateId++] = stateF;
if (DM.HasDxilFunctionProps(F)) {
DM.CloneDxilEntryProps(F, stateF);
}
}
}
StateFunctionTransform::finalizeStateIds(m_module, shaderEntryStateIds);
}
void DxrFallbackCompiler::createLaunchParams(Function *func) {
Module *mod = func->getParent();
Function *rewrite_setLaunchParams =
mod->getFunction("rewrite_setLaunchParams");
CallInst *call = dyn_cast<CallInst>(*rewrite_setLaunchParams->user_begin());
LLVMContext &context = mod->getContext();
Instruction *insertBefore = call;
Function *DTidFunc =
FunctionBuilder(mod, "dx.op.threadId.i32").i32().i32().i32().build();
Value *DTidx =
CallInst::Create(DTidFunc,
{makeInt32((int)hlsl::OP::OpCode::ThreadId, context),
makeInt32(0, context)},
"DTidx", insertBefore);
Value *DTidy =
CallInst::Create(DTidFunc,
{makeInt32((int)hlsl::OP::OpCode::ThreadId, context),
makeInt32(1, context)},
"DTidy", insertBefore);
Value *dimx = call->getArgOperand(1);
Value *dimy = call->getArgOperand(2);
Function *groupIndexFunc =
FunctionBuilder(mod, "dx.op.flattenedThreadIdInGroup.i32")
.i32()
.i32()
.build();
Value *groupIndex = CallInst::Create(groupIndexFunc, {makeInt32(96, context)},
"groupIndex", insertBefore);
Function *fb_setLaunchParams =
mod->getFunction("fb_Fallback_SetLaunchParams");
Value *runtimeDataArg = call->getArgOperand(0);
CallInst::Create(fb_setLaunchParams,
{runtimeDataArg, DTidx, DTidy, dimx, dimy, groupIndex}, "",
insertBefore);
call->eraseFromParent();
rewrite_setLaunchParams->eraseFromParent();
}
void DxrFallbackCompiler::createStateDispatch(
Function *func, const IntToFuncMap &stateFunctionMap,
Type *runtimeDataArgTy) {
Module *mod = func->getParent();
Function *dispatchFunc =
createDispatchFunction(stateFunctionMap, runtimeDataArgTy);
Function *rewrite_dispatchFunc = mod->getFunction("rewrite_dispatch");
rewrite_dispatchFunc->replaceAllUsesWith(dispatchFunc);
rewrite_dispatchFunc->eraseFromParent();
}
void DxrFallbackCompiler::createStack(Function *func) {
LLVMContext &context = func->getContext();
// We would like to allocate the properly sized stack here, but DXIL doesn't
// allow bitcasts between objects of different sizes. So we have to use the
// default size from the runtime and replace all the accesses later.
Function *rewrite_createStack = m_module->getFunction("rewrite_createStack");
CallInst *call = dyn_cast<CallInst>(*rewrite_createStack->user_begin());
AllocaInst *stack = new AllocaInst(call->getType()->getPointerElementType(),
"theStack", call);
stack->setAlignment(sizeof(int));
call->replaceAllUsesWith(stack);
call->eraseFromParent();
rewrite_createStack->eraseFromParent();
if (m_stackSizeInBytes == 0) // Take the default
m_stackSizeInBytes =
stack->getType()->getPointerElementType()->getArrayNumElements() *
sizeof(int);
Function *rewrite_getStackSize =
m_module->getFunction("rewrite_getStackSize");
call = dyn_cast<CallInst>(*rewrite_getStackSize->user_begin());
Value *stackSizeVal = makeInt32(m_stackSizeInBytes, context);
call->replaceAllUsesWith(stackSizeVal);
call->eraseFromParent();
rewrite_getStackSize->eraseFromParent();
}
// WAR to avoid crazy <3 x float> code emitted by vanilla clang in the runtime
static bool expandFloat3(std::vector<Value *> &args, Value *arg,
Instruction *insertBefore) {
VectorType *argTy = dyn_cast<VectorType>(arg->getType());
if (!argTy || argTy->getVectorNumElements() != 3)
return false;
LLVMContext &C = arg->getContext();
args.push_back(
ExtractElementInst::Create(arg, makeInt32(0, C), "vec.x", insertBefore));
args.push_back(
ExtractElementInst::Create(arg, makeInt32(1, C), "vec.y", insertBefore));
args.push_back(
ExtractElementInst::Create(arg, makeInt32(2, C), "vec.z", insertBefore));
return true;
}
static bool float3x4ToFloat12(std::vector<Value *> &args, Value *arg,
Instruction *insertBefore) {
StructType *STy = dyn_cast<StructType>(arg->getType());
if (!STy || STy->getName() != "class.matrix.float.3.4")
return false;
BasicBlock &entryBlock =
insertBefore->getParent()->getParent()->getEntryBlock();
AllocaInst *alloca =
new AllocaInst(arg->getType(), "tmp", entryBlock.begin());
new StoreInst(arg, alloca, insertBefore);
VectorType *VTy = VectorType::get(Type::getFloatTy(arg->getContext()), 12);
Value *vec12Ptr =
new BitCastInst(alloca, VTy->getPointerTo(), "vec12.ptr", insertBefore);
Value *vec12 = new LoadInst(vec12Ptr, "vec12.", insertBefore);
args.push_back(vec12);
return true;
}
void DxrFallbackCompiler::lowerIntrinsics() {
std::vector<Function *> intrinsics = getFunctionsWithPrefix(m_module, "fb_");
assert(intrinsics.size() > 0);
// Replace intrinsics in anyhit shaders with their pending versions
LLVMContext &C = m_module->getContext();
std::map<std::string, Function *> pendingIntrinsics;
std::string pendingPrefixes[] = {"fb_dxop_pending_", "fb_Fallback_Pending"};
for (auto &F : intrinsics) {
std::string intrinsicName;
if (F->getName().startswith(pendingPrefixes[0]))
intrinsicName = F->getName().substr(pendingPrefixes[0].length());
else if (F->getName().startswith(pendingPrefixes[1]))
intrinsicName =
"Fallback_" + F->getName().substr(pendingPrefixes[1].length()).str();
else
continue;
pendingIntrinsics[intrinsicName] = F;
}
for (Function *func : intrinsics) {
StringRef intrinsicName;
std::string name;
bool isDxilOp = false;
if (func->getName().startswith("fb_Fallback_")) {
intrinsicName = func->getName().substr(3); // after the "fb_" prefix
name = "\x1?" + intrinsicName.str();
} else if (func->getName().startswith("fb_dxop_")) {
intrinsicName = func->getName().substr(8);
name = "dx.op." + intrinsicName.str();
isDxilOp = true;
} else {
assert(0 && "Bad intrinsic");
}
std::vector<Function *> calledFunc = getFunctionsWithPrefix(m_module, name);
if (calledFunc.empty())
continue;
std::vector<CallInst *> calls = getCallsToFunction(calledFunc[0]);
if (calls.empty())
continue;
bool needsRuntimeDataArg = (intrinsicName != "Fallback_Scheduler");
Function *pendingFunc = get(pendingIntrinsics, intrinsicName.str());
Function *funcInModule = nullptr;
Function *pendingFuncInModule = nullptr;
for (CallInst *call : calls) {
Function *caller = call->getParent()->getParent();
if (needsRuntimeDataArg && !caller->hasFnAttribute("state_function"))
continue;
Function *F = nullptr;
if (pendingFunc && shouldUsePendingValue(caller, intrinsicName)) {
if (!pendingFuncInModule)
pendingFuncInModule = getOrInsertFunction(m_module, pendingFunc);
F = pendingFuncInModule;
} else {
if (!funcInModule)
funcInModule = getOrInsertFunction(m_module, func);
F = funcInModule;
}
// insert runtime data and the rest of the arguments
std::vector<Value *> args;
if (needsRuntimeDataArg)
args.push_back(caller->arg_begin());
int argIdx = 0;
for (auto &arg : call->arg_operands()) {
if (argIdx++ == 0 && isDxilOp)
continue; // skip the intrinsic number
if (!expandFloat3(args, arg, call) &&
!float3x4ToFloat12(args, arg, call))
args.push_back(arg);
}
CallInst *newCall = CallInst::Create(F, args, "", call);
if (F->getFunctionType()->getReturnType() != Type::getVoidTy(C)) {
newCall->takeName(call);
call->replaceAllUsesWith(newCall);
}
call->eraseFromParent();
}
}
}
Type *DxrFallbackCompiler::getRuntimeDataArgType() {
// Get the first argument from a known runtime function (assuming the runtime
// has already been linked in).
Function *F = m_module->getFunction("stackIntPtr");
return F->arg_begin()->getType();
}
Function *DxrFallbackCompiler::createDispatchFunction(
const IntToFuncMap &stateFunctionMap, Type *runtimeDataArgTy) {
LLVMContext &context = m_module->getContext();
FunctionType *stateFuncTy =
FunctionType::get(Type::getInt32Ty(context), {runtimeDataArgTy}, false);
Function *dispatchFunc = FunctionBuilder(m_module, "dispatch")
.i32()
.type(runtimeDataArgTy, "runtimeData")
.i32("stateID")
.build();
Value *runtimeDataArg = dispatchFunc->arg_begin();
Value *stateIdArg = ++dispatchFunc->arg_begin();
BasicBlock *entryBlock = BasicBlock::Create(context, "entry", dispatchFunc);
BasicBlock *badBlock =
BasicBlock::Create(context, "badStateID", dispatchFunc);
IRBuilder<> builder(badBlock);
builder.SetInsertPoint(badBlock);
builder.CreateRet(makeInt32(-3, context)); // return an error value
builder.SetInsertPoint(entryBlock);
SwitchInst *switchInst =
builder.CreateSwitch(stateIdArg, badBlock, stateFunctionMap.size());
BasicBlock *endBlock = badBlock;
for (auto &kv : stateFunctionMap) {
int stateId = kv.first;
Function *stateFunc = kv.second;
Value *stateFuncInModule =
m_module->getOrInsertFunction(stateFunc->getName(), stateFuncTy);
BasicBlock *block = BasicBlock::Create(
context, "state_" + Twine(stateId) + "." + stateFunc->getName(),
dispatchFunc, endBlock);
builder.SetInsertPoint(block);
Value *nextStateId =
builder.CreateCall(stateFuncInModule, {runtimeDataArg}, "nextStateId");
builder.CreateRet(nextStateId);
switchInst->addCase(makeInt32(stateId, context), block);
}
return dispatchFunc;
}
std::vector<CallInst *>
DxrFallbackCompiler::getCallsInShadersToFunction(const std::string &funcName) {
std::vector<CallInst *> calls;
Function *F = m_module->getFunction(funcName);
if (!F)
return calls;
for (User *U : F->users()) {
CallInst *call = dyn_cast<CallInst>(U);
if (!call)
continue;
Function *caller = call->getParent()->getParent();
auto it = m_shaderMap.find(cleanName(caller->getName()));
if (it != m_shaderMap.end())
calls.push_back(call);
}
return calls;
}
std::vector<CallInst *>
DxrFallbackCompiler::getCallsInShadersToFunctionWithPrefix(
const std::string &funcNamePrefix) {
std::vector<CallInst *> calls;
for (Function *F : getFunctionsWithPrefix(m_module, funcNamePrefix)) {
for (User *U : F->users()) {
CallInst *call = dyn_cast<CallInst>(U);
if (!call)
continue;
Function *caller = call->getParent()->getParent();
if (m_shaderMap.count(cleanName(caller->getName())))
calls.push_back(call);
}
}
return calls;
}
void DxrFallbackCompiler::resizeStack(Function *F, unsigned sizeInBytes) {
// Find the stack
AllocaInst *stack = nullptr;
for (auto &I : F->getEntryBlock().getInstList()) {
AllocaInst *alloc = dyn_cast<AllocaInst>(&I);
if (alloc && alloc->getName().startswith("theStack")) {
stack = alloc;
break;
}
}
if (!stack)
return;
// Create a new stack
LLVMContext &C = F->getContext();
ArrayType *newStackTy =
ArrayType::get(Type::getInt32Ty(C), sizeInBytes / sizeof(int));
AllocaInst *newStack = new AllocaInst(newStackTy, "", stack);
newStack->takeName(stack);
// Remap all GEPs - replaceAllUsesWith() won't change types
for (auto U = stack->user_begin(), UE = stack->user_end(); U != UE;) {
GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(*U++);
assert(gep && "theStack has non-gep user.");
std::vector<Value *> idxList(gep->idx_begin(), gep->idx_end());
GetElementPtrInst *newGep =
GetElementPtrInst::CreateInBounds(newStack, idxList, "", gep);
newGep->takeName(gep);
gep->replaceAllUsesWith(newGep);
gep->eraseFromParent();
}
stack->eraseFromParent();
} |
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxrFallback/FunctionBuilder.h | #pragma once
#include "llvm/IR/Module.h"
#include <string>
#include <vector>
//==============================================================================
// Simplifies the creation of functions.
//
// To create a function 'void foo( userType, i32, float* )' use the following
// code:
// FunctionBuilder(module,
// "foo").voidTy().type(userType).i32().floatPtr().build()
//
// The first type specified is the return type.
class FunctionBuilder {
public:
FunctionBuilder(llvm::Module *mod, const std::string &name)
: m_context(mod->getContext()), m_module(mod), m_name(name) {}
FunctionBuilder &voidTy() {
m_argNames.push_back("");
m_types.push_back(llvm::Type::getVoidTy(m_context));
return *this;
}
FunctionBuilder &floatTy(const std::string &argName = "") {
m_argNames.push_back(argName);
m_types.push_back(llvm::Type::getFloatTy(m_context));
return *this;
}
FunctionBuilder &floatPtr(const std::string &argName = "") {
m_argNames.push_back(argName);
m_types.push_back(llvm::Type::getFloatPtrTy(m_context));
return *this;
}
FunctionBuilder &doubleTy(const std::string &argName = "") {
m_argNames.push_back(argName);
m_types.push_back(llvm::Type::getDoubleTy(m_context));
return *this;
}
FunctionBuilder &doublePtr(const std::string &argName = "") {
m_argNames.push_back(argName);
m_types.push_back(llvm::Type::getDoublePtrTy(m_context));
return *this;
}
FunctionBuilder &i32(const std::string &argName = "") {
m_argNames.push_back(argName);
m_types.push_back(llvm::Type::getInt32Ty(m_context));
return *this;
}
FunctionBuilder &i32Ptr(const std::string &argName = "") {
m_argNames.push_back(argName);
m_types.push_back(llvm::Type::getInt32PtrTy(m_context));
return *this;
}
FunctionBuilder &i16(const std::string &argName = "") {
m_argNames.push_back(argName);
m_types.push_back(llvm::Type::getInt16Ty(m_context));
return *this;
}
FunctionBuilder &i16Ptr(const std::string &argName = "") {
m_argNames.push_back(argName);
m_types.push_back(llvm::Type::getInt16PtrTy(m_context));
return *this;
}
FunctionBuilder &i8(const std::string &argName = "") {
m_argNames.push_back(argName);
m_types.push_back(llvm::Type::getInt8Ty(m_context));
return *this;
}
FunctionBuilder &i8Ptr(const std::string &argName = "") {
m_argNames.push_back(argName);
m_types.push_back(llvm::Type::getInt8PtrTy(m_context));
return *this;
}
FunctionBuilder &i1(const std::string &argName = "") {
m_argNames.push_back(argName);
m_types.push_back(llvm::Type::getInt1Ty(m_context));
return *this;
}
FunctionBuilder &i1Ptr(const std::string &argName = "") {
m_argNames.push_back(argName);
m_types.push_back(llvm::Type::getInt1PtrTy(m_context));
return *this;
}
FunctionBuilder &type(llvm::Type *ty, const std::string &argName = "") {
m_argNames.push_back(argName);
m_types.push_back(ty);
return *this;
}
FunctionBuilder &types(const std::vector<llvm::Type *> &ty,
const std::vector<std::string> &argNames) {
if (argNames.empty())
for (size_t i = 0; i < ty.size(); ++i)
m_argNames.push_back("");
m_types.insert(m_types.end(), ty.begin(), ty.end());
return *this;
}
llvm::Function *build() {
using namespace llvm;
Type *retTy = m_types[0];
AttributeSet attributes;
Type **argsBegin = (&m_types[0]) + 1;
Type **argsEnd = argsBegin + m_types.size() - 1;
Constant *funcC = m_module->getOrInsertFunction(
m_name,
FunctionType::get(retTy, ArrayRef<Type *>(argsBegin, argsEnd), false),
attributes);
Function *func = cast<Function>(funcC);
std::string *argNamePtr = m_argNames.data() + 1;
for (auto &arg : func->args())
arg.setName(*argNamePtr++);
return func;
}
private:
llvm::LLVMContext &m_context;
llvm::Module *m_module = nullptr;
std::string m_name;
std::vector<std::string> m_argNames;
std::vector<llvm::Type *> m_types;
// forbidden
FunctionBuilder();
FunctionBuilder(const FunctionBuilder &);
};
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxrFallback/readme.md | # DXR Fallback Compiler
The DXR Fallback Compiler is a specialized compiler that's a part of the [D3D12 Raytracing Fallback Layer](https://github.com/Microsoft/DirectX-Graphics-Samples/tree/master/Libraries/D3D12RaytracingFallback). The purpose of the DXR Fallback Compiler is to take input DXR shader libs and link them into a single compute shader that is runnable DX12 hardware (even without DXR driver support).
## Building the DXR Fallback Compiler
In order to build the DXR Fallback Compiler in Visual Studio, simply build the dxrfallbackcompiler project in the *Clang Libraries* folder.
## Using with the D3D12 Raytracing Fallback Layer
To use the DXR Fallback Compiler with the [DirectX Graphics Samples](https://github.com/Microsoft/DirectX-Graphics-Samples/blob/master/Samples/Desktop/D3D12Raytracing/readme.md), build a dxrfallbackcompiler.dll using the Build instructions and place the output dll in Samples/Desktop/D3D12Raytracing/tools/x64.
If you're incorporating the Fallback Layer into your own personal project, you need to ensure that the dll is either alongside your executable or in the working directory.
## Overview
Note that the below overview and all proceeding documentation assumes familiarity with the DirectX Raytracing API.
The DXR Fallback Compiler addresses several challenges that native DX12 compute shaders are not normally capable of handling:
* Combining multiple orthogonal shaders into a single large compute shader
* Uses of all new DXR HLSL intrinsics
* Invocation of another shader in the middle of shader code - *i.e. TraceRay and CallShader*
* Recursive invocations of shader calls
These challenges are handled by abstractly viewing GPU execution of a DXR pipeline as State Machine traversal, where each shader is transformed into one or more state functions. further technical details are described in the header of [StateFunctionTransform.h](../DxrFallback/StateFunctionTransform.h).
## Building runtime.h
Download LLVM 3.7: http://releases.llvm.org/3.7.0/LLVM-3.7.0-win64.exe
You may need to adjust BINPATH in script.cmd to point to your llvm binaries
Run script.cmd and it should output a patched runtime.h
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxrFallback/runtime.h |
// This file generated by compiling the following source (runtime.c) as follows:
// clang -S -emit-llvm -target nvptr runtime.c
// opt -S -mem2reg runtime.ll -o runtime.opt.ll
// The resulting LLVM-IR is stripped of its datalayout and replaced with one
// compatible with DXIL.
// runtime.c
#if 0
#include <stddef.h>
static const int STACK_SIZE_IN_BYTES = 1024;
typedef float float3 __attribute__((vector_size(3*sizeof(float))));
typedef float float4 __attribute__((vector_size(4*sizeof(float))));
typedef float float12 __attribute__((vector_size(12*sizeof(float))));
typedef float (M3x4)[12];
typedef int (StackType)[STACK_SIZE_IN_BYTES/sizeof(int)];
typedef unsigned char byte;
typedef struct RuntimeDataStruct
{
int DispatchRaysIndex[2];
int DispatchRaysDimensions[2];
float RayTMin;
float RayTCurrent;
unsigned RayFlags;
float WorldRayOrigin[3];
float WorldRayDirection[3];
float ObjectRayOrigin[3];
float ObjectRayDirection[3];
M3x4 ObjectToWorld;
M3x4 WorldToObject;
unsigned PrimitiveIndex;
unsigned InstanceIndex;
unsigned InstanceID;
unsigned HitKind;
unsigned ShaderRecordOffset;
// Pending hit values - accessed in anyHit and intersection shaders before a hit has been committed
float PendingRayTCurrent;
unsigned PendingPrimitiveIndex;
unsigned PendingInstanceIndex;
unsigned PendingInstanceID;
unsigned PendingHitKind;
unsigned PendingShaderRecordOffset;
int GroupIndex;
int AnyHitResult;
int AnyHitStateId; // Originally temporary. We needed to avoid resource usage
// in ReportHit() because of linking issues so weset the value here first.
// May be worth retaining to cache the value when fetching the intersection
// stateId (fetch them both at once).
int PayloadOffset;
int CommittedAttrOffset;
int PendingAttrOffset;
int StackOffset; // offset from the start of the stack
StackType* Stack;
} RuntimeData;
typedef RuntimeData* RuntimeDataType;
typedef struct TraceRaySpills_ClosestHit
{
float RayTMin;
float RayTCurrent;
unsigned RayFlags;
float WorldRayOrigin[3];
float WorldRayDirection[3];
float ObjectRayOrigin[3];
float ObjectRayDirection[3];
unsigned PrimitiveIndex;
unsigned InstanceIndex;
unsigned InstanceID;
unsigned HitKind;
unsigned ShaderRecordOffset;
} TraceRaySpills_ClosestHit;
typedef struct TraceRaySpills_Miss
{
float RayTMin;
float RayTCurrent;
unsigned RayFlags;
float WorldRayOrigin[3];
float WorldRayDirection[3];
unsigned ShaderRecordOffset;
} TraceRaySpills_Miss;
#define REF(x) (runtimeData->x)
#define REF_FLT(x) (runtimeData->x)
#define REF_STACK(offset) \
((*runtimeData->Stack)[runtimeData->StackOffset + offset])
#define REF_FLT_OFS(x, offset) (runtimeData->x[offset])
// Return next stateID
int rewrite_dispatch(RuntimeDataType runtimeData, int stateID);
void* rewrite_setLaunchParams(RuntimeDataType runtimeData, unsigned dimx, unsigned dimy);
unsigned rewrite_getStackSize(void);
StackType* rewrite_createStack(void);
void stackInit(RuntimeDataType runtimeData, StackType* theStack, unsigned stackSize)
{
REF(Stack) = theStack;
REF(StackOffset) = stackSize/sizeof(int) - 1;
REF(PayloadOffset) = 1111; // recognizable bogus values
REF(CommittedAttrOffset) = 2222;
REF(PendingAttrOffset) = 3333;
}
void stackFramePush(RuntimeDataType runtimeData, int size)
{
REF(StackOffset) -= size;
}
void stackFramePop(RuntimeDataType runtimeData, int size)
{
REF(StackOffset) += size;
}
int stackFrameOffset(RuntimeDataType runtimeData)
{
return REF(StackOffset);
}
int payloadOffset(RuntimeDataType runtimeData)
{
return REF(PayloadOffset);
}
int committedAttrOffset(RuntimeDataType runtimeData)
{
return REF(CommittedAttrOffset);
}
int pendingAttrOffset(RuntimeDataType runtimeData)
{
return REF(PendingAttrOffset);
}
int* stackIntPtr(RuntimeDataType runtimeData, int baseOffset, int offset)
{
return &(*runtimeData->Stack)[baseOffset + offset];
}
void traceFramePush(RuntimeDataType runtimeData, int attrSize)
{
// Save the old payload and attribute offsets
REF_STACK(-1) = REF(CommittedAttrOffset);
REF_STACK(-2) = REF(PendingAttrOffset);
// Set new offsets
REF(CommittedAttrOffset) = REF(StackOffset) - 2 - attrSize;
REF(PendingAttrOffset) = REF(StackOffset) - 2 - 2 * attrSize;
}
void traceFramePop(RuntimeDataType runtimeData)
{
// Restore the old attribute offsets
REF(CommittedAttrOffset) = REF_STACK(-1);
REF(PendingAttrOffset) = REF_STACK(-2);
}
void traceRaySave_ClosestHit(RuntimeDataType runtimeData, TraceRaySpills_ClosestHit* spills)
{
spills->RayFlags = REF(RayFlags);
spills->RayTCurrent = REF_FLT(RayTCurrent);
spills->RayTMin = REF_FLT(RayTMin);
spills->WorldRayOrigin[0] = REF_FLT(WorldRayOrigin[0]);
spills->WorldRayOrigin[1] = REF_FLT(WorldRayOrigin[1]);
spills->WorldRayOrigin[2] = REF_FLT(WorldRayOrigin[2]);
spills->WorldRayDirection[0] = REF_FLT(WorldRayDirection[0]);
spills->WorldRayDirection[1] = REF_FLT(WorldRayDirection[1]);
spills->WorldRayDirection[2] = REF_FLT(WorldRayDirection[2]);
spills->ObjectRayOrigin[0] = REF_FLT(ObjectRayOrigin[0]);
spills->ObjectRayOrigin[1] = REF_FLT(ObjectRayOrigin[1]);
spills->ObjectRayOrigin[2] = REF_FLT(ObjectRayOrigin[2]);
spills->ObjectRayDirection[0] = REF_FLT(ObjectRayDirection[0]);
spills->ObjectRayDirection[1] = REF_FLT(ObjectRayDirection[1]);
spills->ObjectRayDirection[2] = REF_FLT(ObjectRayDirection[2]);
spills->PrimitiveIndex = REF(PrimitiveIndex);
spills->InstanceIndex = REF(InstanceIndex);
spills->InstanceID = REF(InstanceID);
spills->HitKind = REF(HitKind);
spills->ShaderRecordOffset = REF(ShaderRecordOffset);
}
void traceRayRestore_ClosestHit(RuntimeDataType runtimeData, TraceRaySpills_ClosestHit* spills)
{
REF(RayFlags) = spills->RayFlags;
REF_FLT(RayTCurrent) = spills->RayTCurrent;
REF_FLT(RayTMin) = spills->RayTMin;
REF_FLT(WorldRayOrigin[0]) = spills->WorldRayOrigin[0];
REF_FLT(WorldRayOrigin[1]) = spills->WorldRayOrigin[1];
REF_FLT(WorldRayOrigin[2]) = spills->WorldRayOrigin[2];
REF_FLT(WorldRayDirection[0]) = spills->WorldRayDirection[0];
REF_FLT(WorldRayDirection[1]) = spills->WorldRayDirection[1];
REF_FLT(WorldRayDirection[2]) = spills->WorldRayDirection[2];
REF_FLT(ObjectRayOrigin[0]) = spills->ObjectRayOrigin[0];
REF_FLT(ObjectRayOrigin[1]) = spills->ObjectRayOrigin[1];
REF_FLT(ObjectRayOrigin[2]) = spills->ObjectRayOrigin[2];
REF_FLT(ObjectRayDirection[0]) = spills->ObjectRayDirection[0];
REF_FLT(ObjectRayDirection[1]) = spills->ObjectRayDirection[1];
REF_FLT(ObjectRayDirection[2]) = spills->ObjectRayDirection[2];
REF(PrimitiveIndex) = spills->PrimitiveIndex;
REF(InstanceIndex) = spills->InstanceIndex;
REF(InstanceID) = spills->InstanceID;
REF(HitKind) = spills->HitKind;
REF(ShaderRecordOffset) = spills->ShaderRecordOffset;
}
void traceRaySave_Miss(RuntimeDataType runtimeData, TraceRaySpills_Miss* spills)
{
spills->RayFlags = REF(RayFlags);
spills->RayTCurrent = REF_FLT(RayTCurrent);
spills->RayTMin = REF_FLT(RayTMin);
spills->WorldRayOrigin[0] = REF_FLT(WorldRayOrigin[0]);
spills->WorldRayOrigin[1] = REF_FLT(WorldRayOrigin[1]);
spills->WorldRayOrigin[2] = REF_FLT(WorldRayOrigin[2]);
spills->WorldRayDirection[0] = REF_FLT(WorldRayDirection[0]);
spills->WorldRayDirection[1] = REF_FLT(WorldRayDirection[1]);
spills->WorldRayDirection[2] = REF_FLT(WorldRayDirection[2]);
spills->ShaderRecordOffset = REF(ShaderRecordOffset);
}
void traceRayRestore_Miss(RuntimeDataType runtimeData, TraceRaySpills_Miss* spills)
{
REF(RayFlags) = spills->RayFlags;
REF_FLT(RayTCurrent) = spills->RayTCurrent;
REF_FLT(RayTMin) = spills->RayTMin;
REF_FLT(WorldRayOrigin[0]) = spills->WorldRayOrigin[0];
REF_FLT(WorldRayOrigin[1]) = spills->WorldRayOrigin[1];
REF_FLT(WorldRayOrigin[2]) = spills->WorldRayOrigin[2];
REF_FLT(WorldRayDirection[0]) = spills->WorldRayDirection[0];
REF_FLT(WorldRayDirection[1]) = spills->WorldRayDirection[1];
REF_FLT(WorldRayDirection[2]) = spills->WorldRayDirection[2];
REF(ShaderRecordOffset) = spills->ShaderRecordOffset;
}
//////////////////////////////////////////////////////////////////////////
//
// Intrinsics for the fallback layer
//
//////////////////////////////////////////////////////////////////////////
void fb_Fallback_Scheduler(int initialStateId, unsigned dimx, unsigned dimy)
{
StackType* theStack = rewrite_createStack();
RuntimeData theRuntimeData;
RuntimeDataType runtimeData = &theRuntimeData;
rewrite_setLaunchParams(runtimeData, dimx, dimy);
if(REF(DispatchRaysIndex[0]) >= REF(DispatchRaysDimensions[0]) ||
REF(DispatchRaysIndex[1]) >= REF(DispatchRaysDimensions[1]))
{
return;
}
// Set final return stateID into reserved area at stack top
unsigned stackSize = rewrite_getStackSize();
stackInit(runtimeData, theStack, stackSize);
int stackFrameOffs = stackFrameOffset(runtimeData);
*stackIntPtr(runtimeData, stackFrameOffs, 0) = -1;
int stateId = initialStateId;
int count = 0;
while( stateId >= 0 )
{
stateId = rewrite_dispatch(runtimeData, stateId);
}
}
void fb_Fallback_SetLaunchParams(RuntimeDataType runtimeData, unsigned DTidx, unsigned DTidy, unsigned dimx, unsigned dimy, unsigned groupIndex)
{
REF(DispatchRaysIndex[0]) = DTidx;
REF(DispatchRaysIndex[1]) = DTidy;
REF(DispatchRaysDimensions[0]) = dimx;
REF(DispatchRaysDimensions[1]) = dimy;
REF(GroupIndex) = groupIndex;
}
int fb_Fallback_TraceRayBegin(RuntimeDataType runtimeData, unsigned rayFlags, float ox, float oy, float oz, float tmin, float dx, float dy, float dz, float tmax, int newPayloadOffset)
{
REF(RayFlags) = rayFlags;
REF_FLT(WorldRayOrigin[0]) = ox;
REF_FLT(WorldRayOrigin[1]) = oy;
REF_FLT(WorldRayOrigin[2]) = oz;
REF_FLT(WorldRayDirection[0]) = dx;
REF_FLT(WorldRayDirection[1]) = dy;
REF_FLT(WorldRayDirection[2]) = dz;
REF_FLT(RayTCurrent) = tmax;
REF_FLT(RayTMin) = tmin;
int oldOffset = REF(PayloadOffset);
REF(PayloadOffset) = newPayloadOffset;
return oldOffset;
}
void fb_Fallback_TraceRayEnd(RuntimeDataType runtimeData, int oldPayloadOffset)
{
REF(PayloadOffset) = oldPayloadOffset;
}
void fb_Fallback_SetPendingTriVals(RuntimeDataType runtimeData, unsigned shaderRecordOffset, unsigned primitiveIndex, unsigned instanceIndex, unsigned instanceID, float t, unsigned hitKind)
{
REF(PendingShaderRecordOffset) = shaderRecordOffset;
REF(PendingPrimitiveIndex) = primitiveIndex;
REF(PendingInstanceIndex) = instanceIndex;
REF(PendingInstanceID) = instanceID;
REF_FLT(PendingRayTCurrent) = t;
REF(PendingHitKind) = hitKind;
}
void fb_Fallback_SetPendingCustomVals(RuntimeDataType runtimeData, unsigned shaderRecordOffset, unsigned primitiveIndex, unsigned instanceIndex, unsigned instanceID)
{
REF(PendingShaderRecordOffset) = shaderRecordOffset;
REF(PendingPrimitiveIndex) = primitiveIndex;
REF(PendingInstanceIndex) = instanceIndex;
REF(PendingInstanceID) = instanceID;
}
void fb_Fallback_CommitHit(RuntimeDataType runtimeData)
{
REF_FLT(RayTCurrent) = REF_FLT(PendingRayTCurrent);
REF(ShaderRecordOffset) = REF(PendingShaderRecordOffset);
REF(PrimitiveIndex) = REF(PendingPrimitiveIndex);
REF(InstanceIndex) = REF(PendingInstanceIndex);
REF(InstanceID) = REF(PendingInstanceID);
REF(HitKind) = REF(PendingHitKind);
int PendingAttrOffset = REF(PendingAttrOffset);
REF(PendingAttrOffset) = REF(CommittedAttrOffset);
REF(CommittedAttrOffset) = PendingAttrOffset;
}
int fb_Fallback_RuntimeDataLoadInt(RuntimeDataType runtimeData, int offset)
{
return (*runtimeData->Stack)[offset];
}
void fb_Fallback_RuntimeDataStoreInt(RuntimeDataType runtimeData, int offset, int val)
{
(*runtimeData->Stack)[offset] = val;
}
unsigned fb_dxop_dispatchRaysIndex(RuntimeDataType runtimeData, byte i)
{
return REF(DispatchRaysIndex[i]);
}
unsigned fb_dxop_dispatchRaysDimensions(RuntimeDataType runtimeData, byte i)
{
return REF(DispatchRaysDimensions[i]);
}
float fb_dxop_rayTMin(RuntimeDataType runtimeData)
{
return REF_FLT(RayTMin);
}
float fb_Fallback_RayTMin(RuntimeDataType runtimeData)
{
return REF_FLT(RayTMin);
}
void fb_Fallback_SetRayTMin(RuntimeDataType runtimeData, float t)
{
REF_FLT(RayTMin) = t;
}
float fb_dxop_rayTCurrent(RuntimeDataType runtimeData)
{
return REF_FLT(RayTCurrent);
}
float fb_Fallback_RayTCurrent(RuntimeDataType runtimeData)
{
return REF_FLT(RayTCurrent);
}
void fb_Fallback_SetRayTCurrent(RuntimeDataType runtimeData, float t)
{
REF_FLT(RayTCurrent) = t;
}
unsigned fb_dxop_rayFlags(RuntimeDataType runtimeData)
{
return REF(RayFlags);
}
unsigned fb_Fallback_RayFlags(RuntimeDataType runtimeData)
{
return REF(RayFlags);
}
void fb_Fallback_SetRayFlags(RuntimeDataType runtimeData, unsigned flags)
{
REF(RayFlags) = flags;
}
float fb_dxop_worldRayOrigin(RuntimeDataType runtimeData, byte i)
{
return REF_FLT(WorldRayOrigin[i]);
}
float fb_Fallback_WorldRayOrigin(RuntimeDataType runtimeData, byte i)
{
return REF_FLT(WorldRayOrigin[i]);
}
void fb_Fallback_SetWorldRayOrigin(RuntimeDataType runtimeData, float x, float y, float z)
{
REF_FLT(WorldRayOrigin[0]) = x;
REF_FLT(WorldRayOrigin[1]) = y;
REF_FLT(WorldRayOrigin[2]) = z;
}
float fb_dxop_worldRayDirection(RuntimeDataType runtimeData, byte i)
{
return REF_FLT(WorldRayDirection[i]);
}
float fb_Fallback_WorldRayDirection(RuntimeDataType runtimeData, byte i)
{
return REF_FLT(WorldRayDirection[i]);
}
void fb_Fallback_SetWorldRayDirection(RuntimeDataType runtimeData, float x, float y, float z)
{
REF_FLT(WorldRayDirection[0]) = x;
REF_FLT(WorldRayDirection[1]) = y;
REF_FLT(WorldRayDirection[2]) = z;
}
float fb_dxop_objectRayOrigin(RuntimeDataType runtimeData, byte i)
{
return REF_FLT(ObjectRayOrigin[i]);
}
float fb_Fallback_ObjectRayOrigin(RuntimeDataType runtimeData, byte i)
{
return REF_FLT(ObjectRayOrigin[i]);
}
void fb_Fallback_SetObjectRayOrigin(RuntimeDataType runtimeData, float x, float y, float z)
{
REF_FLT(ObjectRayOrigin[0]) = x;
REF_FLT(ObjectRayOrigin[1]) = y;
REF_FLT(ObjectRayOrigin[2]) = z;
}
float fb_dxop_objectRayDirection(RuntimeDataType runtimeData, byte i)
{
return REF_FLT(ObjectRayDirection[i]);
}
float fb_Fallback_ObjectRayDirection(RuntimeDataType runtimeData, byte i)
{
return REF_FLT(ObjectRayDirection[i]);
}
void fb_Fallback_SetObjectRayDirection(RuntimeDataType runtimeData, float x, float y, float z)
{
REF_FLT(ObjectRayDirection[0]) = x;
REF_FLT(ObjectRayDirection[1]) = y;
REF_FLT(ObjectRayDirection[2]) = z;
}
float fb_dxop_objectToWorld(RuntimeDataType runtimeData, int r, byte c)
{
int i = r * 4 + c;
return REF_FLT_OFS(ObjectToWorld, i);
}
void fb_Fallback_SetObjectToWorld(RuntimeDataType runtimeData, float12 M)
{
REF_FLT_OFS(ObjectToWorld, 0) = M[0];
REF_FLT_OFS(ObjectToWorld, 1) = M[1];
REF_FLT_OFS(ObjectToWorld, 2) = M[2];
REF_FLT_OFS(ObjectToWorld, 3) = M[3];
REF_FLT_OFS(ObjectToWorld, 4) = M[4];
REF_FLT_OFS(ObjectToWorld, 5) = M[5];
REF_FLT_OFS(ObjectToWorld, 6) = M[6];
REF_FLT_OFS(ObjectToWorld, 7) = M[7];
REF_FLT_OFS(ObjectToWorld, 8) = M[8];
REF_FLT_OFS(ObjectToWorld, 9) = M[9];
REF_FLT_OFS(ObjectToWorld, 10) = M[10];
REF_FLT_OFS(ObjectToWorld, 11) = M[11];
}
float fb_dxop_worldToObject(RuntimeDataType runtimeData, int r, byte c)
{
int i = r * 4 + c;
return REF_FLT_OFS(WorldToObject, i);
}
void fb_Fallback_SetWorldToObject(RuntimeDataType runtimeData, float12 M)
{
REF_FLT_OFS(WorldToObject, 0) = M[0];
REF_FLT_OFS(WorldToObject, 1) = M[1];
REF_FLT_OFS(WorldToObject, 2) = M[2];
REF_FLT_OFS(WorldToObject, 3) = M[3];
REF_FLT_OFS(WorldToObject, 4) = M[4];
REF_FLT_OFS(WorldToObject, 5) = M[5];
REF_FLT_OFS(WorldToObject, 6) = M[6];
REF_FLT_OFS(WorldToObject, 7) = M[7];
REF_FLT_OFS(WorldToObject, 8) = M[8];
REF_FLT_OFS(WorldToObject, 9) = M[9];
REF_FLT_OFS(WorldToObject, 10) = M[10];
REF_FLT_OFS(WorldToObject, 11) = M[11];
}
unsigned fb_dxop_primitiveIndex(RuntimeDataType runtimeData)
{
return REF(PrimitiveIndex);
}
unsigned fb_Fallback_PrimitiveIndex(RuntimeDataType runtimeData)
{
return REF(PrimitiveIndex);
}
void fb_Fallback_SetPrimitiveIndex(RuntimeDataType runtimeData, unsigned i)
{
REF(PrimitiveIndex) = i;
}
unsigned fb_Fallback_ShaderRecordOffset(RuntimeDataType runtimeData)
{
return REF(ShaderRecordOffset);
}
void fb_Fallback_SetShaderRecordOffset(RuntimeDataType runtimeData, unsigned shaderRecordOffset)
{
REF(ShaderRecordOffset) = shaderRecordOffset;
}
unsigned fb_dxop_instanceIndex(RuntimeDataType runtimeData)
{
return REF(InstanceIndex);
}
unsigned fb_Fallback_InstanceIndex(RuntimeDataType runtimeData)
{
return REF(InstanceIndex);
}
void fb_Fallback_SetInstanceIndex(RuntimeDataType runtimeData, unsigned i)
{
REF(InstanceIndex) = i;
}
unsigned fb_dxop_instanceID(RuntimeDataType runtimeData)
{
return REF(InstanceID);
}
unsigned fb_Fallback_InstanceID(RuntimeDataType runtimeData)
{
return REF(InstanceID);
}
void fb_Fallback_SetInstanceID(RuntimeDataType runtimeData, unsigned i)
{
REF(InstanceID) = i;
}
unsigned fb_dxop_hitKind(RuntimeDataType runtimeData)
{
return REF(HitKind);
}
unsigned fb_Fallback_HitKind(RuntimeDataType runtimeData)
{
return REF(HitKind);
}
void fb_Fallback_SetHitKind(RuntimeDataType runtimeData, unsigned i)
{
REF(HitKind) = i;
}
float fb_dxop_pending_rayTCurrent(RuntimeDataType runtimeData)
{
return REF_FLT(PendingRayTCurrent);
}
void fb_Fallback_SetPendingRayTCurrent(RuntimeDataType runtimeData, float t)
{
REF_FLT(PendingRayTCurrent) = t;
}
unsigned fb_dxop_pending_primitiveID(RuntimeDataType runtimeData)
//unsigned fb_dxop_pending_primitiveIndex(RuntimeDataType runtimeData)
{
return REF(PendingPrimitiveIndex);
}
unsigned fb_Fallback_PendingShaderRecordOffset(RuntimeDataType runtimeData)
{
return REF(PendingShaderRecordOffset);
}
unsigned fb_dxop_pending_instanceIndex(RuntimeDataType runtimeData)
{
return REF(PendingInstanceIndex);
}
unsigned fb_dxop_pending_instanceID(RuntimeDataType runtimeData)
{
return REF(PendingInstanceID);
}
unsigned fb_dxop_pending_hitKind(RuntimeDataType runtimeData)
{
return REF(PendingHitKind);
}
void fb_Fallback_SetPendingHitKind(RuntimeDataType runtimeData, unsigned i)
{
REF(PendingHitKind) = i;
}
unsigned fb_Fallback_GroupIndex(RuntimeDataType runtimeData)
{
return REF(GroupIndex);
}
int fb_Fallback_AnyHitResult(RuntimeDataType runtimeData)
{
return REF(AnyHitResult);
}
void fb_Fallback_SetAnyHitResult(RuntimeDataType runtimeData, int result)
{
REF(AnyHitResult) = result;
}
int fb_Fallback_AnyHitStateId(RuntimeDataType runtimeData)
{
return REF(AnyHitStateId);
}
void fb_Fallback_SetAnyHitStateId(RuntimeDataType runtimeData, int id)
{
REF(AnyHitStateId) = id;
}
#endif
static const char *runtimeString[] = {R"AAA(
target datalayout = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f:64:64-n8:16:32:64"
target triple = "dxil-ms-dx"
%struct.RuntimeDataStruct = type { [2 x i32], [2 x i32], float, float, i32, [3 x float], [3 x float], [3 x float], [3 x float], [12 x float], [12 x float], i32, i32, i32, i32, i32, float, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, [256 x i32]* }
%struct.TraceRaySpills_ClosestHit = type { float, float, i32, [3 x float], [3 x float], [3 x float], [3 x float], i32, i32, i32, i32, i32 }
%struct.TraceRaySpills_Miss = type { float, float, i32, [3 x float], [3 x float], i32 }
; Function Attrs: nounwind
define void @stackInit(%struct.RuntimeDataStruct* %runtimeData, [256 x i32]* %theStack, i32 %stackSize) #0 {
entry:
%Stack = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 29
store [256 x i32]* %theStack, [256 x i32]** %Stack, align 4
%div = udiv i32 %stackSize, 4
%sub = sub i32 %div, 1
%StackOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 28
store i32 %sub, i32* %StackOffset, align 4
%PayloadOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 25
store i32 1111, i32* %PayloadOffset, align 4
%CommittedAttrOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 26
store i32 2222, i32* %CommittedAttrOffset, align 4
%PendingAttrOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 27
store i32 3333, i32* %PendingAttrOffset, align 4
ret void
}
; Function Attrs: nounwind
define void @stackFramePush(%struct.RuntimeDataStruct* %runtimeData, i32 %size) #0 {
entry:
%StackOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 28
%0 = load i32, i32* %StackOffset, align 4
%sub = sub nsw i32 %0, %size
store i32 %sub, i32* %StackOffset, align 4
ret void
}
; Function Attrs: nounwind
define void @stackFramePop(%struct.RuntimeDataStruct* %runtimeData, i32 %size) #0 {
entry:
%StackOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 28
%0 = load i32, i32* %StackOffset, align 4
%add = add nsw i32 %0, %size
store i32 %add, i32* %StackOffset, align 4
ret void
}
; Function Attrs: nounwind
define i32 @stackFrameOffset(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%StackOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 28
%0 = load i32, i32* %StackOffset, align 4
ret i32 %0
}
; Function Attrs: nounwind
define i32 @payloadOffset(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%PayloadOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 25
%0 = load i32, i32* %PayloadOffset, align 4
ret i32 %0
}
; Function Attrs: nounwind
define i32 @committedAttrOffset(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%CommittedAttrOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 26
%0 = load i32, i32* %CommittedAttrOffset, align 4
ret i32 %0
}
; Function Attrs: nounwind
define i32 @pendingAttrOffset(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%PendingAttrOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 27
%0 = load i32, i32* %PendingAttrOffset, align 4
ret i32 %0
}
; Function Attrs: nounwind
define i32* @stackIntPtr(%struct.RuntimeDataStruct* %runtimeData, i32 %baseOffset, i32 %offset) #0 {
entry:
%add = add nsw i32 %baseOffset, %offset
%Stack = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 29
%0 = load [256 x i32]*, [256 x i32]** %Stack, align 4
%arrayidx = getelementptr inbounds [256 x i32], [256 x i32]* %0, i32 0, i32 %add
ret i32* %arrayidx
}
; Function Attrs: nounwind
define void @traceFramePush(%struct.RuntimeDataStruct* %runtimeData, i32 %attrSize) #0 {
entry:
%CommittedAttrOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 26
%0 = load i32, i32* %CommittedAttrOffset, align 4
%StackOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 28
%1 = load i32, i32* %StackOffset, align 4
%add = add nsw i32 %1, -1
%Stack = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 29
%2 = load [256 x i32]*, [256 x i32]** %Stack, align 4
%arrayidx = getelementptr inbounds [256 x i32], [256 x i32]* %2, i32 0, i32 %add
store i32 %0, i32* %arrayidx, align 4
%PendingAttrOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 27
%3 = load i32, i32* %PendingAttrOffset, align 4
%StackOffset1 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 28
%4 = load i32, i32* %StackOffset1, align 4
%add2 = add nsw i32 %4, -2
%Stack3 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 29
%5 = load [256 x i32]*, [256 x i32]** %Stack3, align 4
%arrayidx4 = getelementptr inbounds [256 x i32], [256 x i32]* %5, i32 0, i32 %add2
store i32 %3, i32* %arrayidx4, align 4
%StackOffset5 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 28
%6 = load i32, i32* %StackOffset5, align 4
%sub = sub nsw i32 %6, 2
%sub6 = sub nsw i32 %sub, %attrSize
%CommittedAttrOffset7 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 26
store i32 %sub6, i32* %CommittedAttrOffset7, align 4
%StackOffset8 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 28
%7 = load i32, i32* %StackOffset8, align 4
%sub9 = sub nsw i32 %7, 2
%mul = mul nsw i32 2, %attrSize
%sub10 = sub nsw i32 %sub9, %mul
%PendingAttrOffset11 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 27
store i32 %sub10, i32* %PendingAttrOffset11, align 4
ret void
}
; Function Attrs: nounwind
define void @traceFramePop(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%StackOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 28
%0 = load i32, i32* %StackOffset, align 4
%add = add nsw i32 %0, -1
%Stack = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 29
%1 = load [256 x i32]*, [256 x i32]** %Stack, align 4
%arrayidx = getelementptr inbounds [256 x i32], [256 x i32]* %1, i32 0, i32 %add
%2 = load i32, i32* %arrayidx, align 4
%CommittedAttrOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 26
store i32 %2, i32* %CommittedAttrOffset, align 4
%StackOffset1 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 28
%3 = load i32, i32* %StackOffset1, align 4
%add2 = add nsw i32 %3, -2
%Stack3 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 29
%4 = load [256 x i32]*, [256 x i32]** %Stack3, align 4
%arrayidx4 = getelementptr inbounds [256 x i32], [256 x i32]* %4, i32 0, i32 %add2
%5 = load i32, i32* %arrayidx4, align 4
%PendingAttrOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 27
store i32 %5, i32* %PendingAttrOffset, align 4
ret void
}
; Function Attrs: nounwind
define void @traceRaySave_ClosestHit(%struct.RuntimeDataStruct* %runtimeData, %struct.TraceRaySpills_ClosestHit* %spills) #0 {
entry:
%RayFlags = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 4
%0 = load i32, i32* %RayFlags, align 4
%RayFlags1 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 2
store i32 %0, i32* %RayFlags1, align 4
%RayTCurrent = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 3
%1 = load float, float* %RayTCurrent, align 4
%RayTCurrent2 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 1
store float %1, float* %RayTCurrent2, align 4
%RayTMin = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 2
%2 = load float, float* %RayTMin, align 4
%RayTMin3 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 0
store float %2, float* %RayTMin3, align 4
%WorldRayOrigin = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin, i32 0, i32 0
%3 = load float, float* %arrayidx, align 4
%WorldRayOrigin4 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 3
%arrayidx5 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin4, i32 0, i32 0
store float %3, float* %arrayidx5, align 4
%WorldRayOrigin6 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx7 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin6, i32 0, i32 1
%4 = load float, float* %arrayidx7, align 4
%WorldRayOrigin8 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 3
%arrayidx9 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin8, i32 0, i32 1
store float %4, float* %arrayidx9, align 4
%WorldRayOrigin10 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
)AAA",
R"AAA(
%arrayidx11 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin10, i32 0, i32 2
%5 = load float, float* %arrayidx11, align 4
%WorldRayOrigin12 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 3
%arrayidx13 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin12, i32 0, i32 2
store float %5, float* %arrayidx13, align 4
%WorldRayDirection = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx14 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection, i32 0, i32 0
%6 = load float, float* %arrayidx14, align 4
%WorldRayDirection15 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 4
%arrayidx16 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection15, i32 0, i32 0
store float %6, float* %arrayidx16, align 4
%WorldRayDirection17 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx18 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection17, i32 0, i32 1
%7 = load float, float* %arrayidx18, align 4
%WorldRayDirection19 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 4
%arrayidx20 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection19, i32 0, i32 1
store float %7, float* %arrayidx20, align 4
%WorldRayDirection21 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx22 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection21, i32 0, i32 2
%8 = load float, float* %arrayidx22, align 4
%WorldRayDirection23 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 4
%arrayidx24 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection23, i32 0, i32 2
store float %8, float* %arrayidx24, align 4
%ObjectRayOrigin = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 7
%arrayidx25 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin, i32 0, i32 0
%9 = load float, float* %arrayidx25, align 4
%ObjectRayOrigin26 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 5
%arrayidx27 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin26, i32 0, i32 0
store float %9, float* %arrayidx27, align 4
%ObjectRayOrigin28 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 7
%arrayidx29 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin28, i32 0, i32 1
%10 = load float, float* %arrayidx29, align 4
%ObjectRayOrigin30 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 5
%arrayidx31 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin30, i32 0, i32 1
store float %10, float* %arrayidx31, align 4
%ObjectRayOrigin32 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 7
%arrayidx33 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin32, i32 0, i32 2
%11 = load float, float* %arrayidx33, align 4
%ObjectRayOrigin34 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 5
%arrayidx35 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin34, i32 0, i32 2
store float %11, float* %arrayidx35, align 4
%ObjectRayDirection = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 8
%arrayidx36 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection, i32 0, i32 0
%12 = load float, float* %arrayidx36, align 4
%ObjectRayDirection37 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 6
%arrayidx38 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection37, i32 0, i32 0
store float %12, float* %arrayidx38, align 4
%ObjectRayDirection39 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 8
%arrayidx40 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection39, i32 0, i32 1
%13 = load float, float* %arrayidx40, align 4
%ObjectRayDirection41 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 6
%arrayidx42 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection41, i32 0, i32 1
store float %13, float* %arrayidx42, align 4
%ObjectRayDirection43 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 8
%arrayidx44 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection43, i32 0, i32 2
%14 = load float, float* %arrayidx44, align 4
%ObjectRayDirection45 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 6
%arrayidx46 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection45, i32 0, i32 2
store float %14, float* %arrayidx46, align 4
%PrimitiveIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 11
%15 = load i32, i32* %PrimitiveIndex, align 4
%PrimitiveIndex47 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 7
store i32 %15, i32* %PrimitiveIndex47, align 4
%InstanceIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 12
%16 = load i32, i32* %InstanceIndex, align 4
%InstanceIndex48 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 8
store i32 %16, i32* %InstanceIndex48, align 4
%InstanceID = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 13
%17 = load i32, i32* %InstanceID, align 4
%InstanceID49 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 9
store i32 %17, i32* %InstanceID49, align 4
%HitKind = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 14
%18 = load i32, i32* %HitKind, align 4
%HitKind50 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 10
store i32 %18, i32* %HitKind50, align 4
%ShaderRecordOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 15
%19 = load i32, i32* %ShaderRecordOffset, align 4
%ShaderRecordOffset51 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 11
store i32 %19, i32* %ShaderRecordOffset51, align 4
ret void
}
; Function Attrs: nounwind
define void @traceRayRestore_ClosestHit(%struct.RuntimeDataStruct* %runtimeData, %struct.TraceRaySpills_ClosestHit* %spills) #0 {
entry:
%RayFlags = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 2
%0 = load i32, i32* %RayFlags, align 4
%RayFlags1 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 4
store i32 %0, i32* %RayFlags1, align 4
%RayTCurrent = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 1
%1 = load float, float* %RayTCurrent, align 4
%RayTCurrent2 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 3
store float %1, float* %RayTCurrent2, align 4
%RayTMin = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 0
%2 = load float, float* %RayTMin, align 4
%RayTMin3 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 2
store float %2, float* %RayTMin3, align 4
%WorldRayOrigin = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 3
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin, i32 0, i32 0
%3 = load float, float* %arrayidx, align 4
%WorldRayOrigin4 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx5 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin4, i32 0, i32 0
store float %3, float* %arrayidx5, align 4
%WorldRayOrigin6 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 3
%arrayidx7 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin6, i32 0, i32 1
%4 = load float, float* %arrayidx7, align 4
%WorldRayOrigin8 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx9 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin8, i32 0, i32 1
store float %4, float* %arrayidx9, align 4
%WorldRayOrigin10 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 3
%arrayidx11 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin10, i32 0, i32 2
%5 = load float, float* %arrayidx11, align 4
%WorldRayOrigin12 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx13 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin12, i32 0, i32 2
store float %5, float* %arrayidx13, align 4
%WorldRayDirection = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 4
)AAA",
R"AAA(
%arrayidx14 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection, i32 0, i32 0
%6 = load float, float* %arrayidx14, align 4
%WorldRayDirection15 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx16 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection15, i32 0, i32 0
store float %6, float* %arrayidx16, align 4
%WorldRayDirection17 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 4
%arrayidx18 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection17, i32 0, i32 1
%7 = load float, float* %arrayidx18, align 4
%WorldRayDirection19 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx20 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection19, i32 0, i32 1
store float %7, float* %arrayidx20, align 4
%WorldRayDirection21 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 4
%arrayidx22 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection21, i32 0, i32 2
%8 = load float, float* %arrayidx22, align 4
%WorldRayDirection23 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx24 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection23, i32 0, i32 2
store float %8, float* %arrayidx24, align 4
%ObjectRayOrigin = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 5
%arrayidx25 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin, i32 0, i32 0
%9 = load float, float* %arrayidx25, align 4
%ObjectRayOrigin26 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 7
%arrayidx27 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin26, i32 0, i32 0
store float %9, float* %arrayidx27, align 4
%ObjectRayOrigin28 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 5
%arrayidx29 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin28, i32 0, i32 1
%10 = load float, float* %arrayidx29, align 4
%ObjectRayOrigin30 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 7
%arrayidx31 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin30, i32 0, i32 1
store float %10, float* %arrayidx31, align 4
%ObjectRayOrigin32 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 5
%arrayidx33 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin32, i32 0, i32 2
%11 = load float, float* %arrayidx33, align 4
%ObjectRayOrigin34 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 7
%arrayidx35 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin34, i32 0, i32 2
store float %11, float* %arrayidx35, align 4
%ObjectRayDirection = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 6
%arrayidx36 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection, i32 0, i32 0
%12 = load float, float* %arrayidx36, align 4
%ObjectRayDirection37 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 8
%arrayidx38 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection37, i32 0, i32 0
store float %12, float* %arrayidx38, align 4
%ObjectRayDirection39 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 6
%arrayidx40 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection39, i32 0, i32 1
%13 = load float, float* %arrayidx40, align 4
%ObjectRayDirection41 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 8
%arrayidx42 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection41, i32 0, i32 1
store float %13, float* %arrayidx42, align 4
%ObjectRayDirection43 = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 6
%arrayidx44 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection43, i32 0, i32 2
%14 = load float, float* %arrayidx44, align 4
%ObjectRayDirection45 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 8
%arrayidx46 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection45, i32 0, i32 2
store float %14, float* %arrayidx46, align 4
%PrimitiveIndex = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 7
%15 = load i32, i32* %PrimitiveIndex, align 4
%PrimitiveIndex47 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 11
store i32 %15, i32* %PrimitiveIndex47, align 4
%InstanceIndex = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 8
%16 = load i32, i32* %InstanceIndex, align 4
%InstanceIndex48 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 12
store i32 %16, i32* %InstanceIndex48, align 4
%InstanceID = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 9
%17 = load i32, i32* %InstanceID, align 4
%InstanceID49 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 13
store i32 %17, i32* %InstanceID49, align 4
%HitKind = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 10
%18 = load i32, i32* %HitKind, align 4
%HitKind50 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 14
store i32 %18, i32* %HitKind50, align 4
%ShaderRecordOffset = getelementptr inbounds %struct.TraceRaySpills_ClosestHit, %struct.TraceRaySpills_ClosestHit* %spills, i32 0, i32 11
%19 = load i32, i32* %ShaderRecordOffset, align 4
%ShaderRecordOffset51 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 15
store i32 %19, i32* %ShaderRecordOffset51, align 4
ret void
}
; Function Attrs: nounwind
define void @traceRaySave_Miss(%struct.RuntimeDataStruct* %runtimeData, %struct.TraceRaySpills_Miss* %spills) #0 {
entry:
%RayFlags = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 4
%0 = load i32, i32* %RayFlags, align 4
%RayFlags1 = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 2
store i32 %0, i32* %RayFlags1, align 4
%RayTCurrent = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 3
%1 = load float, float* %RayTCurrent, align 4
%RayTCurrent2 = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 1
store float %1, float* %RayTCurrent2, align 4
%RayTMin = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 2
%2 = load float, float* %RayTMin, align 4
%RayTMin3 = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 0
store float %2, float* %RayTMin3, align 4
%WorldRayOrigin = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin, i32 0, i32 0
%3 = load float, float* %arrayidx, align 4
%WorldRayOrigin4 = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 3
%arrayidx5 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin4, i32 0, i32 0
store float %3, float* %arrayidx5, align 4
%WorldRayOrigin6 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx7 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin6, i32 0, i32 1
%4 = load float, float* %arrayidx7, align 4
%WorldRayOrigin8 = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 3
%arrayidx9 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin8, i32 0, i32 1
store float %4, float* %arrayidx9, align 4
%WorldRayOrigin10 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx11 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin10, i32 0, i32 2
%5 = load float, float* %arrayidx11, align 4
%WorldRayOrigin12 = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 3
%arrayidx13 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin12, i32 0, i32 2
store float %5, float* %arrayidx13, align 4
%WorldRayDirection = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx14 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection, i32 0, i32 0
%6 = load float, float* %arrayidx14, align 4
%WorldRayDirection15 = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 4
%arrayidx16 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection15, i32 0, i32 0
store float %6, float* %arrayidx16, align 4
%WorldRayDirection17 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx18 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection17, i32 0, i32 1
)AAA",
R"AAA(
%7 = load float, float* %arrayidx18, align 4
%WorldRayDirection19 = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 4
%arrayidx20 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection19, i32 0, i32 1
store float %7, float* %arrayidx20, align 4
%WorldRayDirection21 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx22 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection21, i32 0, i32 2
%8 = load float, float* %arrayidx22, align 4
%WorldRayDirection23 = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 4
%arrayidx24 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection23, i32 0, i32 2
store float %8, float* %arrayidx24, align 4
%ShaderRecordOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 15
%9 = load i32, i32* %ShaderRecordOffset, align 4
%ShaderRecordOffset25 = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 5
store i32 %9, i32* %ShaderRecordOffset25, align 4
ret void
}
; Function Attrs: nounwind
define void @traceRayRestore_Miss(%struct.RuntimeDataStruct* %runtimeData, %struct.TraceRaySpills_Miss* %spills) #0 {
entry:
%RayFlags = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 2
%0 = load i32, i32* %RayFlags, align 4
%RayFlags1 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 4
store i32 %0, i32* %RayFlags1, align 4
%RayTCurrent = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 1
%1 = load float, float* %RayTCurrent, align 4
%RayTCurrent2 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 3
store float %1, float* %RayTCurrent2, align 4
%RayTMin = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 0
%2 = load float, float* %RayTMin, align 4
%RayTMin3 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 2
store float %2, float* %RayTMin3, align 4
%WorldRayOrigin = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 3
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin, i32 0, i32 0
%3 = load float, float* %arrayidx, align 4
%WorldRayOrigin4 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx5 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin4, i32 0, i32 0
store float %3, float* %arrayidx5, align 4
%WorldRayOrigin6 = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 3
%arrayidx7 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin6, i32 0, i32 1
%4 = load float, float* %arrayidx7, align 4
%WorldRayOrigin8 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx9 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin8, i32 0, i32 1
store float %4, float* %arrayidx9, align 4
%WorldRayOrigin10 = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 3
%arrayidx11 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin10, i32 0, i32 2
%5 = load float, float* %arrayidx11, align 4
%WorldRayOrigin12 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx13 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin12, i32 0, i32 2
store float %5, float* %arrayidx13, align 4
%WorldRayDirection = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 4
%arrayidx14 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection, i32 0, i32 0
%6 = load float, float* %arrayidx14, align 4
%WorldRayDirection15 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx16 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection15, i32 0, i32 0
store float %6, float* %arrayidx16, align 4
%WorldRayDirection17 = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 4
%arrayidx18 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection17, i32 0, i32 1
%7 = load float, float* %arrayidx18, align 4
%WorldRayDirection19 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx20 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection19, i32 0, i32 1
store float %7, float* %arrayidx20, align 4
%WorldRayDirection21 = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 4
%arrayidx22 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection21, i32 0, i32 2
%8 = load float, float* %arrayidx22, align 4
%WorldRayDirection23 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx24 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection23, i32 0, i32 2
store float %8, float* %arrayidx24, align 4
%ShaderRecordOffset = getelementptr inbounds %struct.TraceRaySpills_Miss, %struct.TraceRaySpills_Miss* %spills, i32 0, i32 5
%9 = load i32, i32* %ShaderRecordOffset, align 4
%ShaderRecordOffset25 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 15
store i32 %9, i32* %ShaderRecordOffset25, align 4
ret void
}
; Function Attrs: nounwind
define void @fb_Fallback_Scheduler(i32 %initialStateId, i32 %dimx, i32 %dimy) #0 {
entry:
%theRuntimeData = alloca %struct.RuntimeDataStruct, align 4
%call = call [256 x i32]* @rewrite_createStack()
%call1 = call i8* @rewrite_setLaunchParams(%struct.RuntimeDataStruct* %theRuntimeData, i32 %dimx, i32 %dimy)
%DispatchRaysIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %theRuntimeData, i32 0, i32 0
%arrayidx = getelementptr inbounds [2 x i32], [2 x i32]* %DispatchRaysIndex, i32 0, i32 0
%0 = load i32, i32* %arrayidx, align 4
%DispatchRaysDimensions = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %theRuntimeData, i32 0, i32 1
%arrayidx2 = getelementptr inbounds [2 x i32], [2 x i32]* %DispatchRaysDimensions, i32 0, i32 0
%1 = load i32, i32* %arrayidx2, align 4
%cmp = icmp sge i32 %0, %1
br i1 %cmp, label %if.then, label %lor.lhs.false
lor.lhs.false: ; preds = %entry
%DispatchRaysIndex3 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %theRuntimeData, i32 0, i32 0
%arrayidx4 = getelementptr inbounds [2 x i32], [2 x i32]* %DispatchRaysIndex3, i32 0, i32 1
%2 = load i32, i32* %arrayidx4, align 4
%DispatchRaysDimensions5 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %theRuntimeData, i32 0, i32 1
%arrayidx6 = getelementptr inbounds [2 x i32], [2 x i32]* %DispatchRaysDimensions5, i32 0, i32 1
%3 = load i32, i32* %arrayidx6, align 4
%cmp7 = icmp sge i32 %2, %3
br i1 %cmp7, label %if.then, label %if.end
if.then: ; preds = %lor.lhs.false, %entry
br label %while.end
if.end: ; preds = %lor.lhs.false
%call8 = call i32 @rewrite_getStackSize()
call void @stackInit(%struct.RuntimeDataStruct* %theRuntimeData, [256 x i32]* %call, i32 %call8)
%call9 = call i32 @stackFrameOffset(%struct.RuntimeDataStruct* %theRuntimeData)
%call10 = call i32* @stackIntPtr(%struct.RuntimeDataStruct* %theRuntimeData, i32 %call9, i32 0)
store i32 -1, i32* %call10, align 4
br label %while.cond
while.cond: ; preds = %while.body, %if.end
%stateId.0 = phi i32 [ %initialStateId, %if.end ], [ %call12, %while.body ]
%cmp11 = icmp sge i32 %stateId.0, 0
br i1 %cmp11, label %while.body, label %while.end
while.body: ; preds = %while.cond
%call12 = call i32 @rewrite_dispatch(%struct.RuntimeDataStruct* %theRuntimeData, i32 %stateId.0)
br label %while.cond
while.end: ; preds = %while.cond, %if.then
ret void
}
declare [256 x i32]* @rewrite_createStack() #1
declare i8* @rewrite_setLaunchParams(%struct.RuntimeDataStruct*, i32, i32) #1
declare i32 @rewrite_getStackSize() #1
declare i32 @rewrite_dispatch(%struct.RuntimeDataStruct*, i32) #1
; Function Attrs: nounwind
define void @fb_Fallback_SetLaunchParams(%struct.RuntimeDataStruct* %runtimeData, i32 %DTidx, i32 %DTidy, i32 %dimx, i32 %dimy, i32 %groupIndex) #0 {
entry:
%DispatchRaysIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 0
%arrayidx = getelementptr inbounds [2 x i32], [2 x i32]* %DispatchRaysIndex, i32 0, i32 0
store i32 %DTidx, i32* %arrayidx, align 4
%DispatchRaysIndex1 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 0
%arrayidx2 = getelementptr inbounds [2 x i32], [2 x i32]* %DispatchRaysIndex1, i32 0, i32 1
store i32 %DTidy, i32* %arrayidx2, align 4
%DispatchRaysDimensions = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 1
%arrayidx3 = getelementptr inbounds [2 x i32], [2 x i32]* %DispatchRaysDimensions, i32 0, i32 0
store i32 %dimx, i32* %arrayidx3, align 4
%DispatchRaysDimensions4 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 1
%arrayidx5 = getelementptr inbounds [2 x i32], [2 x i32]* %DispatchRaysDimensions4, i32 0, i32 1
)AAA",
R"AAA(
store i32 %dimy, i32* %arrayidx5, align 4
%GroupIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 22
store i32 %groupIndex, i32* %GroupIndex, align 4
ret void
}
; Function Attrs: nounwind
define i32 @fb_Fallback_TraceRayBegin(%struct.RuntimeDataStruct* %runtimeData, i32 %rayFlags, float %ox, float %oy, float %oz, float %tmin, float %dx, float %dy, float %dz, float %tmax, i32 %newPayloadOffset) #0 {
entry:
%RayFlags = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 4
store i32 %rayFlags, i32* %RayFlags, align 4
%WorldRayOrigin = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin, i32 0, i32 0
store float %ox, float* %arrayidx, align 4
%WorldRayOrigin1 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx2 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin1, i32 0, i32 1
store float %oy, float* %arrayidx2, align 4
%WorldRayOrigin3 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx4 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin3, i32 0, i32 2
store float %oz, float* %arrayidx4, align 4
%WorldRayDirection = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx5 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection, i32 0, i32 0
store float %dx, float* %arrayidx5, align 4
%WorldRayDirection6 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx7 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection6, i32 0, i32 1
store float %dy, float* %arrayidx7, align 4
%WorldRayDirection8 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx9 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection8, i32 0, i32 2
store float %dz, float* %arrayidx9, align 4
%RayTCurrent = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 3
store float %tmax, float* %RayTCurrent, align 4
%RayTMin = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 2
store float %tmin, float* %RayTMin, align 4
%PayloadOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 25
%0 = load i32, i32* %PayloadOffset, align 4
%PayloadOffset10 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 25
store i32 %newPayloadOffset, i32* %PayloadOffset10, align 4
ret i32 %0
}
; Function Attrs: nounwind
define void @fb_Fallback_TraceRayEnd(%struct.RuntimeDataStruct* %runtimeData, i32 %oldPayloadOffset) #0 {
entry:
%PayloadOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 25
store i32 %oldPayloadOffset, i32* %PayloadOffset, align 4
ret void
}
; Function Attrs: nounwind
define void @fb_Fallback_SetPendingTriVals(%struct.RuntimeDataStruct* %runtimeData, i32 %shaderRecordOffset, i32 %primitiveIndex, i32 %instanceIndex, i32 %instanceID, float %t, i32 %hitKind) #0 {
entry:
%PendingShaderRecordOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 21
store i32 %shaderRecordOffset, i32* %PendingShaderRecordOffset, align 4
%PendingPrimitiveIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 17
store i32 %primitiveIndex, i32* %PendingPrimitiveIndex, align 4
%PendingInstanceIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 18
store i32 %instanceIndex, i32* %PendingInstanceIndex, align 4
%PendingInstanceID = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 19
store i32 %instanceID, i32* %PendingInstanceID, align 4
%PendingRayTCurrent = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 16
store float %t, float* %PendingRayTCurrent, align 4
%PendingHitKind = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 20
store i32 %hitKind, i32* %PendingHitKind, align 4
ret void
}
; Function Attrs: nounwind
define void @fb_Fallback_SetPendingCustomVals(%struct.RuntimeDataStruct* %runtimeData, i32 %shaderRecordOffset, i32 %primitiveIndex, i32 %instanceIndex, i32 %instanceID) #0 {
entry:
%PendingShaderRecordOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 21
store i32 %shaderRecordOffset, i32* %PendingShaderRecordOffset, align 4
%PendingPrimitiveIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 17
store i32 %primitiveIndex, i32* %PendingPrimitiveIndex, align 4
%PendingInstanceIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 18
store i32 %instanceIndex, i32* %PendingInstanceIndex, align 4
%PendingInstanceID = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 19
store i32 %instanceID, i32* %PendingInstanceID, align 4
ret void
}
; Function Attrs: nounwind
define void @fb_Fallback_CommitHit(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%PendingRayTCurrent = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 16
%0 = load float, float* %PendingRayTCurrent, align 4
%RayTCurrent = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 3
store float %0, float* %RayTCurrent, align 4
%PendingShaderRecordOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 21
%1 = load i32, i32* %PendingShaderRecordOffset, align 4
%ShaderRecordOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 15
store i32 %1, i32* %ShaderRecordOffset, align 4
%PendingPrimitiveIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 17
%2 = load i32, i32* %PendingPrimitiveIndex, align 4
%PrimitiveIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 11
store i32 %2, i32* %PrimitiveIndex, align 4
%PendingInstanceIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 18
%3 = load i32, i32* %PendingInstanceIndex, align 4
%InstanceIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 12
store i32 %3, i32* %InstanceIndex, align 4
%PendingInstanceID = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 19
%4 = load i32, i32* %PendingInstanceID, align 4
%InstanceID = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 13
store i32 %4, i32* %InstanceID, align 4
%PendingHitKind = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 20
%5 = load i32, i32* %PendingHitKind, align 4
%HitKind = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 14
store i32 %5, i32* %HitKind, align 4
%PendingAttrOffset1 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 27
%6 = load i32, i32* %PendingAttrOffset1, align 4
%CommittedAttrOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 26
%7 = load i32, i32* %CommittedAttrOffset, align 4
%PendingAttrOffset2 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 27
store i32 %7, i32* %PendingAttrOffset2, align 4
%CommittedAttrOffset3 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 26
store i32 %6, i32* %CommittedAttrOffset3, align 4
ret void
}
; Function Attrs: nounwind
define i32 @fb_Fallback_RuntimeDataLoadInt(%struct.RuntimeDataStruct* %runtimeData, i32 %offset) #0 {
entry:
%Stack = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 29
%0 = load [256 x i32]*, [256 x i32]** %Stack, align 4
%arrayidx = getelementptr inbounds [256 x i32], [256 x i32]* %0, i32 0, i32 %offset
%1 = load i32, i32* %arrayidx, align 4
ret i32 %1
}
; Function Attrs: nounwind
define void @fb_Fallback_RuntimeDataStoreInt(%struct.RuntimeDataStruct* %runtimeData, i32 %offset, i32 %val) #0 {
entry:
%Stack = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 29
%0 = load [256 x i32]*, [256 x i32]** %Stack, align 4
%arrayidx = getelementptr inbounds [256 x i32], [256 x i32]* %0, i32 0, i32 %offset
store i32 %val, i32* %arrayidx, align 4
ret void
}
; Function Attrs: nounwind
define i32 @fb_dxop_dispatchRaysIndex(%struct.RuntimeDataStruct* %runtimeData, i8 zeroext %i) #0 {
entry:
%idxprom = zext i8 %i to i32
%DispatchRaysIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 0
%arrayidx = getelementptr inbounds [2 x i32], [2 x i32]* %DispatchRaysIndex, i32 0, i32 %idxprom
%0 = load i32, i32* %arrayidx, align 4
ret i32 %0
}
; Function Attrs: nounwind
define i32 @fb_dxop_dispatchRaysDimensions(%struct.RuntimeDataStruct* %runtimeData, i8 zeroext %i) #0 {
)AAA",
R"AAA(
entry:
%idxprom = zext i8 %i to i32
%DispatchRaysDimensions = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 1
%arrayidx = getelementptr inbounds [2 x i32], [2 x i32]* %DispatchRaysDimensions, i32 0, i32 %idxprom
%0 = load i32, i32* %arrayidx, align 4
ret i32 %0
}
; Function Attrs: nounwind
define float @fb_dxop_rayTMin(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%RayTMin = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 2
%0 = load float, float* %RayTMin, align 4
ret float %0
}
; Function Attrs: nounwind
define float @fb_Fallback_RayTMin(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%RayTMin = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 2
%0 = load float, float* %RayTMin, align 4
ret float %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetRayTMin(%struct.RuntimeDataStruct* %runtimeData, float %t) #0 {
entry:
%RayTMin = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 2
store float %t, float* %RayTMin, align 4
ret void
}
; Function Attrs: nounwind
define float @fb_dxop_rayTCurrent(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%RayTCurrent = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 3
%0 = load float, float* %RayTCurrent, align 4
ret float %0
}
; Function Attrs: nounwind
define float @fb_Fallback_RayTCurrent(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%RayTCurrent = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 3
%0 = load float, float* %RayTCurrent, align 4
ret float %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetRayTCurrent(%struct.RuntimeDataStruct* %runtimeData, float %t) #0 {
entry:
%RayTCurrent = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 3
store float %t, float* %RayTCurrent, align 4
ret void
}
; Function Attrs: nounwind
define i32 @fb_dxop_rayFlags(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%RayFlags = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 4
%0 = load i32, i32* %RayFlags, align 4
ret i32 %0
}
; Function Attrs: nounwind
define i32 @fb_Fallback_RayFlags(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%RayFlags = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 4
%0 = load i32, i32* %RayFlags, align 4
ret i32 %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetRayFlags(%struct.RuntimeDataStruct* %runtimeData, i32 %flags) #0 {
entry:
%RayFlags = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 4
store i32 %flags, i32* %RayFlags, align 4
ret void
}
; Function Attrs: nounwind
define float @fb_dxop_worldRayOrigin(%struct.RuntimeDataStruct* %runtimeData, i8 zeroext %i) #0 {
entry:
%idxprom = zext i8 %i to i32
%WorldRayOrigin = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin, i32 0, i32 %idxprom
%0 = load float, float* %arrayidx, align 4
ret float %0
}
; Function Attrs: nounwind
define float @fb_Fallback_WorldRayOrigin(%struct.RuntimeDataStruct* %runtimeData, i8 zeroext %i) #0 {
entry:
%idxprom = zext i8 %i to i32
%WorldRayOrigin = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin, i32 0, i32 %idxprom
%0 = load float, float* %arrayidx, align 4
ret float %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetWorldRayOrigin(%struct.RuntimeDataStruct* %runtimeData, float %x, float %y, float %z) #0 {
entry:
%WorldRayOrigin = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin, i32 0, i32 0
store float %x, float* %arrayidx, align 4
%WorldRayOrigin1 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx2 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin1, i32 0, i32 1
store float %y, float* %arrayidx2, align 4
%WorldRayOrigin3 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 5
%arrayidx4 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayOrigin3, i32 0, i32 2
store float %z, float* %arrayidx4, align 4
ret void
}
; Function Attrs: nounwind
define float @fb_dxop_worldRayDirection(%struct.RuntimeDataStruct* %runtimeData, i8 zeroext %i) #0 {
entry:
%idxprom = zext i8 %i to i32
%WorldRayDirection = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection, i32 0, i32 %idxprom
%0 = load float, float* %arrayidx, align 4
ret float %0
}
; Function Attrs: nounwind
define float @fb_Fallback_WorldRayDirection(%struct.RuntimeDataStruct* %runtimeData, i8 zeroext %i) #0 {
entry:
%idxprom = zext i8 %i to i32
%WorldRayDirection = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection, i32 0, i32 %idxprom
%0 = load float, float* %arrayidx, align 4
ret float %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetWorldRayDirection(%struct.RuntimeDataStruct* %runtimeData, float %x, float %y, float %z) #0 {
entry:
%WorldRayDirection = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection, i32 0, i32 0
store float %x, float* %arrayidx, align 4
%WorldRayDirection1 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx2 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection1, i32 0, i32 1
store float %y, float* %arrayidx2, align 4
%WorldRayDirection3 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 6
%arrayidx4 = getelementptr inbounds [3 x float], [3 x float]* %WorldRayDirection3, i32 0, i32 2
store float %z, float* %arrayidx4, align 4
ret void
}
; Function Attrs: nounwind
define float @fb_dxop_objectRayOrigin(%struct.RuntimeDataStruct* %runtimeData, i8 zeroext %i) #0 {
entry:
%idxprom = zext i8 %i to i32
%ObjectRayOrigin = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 7
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin, i32 0, i32 %idxprom
%0 = load float, float* %arrayidx, align 4
ret float %0
}
; Function Attrs: nounwind
define float @fb_Fallback_ObjectRayOrigin(%struct.RuntimeDataStruct* %runtimeData, i8 zeroext %i) #0 {
entry:
%idxprom = zext i8 %i to i32
%ObjectRayOrigin = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 7
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin, i32 0, i32 %idxprom
%0 = load float, float* %arrayidx, align 4
ret float %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetObjectRayOrigin(%struct.RuntimeDataStruct* %runtimeData, float %x, float %y, float %z) #0 {
entry:
%ObjectRayOrigin = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 7
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin, i32 0, i32 0
store float %x, float* %arrayidx, align 4
%ObjectRayOrigin1 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 7
%arrayidx2 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin1, i32 0, i32 1
store float %y, float* %arrayidx2, align 4
%ObjectRayOrigin3 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 7
%arrayidx4 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayOrigin3, i32 0, i32 2
store float %z, float* %arrayidx4, align 4
ret void
}
; Function Attrs: nounwind
define float @fb_dxop_objectRayDirection(%struct.RuntimeDataStruct* %runtimeData, i8 zeroext %i) #0 {
entry:
%idxprom = zext i8 %i to i32
%ObjectRayDirection = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 8
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection, i32 0, i32 %idxprom
%0 = load float, float* %arrayidx, align 4
ret float %0
}
; Function Attrs: nounwind
define float @fb_Fallback_ObjectRayDirection(%struct.RuntimeDataStruct* %runtimeData, i8 zeroext %i) #0 {
entry:
%idxprom = zext i8 %i to i32
%ObjectRayDirection = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 8
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection, i32 0, i32 %idxprom
%0 = load float, float* %arrayidx, align 4
ret float %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetObjectRayDirection(%struct.RuntimeDataStruct* %runtimeData, float %x, float %y, float %z) #0 {
entry:
%ObjectRayDirection = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 8
%arrayidx = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection, i32 0, i32 0
store float %x, float* %arrayidx, align 4
%ObjectRayDirection1 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 8
%arrayidx2 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection1, i32 0, i32 1
)AAA",
R"AAA(
store float %y, float* %arrayidx2, align 4
%ObjectRayDirection3 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 8
%arrayidx4 = getelementptr inbounds [3 x float], [3 x float]* %ObjectRayDirection3, i32 0, i32 2
store float %z, float* %arrayidx4, align 4
ret void
}
; Function Attrs: nounwind
define float @fb_dxop_objectToWorld(%struct.RuntimeDataStruct* %runtimeData, i32 %r, i8 zeroext %c) #0 {
entry:
%mul = mul nsw i32 %r, 4
%conv = zext i8 %c to i32
%add = add nsw i32 %mul, %conv
%ObjectToWorld = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 9
%arrayidx = getelementptr inbounds [12 x float], [12 x float]* %ObjectToWorld, i32 0, i32 %add
%0 = load float, float* %arrayidx, align 4
ret float %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetObjectToWorld(%struct.RuntimeDataStruct* %runtimeData, <12 x float> %M) #0 {
entry:
%vecext = extractelement <12 x float> %M, i32 0
%ObjectToWorld = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 9
%arrayidx = getelementptr inbounds [12 x float], [12 x float]* %ObjectToWorld, i32 0, i32 0
store float %vecext, float* %arrayidx, align 4
%vecext1 = extractelement <12 x float> %M, i32 1
%ObjectToWorld2 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 9
%arrayidx3 = getelementptr inbounds [12 x float], [12 x float]* %ObjectToWorld2, i32 0, i32 1
store float %vecext1, float* %arrayidx3, align 4
%vecext4 = extractelement <12 x float> %M, i32 2
%ObjectToWorld5 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 9
%arrayidx6 = getelementptr inbounds [12 x float], [12 x float]* %ObjectToWorld5, i32 0, i32 2
store float %vecext4, float* %arrayidx6, align 4
%vecext7 = extractelement <12 x float> %M, i32 3
%ObjectToWorld8 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 9
%arrayidx9 = getelementptr inbounds [12 x float], [12 x float]* %ObjectToWorld8, i32 0, i32 3
store float %vecext7, float* %arrayidx9, align 4
%vecext10 = extractelement <12 x float> %M, i32 4
%ObjectToWorld11 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 9
%arrayidx12 = getelementptr inbounds [12 x float], [12 x float]* %ObjectToWorld11, i32 0, i32 4
store float %vecext10, float* %arrayidx12, align 4
%vecext13 = extractelement <12 x float> %M, i32 5
%ObjectToWorld14 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 9
%arrayidx15 = getelementptr inbounds [12 x float], [12 x float]* %ObjectToWorld14, i32 0, i32 5
store float %vecext13, float* %arrayidx15, align 4
%vecext16 = extractelement <12 x float> %M, i32 6
%ObjectToWorld17 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 9
%arrayidx18 = getelementptr inbounds [12 x float], [12 x float]* %ObjectToWorld17, i32 0, i32 6
store float %vecext16, float* %arrayidx18, align 4
%vecext19 = extractelement <12 x float> %M, i32 7
%ObjectToWorld20 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 9
%arrayidx21 = getelementptr inbounds [12 x float], [12 x float]* %ObjectToWorld20, i32 0, i32 7
store float %vecext19, float* %arrayidx21, align 4
%vecext22 = extractelement <12 x float> %M, i32 8
%ObjectToWorld23 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 9
%arrayidx24 = getelementptr inbounds [12 x float], [12 x float]* %ObjectToWorld23, i32 0, i32 8
store float %vecext22, float* %arrayidx24, align 4
%vecext25 = extractelement <12 x float> %M, i32 9
%ObjectToWorld26 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 9
%arrayidx27 = getelementptr inbounds [12 x float], [12 x float]* %ObjectToWorld26, i32 0, i32 9
store float %vecext25, float* %arrayidx27, align 4
%vecext28 = extractelement <12 x float> %M, i32 10
%ObjectToWorld29 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 9
%arrayidx30 = getelementptr inbounds [12 x float], [12 x float]* %ObjectToWorld29, i32 0, i32 10
store float %vecext28, float* %arrayidx30, align 4
%vecext31 = extractelement <12 x float> %M, i32 11
%ObjectToWorld32 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 9
%arrayidx33 = getelementptr inbounds [12 x float], [12 x float]* %ObjectToWorld32, i32 0, i32 11
store float %vecext31, float* %arrayidx33, align 4
ret void
}
; Function Attrs: nounwind
define float @fb_dxop_worldToObject(%struct.RuntimeDataStruct* %runtimeData, i32 %r, i8 zeroext %c) #0 {
entry:
%mul = mul nsw i32 %r, 4
%conv = zext i8 %c to i32
%add = add nsw i32 %mul, %conv
%WorldToObject = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 10
%arrayidx = getelementptr inbounds [12 x float], [12 x float]* %WorldToObject, i32 0, i32 %add
%0 = load float, float* %arrayidx, align 4
ret float %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetWorldToObject(%struct.RuntimeDataStruct* %runtimeData, <12 x float> %M) #0 {
entry:
%vecext = extractelement <12 x float> %M, i32 0
%WorldToObject = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 10
%arrayidx = getelementptr inbounds [12 x float], [12 x float]* %WorldToObject, i32 0, i32 0
store float %vecext, float* %arrayidx, align 4
%vecext1 = extractelement <12 x float> %M, i32 1
%WorldToObject2 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 10
%arrayidx3 = getelementptr inbounds [12 x float], [12 x float]* %WorldToObject2, i32 0, i32 1
store float %vecext1, float* %arrayidx3, align 4
%vecext4 = extractelement <12 x float> %M, i32 2
%WorldToObject5 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 10
%arrayidx6 = getelementptr inbounds [12 x float], [12 x float]* %WorldToObject5, i32 0, i32 2
store float %vecext4, float* %arrayidx6, align 4
%vecext7 = extractelement <12 x float> %M, i32 3
%WorldToObject8 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 10
%arrayidx9 = getelementptr inbounds [12 x float], [12 x float]* %WorldToObject8, i32 0, i32 3
store float %vecext7, float* %arrayidx9, align 4
%vecext10 = extractelement <12 x float> %M, i32 4
%WorldToObject11 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 10
%arrayidx12 = getelementptr inbounds [12 x float], [12 x float]* %WorldToObject11, i32 0, i32 4
store float %vecext10, float* %arrayidx12, align 4
%vecext13 = extractelement <12 x float> %M, i32 5
%WorldToObject14 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 10
%arrayidx15 = getelementptr inbounds [12 x float], [12 x float]* %WorldToObject14, i32 0, i32 5
store float %vecext13, float* %arrayidx15, align 4
%vecext16 = extractelement <12 x float> %M, i32 6
%WorldToObject17 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 10
%arrayidx18 = getelementptr inbounds [12 x float], [12 x float]* %WorldToObject17, i32 0, i32 6
store float %vecext16, float* %arrayidx18, align 4
%vecext19 = extractelement <12 x float> %M, i32 7
%WorldToObject20 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 10
%arrayidx21 = getelementptr inbounds [12 x float], [12 x float]* %WorldToObject20, i32 0, i32 7
store float %vecext19, float* %arrayidx21, align 4
%vecext22 = extractelement <12 x float> %M, i32 8
%WorldToObject23 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 10
%arrayidx24 = getelementptr inbounds [12 x float], [12 x float]* %WorldToObject23, i32 0, i32 8
store float %vecext22, float* %arrayidx24, align 4
%vecext25 = extractelement <12 x float> %M, i32 9
%WorldToObject26 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 10
%arrayidx27 = getelementptr inbounds [12 x float], [12 x float]* %WorldToObject26, i32 0, i32 9
store float %vecext25, float* %arrayidx27, align 4
%vecext28 = extractelement <12 x float> %M, i32 10
%WorldToObject29 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 10
%arrayidx30 = getelementptr inbounds [12 x float], [12 x float]* %WorldToObject29, i32 0, i32 10
store float %vecext28, float* %arrayidx30, align 4
%vecext31 = extractelement <12 x float> %M, i32 11
%WorldToObject32 = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 10
%arrayidx33 = getelementptr inbounds [12 x float], [12 x float]* %WorldToObject32, i32 0, i32 11
store float %vecext31, float* %arrayidx33, align 4
ret void
}
; Function Attrs: nounwind
define i32 @fb_dxop_primitiveIndex(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%PrimitiveIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 11
%0 = load i32, i32* %PrimitiveIndex, align 4
ret i32 %0
}
; Function Attrs: nounwind
define i32 @fb_Fallback_PrimitiveIndex(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%PrimitiveIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 11
%0 = load i32, i32* %PrimitiveIndex, align 4
ret i32 %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetPrimitiveIndex(%struct.RuntimeDataStruct* %runtimeData, i32 %i) #0 {
)AAA",
R"AAA(
entry:
%PrimitiveIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 11
store i32 %i, i32* %PrimitiveIndex, align 4
ret void
}
; Function Attrs: nounwind
define i32 @fb_Fallback_ShaderRecordOffset(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%ShaderRecordOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 15
%0 = load i32, i32* %ShaderRecordOffset, align 4
ret i32 %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetShaderRecordOffset(%struct.RuntimeDataStruct* %runtimeData, i32 %shaderRecordOffset) #0 {
entry:
%ShaderRecordOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 15
store i32 %shaderRecordOffset, i32* %ShaderRecordOffset, align 4
ret void
}
; Function Attrs: nounwind
define i32 @fb_dxop_instanceIndex(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%InstanceIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 12
%0 = load i32, i32* %InstanceIndex, align 4
ret i32 %0
}
; Function Attrs: nounwind
define i32 @fb_Fallback_InstanceIndex(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%InstanceIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 12
%0 = load i32, i32* %InstanceIndex, align 4
ret i32 %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetInstanceIndex(%struct.RuntimeDataStruct* %runtimeData, i32 %i) #0 {
entry:
%InstanceIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 12
store i32 %i, i32* %InstanceIndex, align 4
ret void
}
; Function Attrs: nounwind
define i32 @fb_dxop_instanceID(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%InstanceID = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 13
%0 = load i32, i32* %InstanceID, align 4
ret i32 %0
}
; Function Attrs: nounwind
define i32 @fb_Fallback_InstanceID(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%InstanceID = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 13
%0 = load i32, i32* %InstanceID, align 4
ret i32 %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetInstanceID(%struct.RuntimeDataStruct* %runtimeData, i32 %i) #0 {
entry:
%InstanceID = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 13
store i32 %i, i32* %InstanceID, align 4
ret void
}
; Function Attrs: nounwind
define i32 @fb_dxop_hitKind(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%HitKind = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 14
%0 = load i32, i32* %HitKind, align 4
ret i32 %0
}
; Function Attrs: nounwind
define i32 @fb_Fallback_HitKind(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%HitKind = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 14
%0 = load i32, i32* %HitKind, align 4
ret i32 %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetHitKind(%struct.RuntimeDataStruct* %runtimeData, i32 %i) #0 {
entry:
%HitKind = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 14
store i32 %i, i32* %HitKind, align 4
ret void
}
; Function Attrs: nounwind
define float @fb_dxop_pending_rayTCurrent(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%PendingRayTCurrent = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 16
%0 = load float, float* %PendingRayTCurrent, align 4
ret float %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetPendingRayTCurrent(%struct.RuntimeDataStruct* %runtimeData, float %t) #0 {
entry:
%PendingRayTCurrent = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 16
store float %t, float* %PendingRayTCurrent, align 4
ret void
}
; Function Attrs: nounwind
define i32 @fb_dxop_pending_primitiveID(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%PendingPrimitiveIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 17
%0 = load i32, i32* %PendingPrimitiveIndex, align 4
ret i32 %0
}
; Function Attrs: nounwind
define i32 @fb_Fallback_PendingShaderRecordOffset(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%PendingShaderRecordOffset = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 21
%0 = load i32, i32* %PendingShaderRecordOffset, align 4
ret i32 %0
}
; Function Attrs: nounwind
define i32 @fb_dxop_pending_instanceIndex(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%PendingInstanceIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 18
%0 = load i32, i32* %PendingInstanceIndex, align 4
ret i32 %0
}
; Function Attrs: nounwind
define i32 @fb_dxop_pending_instanceID(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%PendingInstanceID = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 19
%0 = load i32, i32* %PendingInstanceID, align 4
ret i32 %0
}
; Function Attrs: nounwind
define i32 @fb_dxop_pending_hitKind(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%PendingHitKind = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 20
%0 = load i32, i32* %PendingHitKind, align 4
ret i32 %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetPendingHitKind(%struct.RuntimeDataStruct* %runtimeData, i32 %i) #0 {
entry:
%PendingHitKind = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 20
store i32 %i, i32* %PendingHitKind, align 4
ret void
}
; Function Attrs: nounwind
define i32 @fb_Fallback_GroupIndex(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%GroupIndex = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 22
%0 = load i32, i32* %GroupIndex, align 4
ret i32 %0
}
; Function Attrs: nounwind
define i32 @fb_Fallback_AnyHitResult(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%AnyHitResult = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 23
%0 = load i32, i32* %AnyHitResult, align 4
ret i32 %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetAnyHitResult(%struct.RuntimeDataStruct* %runtimeData, i32 %result) #0 {
entry:
%AnyHitResult = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 23
store i32 %result, i32* %AnyHitResult, align 4
ret void
}
; Function Attrs: nounwind
define i32 @fb_Fallback_AnyHitStateId(%struct.RuntimeDataStruct* %runtimeData) #0 {
entry:
%AnyHitStateId = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 24
%0 = load i32, i32* %AnyHitStateId, align 4
ret i32 %0
}
; Function Attrs: nounwind
define void @fb_Fallback_SetAnyHitStateId(%struct.RuntimeDataStruct* %runtimeData, i32 %id) #0 {
entry:
%AnyHitStateId = getelementptr inbounds %struct.RuntimeDataStruct, %struct.RuntimeDataStruct* %runtimeData, i32 0, i32 24
store i32 %id, i32* %AnyHitStateId, align 4
ret void
}
attributes #0 = { nounwind }
attributes #1 = { nounwind }
)AAA"};
#include <sstream>
static std::string getRuntimeString() {
std::ostringstream out;
for (size_t i = 0; i < _countof(runtimeString); ++i)
out << runtimeString[i];
return out.str();
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxrFallback/Reducibility.h | #pragma once
namespace llvm {
class Function;
}
// Analyzes the reducibility of the control flow graph of F and uses node
// splitting to make an irredicible CFG reducible. Returns the number of node
// splits.
int makeReducible(llvm::Function *F); |
0 | repos/DirectXShaderCompiler/lib/DxrFallback | repos/DirectXShaderCompiler/lib/DxrFallback/runtime/rewriteRuntime.py | import re
inputFilename = 'runtime.opt.ll'
sourceFilename = r'C:/Users/chwallis/Desktop/DXILShaderPatch/runtime.c'
outputFilename = 'C:/Users/chwallis/Desktop/DXILShaderPatch/runtime.h'
source = open(sourceFilename).read()
input = open(inputFilename).read()
m = re.search(r'"nvptx"(.*?)attributes #', input, re.DOTALL)
dxil = m.group(1)
# split the string up to avoid error C2026: string too big, trailing characters truncated
lines = dxil.splitlines()
dxil = []
count = 0
for line in lines:
count += len(line)
dxil.append(line)
if count > 10000:
dxil.append(')AAA",')
dxil.append('R"AAA(')
count = 0
dxil = '\n'.join(dxil)
template = """
// This file generated by compiling the following source (runtime.c) as follows:
// clang -S -emit-llvm -target nvptr runtime.c
// opt -S -mem2reg runtime.ll -o runtime.opt.ll
// The resulting LLVM-IR is stripped of its datalayout and replaced with one
// compatible with DXIL.
// runtime.c
#if 0
%SOURCE%
#endif
static const char* runtimeString[] = { R"AAA(
target datalayout = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f:64:64-n8:16:32:64"
target triple = "dxil-ms-dx"
%DXIL%
attributes #0 = { nounwind }
attributes #1 = { nounwind }
)AAA"
};
#include <sstream>
static std::string getRuntimeString()
{
std::ostringstream out;
for( size_t i=0; i < _countof(runtimeString); ++i)
out << runtimeString[i];
return out.str();
}
"""
output = re.sub(r'%SOURCE%', source, template)
output = re.sub(r'%DXIL%', dxil, output)
open(outputFilename, 'w').write(output)
|
0 | repos/DirectXShaderCompiler/lib/DxrFallback | repos/DirectXShaderCompiler/lib/DxrFallback/runtime/runtime.c | #include <stddef.h>
static const int STACK_SIZE_IN_BYTES = 1024;
typedef float float3 __attribute__((vector_size(3*sizeof(float))));
typedef float float4 __attribute__((vector_size(4*sizeof(float))));
typedef float float12 __attribute__((vector_size(12*sizeof(float))));
typedef float (M3x4)[12];
typedef int (StackType)[STACK_SIZE_IN_BYTES/sizeof(int)];
typedef unsigned char byte;
typedef struct RuntimeDataStruct
{
int DispatchRaysIndex[2];
int DispatchRaysDimensions[2];
float RayTMin;
float RayTCurrent;
unsigned RayFlags;
float WorldRayOrigin[3];
float WorldRayDirection[3];
float ObjectRayOrigin[3];
float ObjectRayDirection[3];
M3x4 ObjectToWorld;
M3x4 WorldToObject;
unsigned PrimitiveIndex;
unsigned InstanceIndex;
unsigned InstanceID;
unsigned HitKind;
unsigned ShaderRecordOffset;
// Pending hit values - accessed in anyHit and intersection shaders before a hit has been committed
float PendingRayTCurrent;
unsigned PendingPrimitiveIndex;
unsigned PendingInstanceIndex;
unsigned PendingInstanceID;
unsigned PendingHitKind;
unsigned PendingShaderRecordOffset;
int GroupIndex;
int AnyHitResult;
int AnyHitStateId; // Originally temporary. We needed to avoid resource usage
// in ReportHit() because of linking issues so weset the value here first.
// May be worth retaining to cache the value when fetching the intersection
// stateId (fetch them both at once).
int PayloadOffset;
int CommittedAttrOffset;
int PendingAttrOffset;
int StackOffset; // offset from the start of the stack
StackType* Stack;
} RuntimeData;
typedef RuntimeData* RuntimeDataType;
typedef struct TraceRaySpills_ClosestHit
{
float RayTMin;
float RayTCurrent;
unsigned RayFlags;
float WorldRayOrigin[3];
float WorldRayDirection[3];
float ObjectRayOrigin[3];
float ObjectRayDirection[3];
unsigned PrimitiveIndex;
unsigned InstanceIndex;
unsigned InstanceID;
unsigned HitKind;
unsigned ShaderRecordOffset;
} TraceRaySpills_ClosestHit;
typedef struct TraceRaySpills_Miss
{
float RayTMin;
float RayTCurrent;
unsigned RayFlags;
float WorldRayOrigin[3];
float WorldRayDirection[3];
unsigned ShaderRecordOffset;
} TraceRaySpills_Miss;
#define REF(x) (runtimeData->x)
#define REF_FLT(x) (runtimeData->x)
#define REF_STACK(offset) ((*runtimeData->Stack)[runtimeData->StackOffset + offset])
#define REF_FLT_OFS(x, offset) (runtimeData->x[offset])
// Return next stateID
int rewrite_dispatch(RuntimeDataType runtimeData, int stateID);
void* rewrite_setLaunchParams(RuntimeDataType runtimeData, unsigned dimx, unsigned dimy);
unsigned rewrite_getStackSize(void);
StackType* rewrite_createStack(void);
void stackInit(RuntimeDataType runtimeData, StackType* theStack, unsigned stackSize)
{
REF(Stack) = theStack;
REF(StackOffset) = stackSize/sizeof(int) - 1;
REF(PayloadOffset) = 1111; // recognizable bogus values
REF(CommittedAttrOffset) = 2222;
REF(PendingAttrOffset) = 3333;
}
void stackFramePush(RuntimeDataType runtimeData, int size)
{
REF(StackOffset) -= size;
}
void stackFramePop(RuntimeDataType runtimeData, int size)
{
REF(StackOffset) += size;
}
int stackFrameOffset(RuntimeDataType runtimeData)
{
return REF(StackOffset);
}
int payloadOffset(RuntimeDataType runtimeData)
{
return REF(PayloadOffset);
}
int committedAttrOffset(RuntimeDataType runtimeData)
{
return REF(CommittedAttrOffset);
}
int pendingAttrOffset(RuntimeDataType runtimeData)
{
return REF(PendingAttrOffset);
}
int* stackIntPtr(RuntimeDataType runtimeData, int baseOffset, int offset)
{
return &(*runtimeData->Stack)[baseOffset + offset];
}
void traceFramePush(RuntimeDataType runtimeData, int attrSize)
{
// Save the old payload and attribute offsets
REF_STACK(-1) = REF(CommittedAttrOffset);
REF_STACK(-2) = REF(PendingAttrOffset);
// Set new offsets
REF(CommittedAttrOffset) = REF(StackOffset) - 2 - attrSize;
REF(PendingAttrOffset) = REF(StackOffset) - 2 - 2 * attrSize;
}
void traceFramePop(RuntimeDataType runtimeData)
{
// Restore the old attribute offsets
REF(CommittedAttrOffset) = REF_STACK(-1);
REF(PendingAttrOffset) = REF_STACK(-2);
}
void traceRaySave_ClosestHit(RuntimeDataType runtimeData, TraceRaySpills_ClosestHit* spills)
{
spills->RayFlags = REF(RayFlags);
spills->RayTCurrent = REF_FLT(RayTCurrent);
spills->RayTMin = REF_FLT(RayTMin);
spills->WorldRayOrigin[0] = REF_FLT(WorldRayOrigin[0]);
spills->WorldRayOrigin[1] = REF_FLT(WorldRayOrigin[1]);
spills->WorldRayOrigin[2] = REF_FLT(WorldRayOrigin[2]);
spills->WorldRayDirection[0] = REF_FLT(WorldRayDirection[0]);
spills->WorldRayDirection[1] = REF_FLT(WorldRayDirection[1]);
spills->WorldRayDirection[2] = REF_FLT(WorldRayDirection[2]);
spills->ObjectRayOrigin[0] = REF_FLT(ObjectRayOrigin[0]);
spills->ObjectRayOrigin[1] = REF_FLT(ObjectRayOrigin[1]);
spills->ObjectRayOrigin[2] = REF_FLT(ObjectRayOrigin[2]);
spills->ObjectRayDirection[0] = REF_FLT(ObjectRayDirection[0]);
spills->ObjectRayDirection[1] = REF_FLT(ObjectRayDirection[1]);
spills->ObjectRayDirection[2] = REF_FLT(ObjectRayDirection[2]);
spills->PrimitiveIndex = REF(PrimitiveIndex);
spills->InstanceIndex = REF(InstanceIndex);
spills->InstanceID = REF(InstanceID);
spills->HitKind = REF(HitKind);
spills->ShaderRecordOffset = REF(ShaderRecordOffset);
}
void traceRayRestore_ClosestHit(RuntimeDataType runtimeData, TraceRaySpills_ClosestHit* spills)
{
REF(RayFlags) = spills->RayFlags;
REF_FLT(RayTCurrent) = spills->RayTCurrent;
REF_FLT(RayTMin) = spills->RayTMin;
REF_FLT(WorldRayOrigin[0]) = spills->WorldRayOrigin[0];
REF_FLT(WorldRayOrigin[1]) = spills->WorldRayOrigin[1];
REF_FLT(WorldRayOrigin[2]) = spills->WorldRayOrigin[2];
REF_FLT(WorldRayDirection[0]) = spills->WorldRayDirection[0];
REF_FLT(WorldRayDirection[1]) = spills->WorldRayDirection[1];
REF_FLT(WorldRayDirection[2]) = spills->WorldRayDirection[2];
REF_FLT(ObjectRayOrigin[0]) = spills->ObjectRayOrigin[0];
REF_FLT(ObjectRayOrigin[1]) = spills->ObjectRayOrigin[1];
REF_FLT(ObjectRayOrigin[2]) = spills->ObjectRayOrigin[2];
REF_FLT(ObjectRayDirection[0]) = spills->ObjectRayDirection[0];
REF_FLT(ObjectRayDirection[1]) = spills->ObjectRayDirection[1];
REF_FLT(ObjectRayDirection[2]) = spills->ObjectRayDirection[2];
REF(PrimitiveIndex) = spills->PrimitiveIndex;
REF(InstanceIndex) = spills->InstanceIndex;
REF(InstanceID) = spills->InstanceID;
REF(HitKind) = spills->HitKind;
REF(ShaderRecordOffset) = spills->ShaderRecordOffset;
}
void traceRaySave_Miss(RuntimeDataType runtimeData, TraceRaySpills_Miss* spills)
{
spills->RayFlags = REF(RayFlags);
spills->RayTCurrent = REF_FLT(RayTCurrent);
spills->RayTMin = REF_FLT(RayTMin);
spills->WorldRayOrigin[0] = REF_FLT(WorldRayOrigin[0]);
spills->WorldRayOrigin[1] = REF_FLT(WorldRayOrigin[1]);
spills->WorldRayOrigin[2] = REF_FLT(WorldRayOrigin[2]);
spills->WorldRayDirection[0] = REF_FLT(WorldRayDirection[0]);
spills->WorldRayDirection[1] = REF_FLT(WorldRayDirection[1]);
spills->WorldRayDirection[2] = REF_FLT(WorldRayDirection[2]);
spills->ShaderRecordOffset = REF(ShaderRecordOffset);
}
void traceRayRestore_Miss(RuntimeDataType runtimeData, TraceRaySpills_Miss* spills)
{
REF(RayFlags) = spills->RayFlags;
REF_FLT(RayTCurrent) = spills->RayTCurrent;
REF_FLT(RayTMin) = spills->RayTMin;
REF_FLT(WorldRayOrigin[0]) = spills->WorldRayOrigin[0];
REF_FLT(WorldRayOrigin[1]) = spills->WorldRayOrigin[1];
REF_FLT(WorldRayOrigin[2]) = spills->WorldRayOrigin[2];
REF_FLT(WorldRayDirection[0]) = spills->WorldRayDirection[0];
REF_FLT(WorldRayDirection[1]) = spills->WorldRayDirection[1];
REF_FLT(WorldRayDirection[2]) = spills->WorldRayDirection[2];
REF(ShaderRecordOffset) = spills->ShaderRecordOffset;
}
//////////////////////////////////////////////////////////////////////////
//
// Intrinsics for the fallback layer
//
//////////////////////////////////////////////////////////////////////////
void fb_Fallback_Scheduler(int initialStateId, unsigned dimx, unsigned dimy)
{
StackType* theStack = rewrite_createStack();
RuntimeData theRuntimeData;
RuntimeDataType runtimeData = &theRuntimeData;
rewrite_setLaunchParams(runtimeData, dimx, dimy);
if(REF(DispatchRaysIndex[0]) >= REF(DispatchRaysDimensions[0]) ||
REF(DispatchRaysIndex[1]) >= REF(DispatchRaysDimensions[1]))
{
return;
}
// Set final return stateID into reserved area at stack top
unsigned stackSize = rewrite_getStackSize();
stackInit(runtimeData, theStack, stackSize);
int stackFrameOffs = stackFrameOffset(runtimeData);
*stackIntPtr(runtimeData, stackFrameOffs, 0) = -1;
int stateId = initialStateId;
int count = 0;
while( stateId >= 0 )
{
stateId = rewrite_dispatch(runtimeData, stateId);
}
}
void fb_Fallback_SetLaunchParams(RuntimeDataType runtimeData, unsigned DTidx, unsigned DTidy, unsigned dimx, unsigned dimy, unsigned groupIndex)
{
REF(DispatchRaysIndex[0]) = DTidx;
REF(DispatchRaysIndex[1]) = DTidy;
REF(DispatchRaysDimensions[0]) = dimx;
REF(DispatchRaysDimensions[1]) = dimy;
REF(GroupIndex) = groupIndex;
}
int fb_Fallback_TraceRayBegin(RuntimeDataType runtimeData, unsigned rayFlags, float ox, float oy, float oz, float tmin, float dx, float dy, float dz, float tmax, int newPayloadOffset)
{
REF(RayFlags) = rayFlags;
REF_FLT(WorldRayOrigin[0]) = ox;
REF_FLT(WorldRayOrigin[1]) = oy;
REF_FLT(WorldRayOrigin[2]) = oz;
REF_FLT(WorldRayDirection[0]) = dx;
REF_FLT(WorldRayDirection[1]) = dy;
REF_FLT(WorldRayDirection[2]) = dz;
REF_FLT(RayTCurrent) = tmax;
REF_FLT(RayTMin) = tmin;
int oldOffset = REF(PayloadOffset);
REF(PayloadOffset) = newPayloadOffset;
return oldOffset;
}
void fb_Fallback_TraceRayEnd(RuntimeDataType runtimeData, int oldPayloadOffset)
{
REF(PayloadOffset) = oldPayloadOffset;
}
void fb_Fallback_SetPendingTriVals(RuntimeDataType runtimeData, unsigned shaderRecordOffset, unsigned primitiveIndex, unsigned instanceIndex, unsigned instanceID, float t, unsigned hitKind)
{
REF(PendingShaderRecordOffset) = shaderRecordOffset;
REF(PendingPrimitiveIndex) = primitiveIndex;
REF(PendingInstanceIndex) = instanceIndex;
REF(PendingInstanceID) = instanceID;
REF_FLT(PendingRayTCurrent) = t;
REF(PendingHitKind) = hitKind;
}
void fb_Fallback_SetPendingCustomVals(RuntimeDataType runtimeData, unsigned shaderRecordOffset, unsigned primitiveIndex, unsigned instanceIndex, unsigned instanceID)
{
REF(PendingShaderRecordOffset) = shaderRecordOffset;
REF(PendingPrimitiveIndex) = primitiveIndex;
REF(PendingInstanceIndex) = instanceIndex;
REF(PendingInstanceID) = instanceID;
}
void fb_Fallback_CommitHit(RuntimeDataType runtimeData)
{
REF_FLT(RayTCurrent) = REF_FLT(PendingRayTCurrent);
REF(ShaderRecordOffset) = REF(PendingShaderRecordOffset);
REF(PrimitiveIndex) = REF(PendingPrimitiveIndex);
REF(InstanceIndex) = REF(PendingInstanceIndex);
REF(InstanceID) = REF(PendingInstanceID);
REF(HitKind) = REF(PendingHitKind);
int PendingAttrOffset = REF(PendingAttrOffset);
REF(PendingAttrOffset) = REF(CommittedAttrOffset);
REF(CommittedAttrOffset) = PendingAttrOffset;
}
int fb_Fallback_RuntimeDataLoadInt(RuntimeDataType runtimeData, int offset)
{
return (*runtimeData->Stack)[offset];
}
void fb_Fallback_RuntimeDataStoreInt(RuntimeDataType runtimeData, int offset, int val)
{
(*runtimeData->Stack)[offset] = val;
}
unsigned fb_dxop_dispatchRaysIndex(RuntimeDataType runtimeData, byte i)
{
return REF(DispatchRaysIndex[i]);
}
unsigned fb_dxop_dispatchRaysDimensions(RuntimeDataType runtimeData, byte i)
{
return REF(DispatchRaysDimensions[i]);
}
float fb_dxop_rayTMin(RuntimeDataType runtimeData)
{
return REF_FLT(RayTMin);
}
float fb_Fallback_RayTMin(RuntimeDataType runtimeData)
{
return REF_FLT(RayTMin);
}
void fb_Fallback_SetRayTMin(RuntimeDataType runtimeData, float t)
{
REF_FLT(RayTMin) = t;
}
float fb_dxop_rayTCurrent(RuntimeDataType runtimeData)
{
return REF_FLT(RayTCurrent);
}
float fb_Fallback_RayTCurrent(RuntimeDataType runtimeData)
{
return REF_FLT(RayTCurrent);
}
void fb_Fallback_SetRayTCurrent(RuntimeDataType runtimeData, float t)
{
REF_FLT(RayTCurrent) = t;
}
unsigned fb_dxop_rayFlags(RuntimeDataType runtimeData)
{
return REF(RayFlags);
}
unsigned fb_Fallback_RayFlags(RuntimeDataType runtimeData)
{
return REF(RayFlags);
}
void fb_Fallback_SetRayFlags(RuntimeDataType runtimeData, unsigned flags)
{
REF(RayFlags) = flags;
}
float fb_dxop_worldRayOrigin(RuntimeDataType runtimeData, byte i)
{
return REF_FLT(WorldRayOrigin[i]);
}
float fb_Fallback_WorldRayOrigin(RuntimeDataType runtimeData, byte i)
{
return REF_FLT(WorldRayOrigin[i]);
}
void fb_Fallback_SetWorldRayOrigin(RuntimeDataType runtimeData, float x, float y, float z)
{
REF_FLT(WorldRayOrigin[0]) = x;
REF_FLT(WorldRayOrigin[1]) = y;
REF_FLT(WorldRayOrigin[2]) = z;
}
float fb_dxop_worldRayDirection(RuntimeDataType runtimeData, byte i)
{
return REF_FLT(WorldRayDirection[i]);
}
float fb_Fallback_WorldRayDirection(RuntimeDataType runtimeData, byte i)
{
return REF_FLT(WorldRayDirection[i]);
}
void fb_Fallback_SetWorldRayDirection(RuntimeDataType runtimeData, float x, float y, float z)
{
REF_FLT(WorldRayDirection[0]) = x;
REF_FLT(WorldRayDirection[1]) = y;
REF_FLT(WorldRayDirection[2]) = z;
}
float fb_dxop_objectRayOrigin(RuntimeDataType runtimeData, byte i)
{
return REF_FLT(ObjectRayOrigin[i]);
}
float fb_Fallback_ObjectRayOrigin(RuntimeDataType runtimeData, byte i)
{
return REF_FLT(ObjectRayOrigin[i]);
}
void fb_Fallback_SetObjectRayOrigin(RuntimeDataType runtimeData, float x, float y, float z)
{
REF_FLT(ObjectRayOrigin[0]) = x;
REF_FLT(ObjectRayOrigin[1]) = y;
REF_FLT(ObjectRayOrigin[2]) = z;
}
float fb_dxop_objectRayDirection(RuntimeDataType runtimeData, byte i)
{
return REF_FLT(ObjectRayDirection[i]);
}
float fb_Fallback_ObjectRayDirection(RuntimeDataType runtimeData, byte i)
{
return REF_FLT(ObjectRayDirection[i]);
}
void fb_Fallback_SetObjectRayDirection(RuntimeDataType runtimeData, float x, float y, float z)
{
REF_FLT(ObjectRayDirection[0]) = x;
REF_FLT(ObjectRayDirection[1]) = y;
REF_FLT(ObjectRayDirection[2]) = z;
}
float fb_dxop_objectToWorld(RuntimeDataType runtimeData, int r, byte c)
{
int i = r * 4 + c;
return REF_FLT_OFS(ObjectToWorld, i);
}
void fb_Fallback_SetObjectToWorld(RuntimeDataType runtimeData, float12 M)
{
REF_FLT_OFS(ObjectToWorld, 0) = M[0];
REF_FLT_OFS(ObjectToWorld, 1) = M[1];
REF_FLT_OFS(ObjectToWorld, 2) = M[2];
REF_FLT_OFS(ObjectToWorld, 3) = M[3];
REF_FLT_OFS(ObjectToWorld, 4) = M[4];
REF_FLT_OFS(ObjectToWorld, 5) = M[5];
REF_FLT_OFS(ObjectToWorld, 6) = M[6];
REF_FLT_OFS(ObjectToWorld, 7) = M[7];
REF_FLT_OFS(ObjectToWorld, 8) = M[8];
REF_FLT_OFS(ObjectToWorld, 9) = M[9];
REF_FLT_OFS(ObjectToWorld, 10) = M[10];
REF_FLT_OFS(ObjectToWorld, 11) = M[11];
}
float fb_dxop_worldToObject(RuntimeDataType runtimeData, int r, byte c)
{
int i = r * 4 + c;
return REF_FLT_OFS(WorldToObject, i);
}
void fb_Fallback_SetWorldToObject(RuntimeDataType runtimeData, float12 M)
{
REF_FLT_OFS(WorldToObject, 0) = M[0];
REF_FLT_OFS(WorldToObject, 1) = M[1];
REF_FLT_OFS(WorldToObject, 2) = M[2];
REF_FLT_OFS(WorldToObject, 3) = M[3];
REF_FLT_OFS(WorldToObject, 4) = M[4];
REF_FLT_OFS(WorldToObject, 5) = M[5];
REF_FLT_OFS(WorldToObject, 6) = M[6];
REF_FLT_OFS(WorldToObject, 7) = M[7];
REF_FLT_OFS(WorldToObject, 8) = M[8];
REF_FLT_OFS(WorldToObject, 9) = M[9];
REF_FLT_OFS(WorldToObject, 10) = M[10];
REF_FLT_OFS(WorldToObject, 11) = M[11];
}
unsigned fb_dxop_primitiveID(RuntimeDataType runtimeData)
//unsigned fb_dxop_primitiveIndex(RuntimeDataType runtimeData)
{
return REF(PrimitiveIndex);
}
unsigned fb_Fallback_PrimitiveIndex(RuntimeDataType runtimeData)
{
return REF(PrimitiveIndex);
}
void fb_Fallback_SetPrimitiveIndex(RuntimeDataType runtimeData, unsigned i)
{
REF(PrimitiveIndex) = i;
}
unsigned fb_Fallback_ShaderRecordOffset(RuntimeDataType runtimeData)
{
return REF(ShaderRecordOffset);
}
void fb_Fallback_SetShaderRecordOffset(RuntimeDataType runtimeData, unsigned shaderRecordOffset)
{
REF(ShaderRecordOffset) = shaderRecordOffset;
}
unsigned fb_dxop_instanceIndex(RuntimeDataType runtimeData)
{
return REF(InstanceIndex);
}
unsigned fb_Fallback_InstanceIndex(RuntimeDataType runtimeData)
{
return REF(InstanceIndex);
}
void fb_Fallback_SetInstanceIndex(RuntimeDataType runtimeData, unsigned i)
{
REF(InstanceIndex) = i;
}
unsigned fb_dxop_instanceID(RuntimeDataType runtimeData)
{
return REF(InstanceID);
}
unsigned fb_Fallback_InstanceID(RuntimeDataType runtimeData)
{
return REF(InstanceID);
}
void fb_Fallback_SetInstanceID(RuntimeDataType runtimeData, unsigned i)
{
REF(InstanceID) = i;
}
unsigned fb_dxop_hitKind(RuntimeDataType runtimeData)
{
return REF(HitKind);
}
unsigned fb_Fallback_HitKind(RuntimeDataType runtimeData)
{
return REF(HitKind);
}
void fb_Fallback_SetHitKind(RuntimeDataType runtimeData, unsigned i)
{
REF(HitKind) = i;
}
float fb_dxop_pending_rayTCurrent(RuntimeDataType runtimeData)
{
return REF_FLT(PendingRayTCurrent);
}
void fb_Fallback_SetPendingRayTCurrent(RuntimeDataType runtimeData, float t)
{
REF_FLT(PendingRayTCurrent) = t;
}
unsigned fb_dxop_pending_primitiveID(RuntimeDataType runtimeData)
//unsigned fb_dxop_pending_primitiveIndex(RuntimeDataType runtimeData)
{
return REF(PendingPrimitiveIndex);
}
unsigned fb_Fallback_PendingShaderRecordOffset(RuntimeDataType runtimeData)
{
return REF(PendingShaderRecordOffset);
}
unsigned fb_dxop_pending_instanceIndex(RuntimeDataType runtimeData)
{
return REF(PendingInstanceIndex);
}
unsigned fb_dxop_pending_instanceID(RuntimeDataType runtimeData)
{
return REF(PendingInstanceID);
}
unsigned fb_dxop_pending_hitKind(RuntimeDataType runtimeData)
{
return REF(PendingHitKind);
}
void fb_Fallback_SetPendingHitKind(RuntimeDataType runtimeData, unsigned i)
{
REF(PendingHitKind) = i;
}
unsigned fb_Fallback_GroupIndex(RuntimeDataType runtimeData)
{
return REF(GroupIndex);
}
int fb_Fallback_AnyHitResult(RuntimeDataType runtimeData)
{
return REF(AnyHitResult);
}
void fb_Fallback_SetAnyHitResult(RuntimeDataType runtimeData, int result)
{
REF(AnyHitResult) = result;
}
int fb_Fallback_AnyHitStateId(RuntimeDataType runtimeData)
{
return REF(AnyHitStateId);
}
void fb_Fallback_SetAnyHitStateId(RuntimeDataType runtimeData, int id)
{
REF(AnyHitStateId) = id;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/AsmParser/LLToken.h | //===- LLToken.h - Token Codes for LLVM Assembly Files ----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the enums for the .ll lexer.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_ASMPARSER_LLTOKEN_H
#define LLVM_LIB_ASMPARSER_LLTOKEN_H
namespace llvm {
namespace lltok {
enum Kind {
// Markers
Eof, Error,
// Tokens with no info.
dotdotdot, // ...
equal, comma, // = ,
star, // *
lsquare, rsquare, // [ ]
lbrace, rbrace, // { }
less, greater, // < >
lparen, rparen, // ( )
exclaim, // !
bar, // |
kw_x,
kw_true, kw_false,
kw_declare, kw_define,
kw_global, kw_constant,
kw_private,
kw_internal,
kw_linkonce, kw_linkonce_odr,
kw_weak, // Used as a linkage, and a modifier for "cmpxchg".
kw_weak_odr, kw_appending,
kw_dllimport, kw_dllexport, kw_common, kw_available_externally,
kw_default, kw_hidden, kw_protected,
kw_unnamed_addr,
kw_externally_initialized,
kw_extern_weak,
kw_external, kw_thread_local,
kw_localdynamic, kw_initialexec, kw_localexec,
kw_zeroinitializer,
kw_undef, kw_null,
kw_to,
kw_tail,
kw_musttail,
kw_target,
kw_triple,
kw_unwind,
kw_deplibs, // FIXME: Remove in 4.0
kw_datalayout,
kw_volatile,
kw_atomic,
kw_unordered, kw_monotonic, kw_acquire, kw_release, kw_acq_rel, kw_seq_cst,
kw_singlethread,
kw_nnan,
kw_ninf,
kw_nsz,
kw_arcp,
kw_fast,
kw_nuw,
kw_nsw,
kw_exact,
kw_inbounds,
kw_align,
kw_addrspace,
kw_section,
kw_alias,
kw_module,
kw_asm,
kw_sideeffect,
kw_alignstack,
kw_inteldialect,
kw_gc,
kw_prefix,
kw_prologue,
kw_c,
kw_cc, kw_ccc, kw_fastcc, kw_coldcc,
kw_intel_ocl_bicc,
kw_x86_stdcallcc, kw_x86_fastcallcc, kw_x86_thiscallcc, kw_x86_vectorcallcc,
kw_arm_apcscc, kw_arm_aapcscc, kw_arm_aapcs_vfpcc,
kw_msp430_intrcc,
kw_ptx_kernel, kw_ptx_device,
kw_spir_kernel, kw_spir_func,
kw_x86_64_sysvcc, kw_x86_64_win64cc,
kw_webkit_jscc, kw_anyregcc,
kw_preserve_mostcc, kw_preserve_allcc,
kw_ghccc,
// Attributes:
kw_attributes,
kw_alwaysinline,
kw_argmemonly,
kw_sanitize_address,
kw_builtin,
kw_byval,
kw_inalloca,
kw_cold,
kw_convergent,
kw_dereferenceable,
kw_dereferenceable_or_null,
kw_inlinehint,
kw_inreg,
kw_jumptable,
kw_minsize,
kw_naked,
kw_nest,
kw_noalias,
kw_nobuiltin,
kw_nocapture,
kw_noduplicate,
kw_noimplicitfloat,
kw_noinline,
kw_nonlazybind,
kw_nonnull,
kw_noredzone,
kw_noreturn,
kw_nounwind,
kw_optnone,
kw_optsize,
kw_readnone,
kw_readonly,
kw_returned,
kw_returns_twice,
kw_signext,
kw_ssp,
kw_sspreq,
kw_sspstrong,
kw_safestack,
kw_sret,
kw_sanitize_thread,
kw_sanitize_memory,
kw_uwtable,
kw_zeroext,
kw_type,
kw_opaque,
kw_comdat,
// Comdat types
kw_any,
kw_exactmatch,
kw_largest,
kw_noduplicates,
kw_samesize,
kw_eq, kw_ne, kw_slt, kw_sgt, kw_sle, kw_sge, kw_ult, kw_ugt, kw_ule,
kw_uge, kw_oeq, kw_one, kw_olt, kw_ogt, kw_ole, kw_oge, kw_ord, kw_uno,
kw_ueq, kw_une,
// atomicrmw operations that aren't also instruction keywords.
kw_xchg, kw_nand, kw_max, kw_min, kw_umax, kw_umin,
// Instruction Opcodes (Opcode in UIntVal).
kw_add, kw_fadd, kw_sub, kw_fsub, kw_mul, kw_fmul,
kw_udiv, kw_sdiv, kw_fdiv,
kw_urem, kw_srem, kw_frem, kw_shl, kw_lshr, kw_ashr,
kw_and, kw_or, kw_xor, kw_icmp, kw_fcmp,
kw_phi, kw_call,
kw_trunc, kw_zext, kw_sext, kw_fptrunc, kw_fpext, kw_uitofp, kw_sitofp,
kw_fptoui, kw_fptosi, kw_inttoptr, kw_ptrtoint, kw_bitcast,
kw_addrspacecast,
kw_select, kw_va_arg,
kw_landingpad, kw_personality, kw_cleanup, kw_catch, kw_filter,
kw_ret, kw_br, kw_switch, kw_indirectbr, kw_invoke, kw_resume,
kw_unreachable,
kw_alloca, kw_load, kw_store, kw_fence, kw_cmpxchg, kw_atomicrmw,
kw_getelementptr,
kw_extractelement, kw_insertelement, kw_shufflevector,
kw_extractvalue, kw_insertvalue, kw_blockaddress,
// Metadata types.
kw_distinct,
// Use-list order directives.
kw_uselistorder, kw_uselistorder_bb,
// Unsigned Valued tokens (UIntVal).
GlobalID, // @42
LocalVarID, // %42
AttrGrpID, // #42
// String valued tokens (StrVal).
LabelStr, // foo:
GlobalVar, // @foo @"foo"
ComdatVar, // $foo
LocalVar, // %foo %"foo"
MetadataVar, // !foo
StringConstant, // "foo"
DwarfTag, // DW_TAG_foo
DwarfAttEncoding, // DW_ATE_foo
DwarfVirtuality, // DW_VIRTUALITY_foo
DwarfLang, // DW_LANG_foo
DwarfOp, // DW_OP_foo
DIFlag, // DIFlagFoo
// Type valued tokens (TyVal).
Type,
APFloat, // APFloatVal
APSInt // APSInt
};
} // end namespace lltok
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/AsmParser/LLLexer.cpp | //===- LLLexer.cpp - Lexer for .ll Files ----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implement the Lexer for .ll files.
//
//===----------------------------------------------------------------------===//
#include "LLLexer.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Twine.h"
#include "llvm/AsmParser/Parser.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace llvm;
bool LLLexer::Error(LocTy ErrorLoc, const Twine &Msg) const {
ErrorInfo = SM.GetMessage(ErrorLoc, SourceMgr::DK_Error, Msg);
return true;
}
void LLLexer::Warning(LocTy WarningLoc, const Twine &Msg) const {
SM.PrintMessage(WarningLoc, SourceMgr::DK_Warning, Msg);
}
//===----------------------------------------------------------------------===//
// Helper functions.
//===----------------------------------------------------------------------===//
// atoull - Convert an ascii string of decimal digits into the unsigned long
// long representation... this does not have to do input error checking,
// because we know that the input will be matched by a suitable regex...
//
uint64_t LLLexer::atoull(const char *Buffer, const char *End) {
uint64_t Result = 0;
for (; Buffer != End; Buffer++) {
uint64_t OldRes = Result;
Result *= 10;
Result += *Buffer-'0';
if (Result < OldRes) { // Uh, oh, overflow detected!!!
Error("constant bigger than 64 bits detected!");
return 0;
}
}
return Result;
}
uint64_t LLLexer::HexIntToVal(const char *Buffer, const char *End) {
uint64_t Result = 0;
for (; Buffer != End; ++Buffer) {
uint64_t OldRes = Result;
Result *= 16;
Result += hexDigitValue(*Buffer);
if (Result < OldRes) { // Uh, oh, overflow detected!!!
Error("constant bigger than 64 bits detected!");
return 0;
}
}
return Result;
}
void LLLexer::HexToIntPair(const char *Buffer, const char *End,
uint64_t Pair[2]) {
Pair[0] = 0;
if (End - Buffer >= 16) {
for (int i = 0; i < 16; i++, Buffer++) {
assert(Buffer != End);
Pair[0] *= 16;
Pair[0] += hexDigitValue(*Buffer);
}
}
Pair[1] = 0;
for (int i = 0; i < 16 && Buffer != End; i++, Buffer++) {
Pair[1] *= 16;
Pair[1] += hexDigitValue(*Buffer);
}
if (Buffer != End)
Error("constant bigger than 128 bits detected!");
}
/// FP80HexToIntPair - translate an 80 bit FP80 number (20 hexits) into
/// { low64, high16 } as usual for an APInt.
void LLLexer::FP80HexToIntPair(const char *Buffer, const char *End,
uint64_t Pair[2]) {
Pair[1] = 0;
for (int i=0; i<4 && Buffer != End; i++, Buffer++) {
assert(Buffer != End);
Pair[1] *= 16;
Pair[1] += hexDigitValue(*Buffer);
}
Pair[0] = 0;
for (int i=0; i<16; i++, Buffer++) {
Pair[0] *= 16;
Pair[0] += hexDigitValue(*Buffer);
}
if (Buffer != End)
Error("constant bigger than 128 bits detected!");
}
// UnEscapeLexed - Run through the specified buffer and change \xx codes to the
// appropriate character.
static void UnEscapeLexed(std::string &Str) {
if (Str.empty()) return;
char *Buffer = &Str[0], *EndBuffer = Buffer+Str.size();
char *BOut = Buffer;
for (char *BIn = Buffer; BIn != EndBuffer; ) {
if (BIn[0] == '\\') {
if (BIn < EndBuffer-1 && BIn[1] == '\\') {
*BOut++ = '\\'; // Two \ becomes one
BIn += 2;
} else if (BIn < EndBuffer-2 &&
isxdigit(static_cast<unsigned char>(BIn[1])) &&
isxdigit(static_cast<unsigned char>(BIn[2]))) {
*BOut = hexDigitValue(BIn[1]) * 16 + hexDigitValue(BIn[2]);
BIn += 3; // Skip over handled chars
++BOut;
} else {
*BOut++ = *BIn++;
}
} else {
*BOut++ = *BIn++;
}
}
Str.resize(BOut-Buffer);
}
/// isLabelChar - Return true for [-a-zA-Z$._0-9].
static bool isLabelChar(char C) {
return isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
C == '.' || C == '_';
}
/// isLabelTail - Return true if this pointer points to a valid end of a label.
static const char *isLabelTail(const char *CurPtr) {
while (1) {
if (CurPtr[0] == ':') return CurPtr+1;
if (!isLabelChar(CurPtr[0])) return nullptr;
++CurPtr;
}
}
//===----------------------------------------------------------------------===//
// Lexer definition.
//===----------------------------------------------------------------------===//
LLLexer::LLLexer(StringRef StartBuf, SourceMgr &sm, SMDiagnostic &Err,
LLVMContext &C)
: CurBuf(StartBuf), ErrorInfo(Err), SM(sm), Context(C), APFloatVal(0.0) {
CurPtr = CurBuf.begin();
}
int LLLexer::getNextChar() {
char CurChar = *CurPtr++;
switch (CurChar) {
default: return (unsigned char)CurChar;
case 0:
// A nul character in the stream is either the end of the current buffer or
// a random nul in the file. Disambiguate that here.
if (CurPtr-1 != CurBuf.end())
return 0; // Just whitespace.
// Otherwise, return end of file.
--CurPtr; // Another call to lex will return EOF again.
return EOF;
}
}
lltok::Kind LLLexer::LexToken() {
TokStart = CurPtr;
int CurChar = getNextChar();
switch (CurChar) {
default:
// Handle letters: [a-zA-Z_]
if (isalpha(static_cast<unsigned char>(CurChar)) || CurChar == '_')
return LexIdentifier();
return lltok::Error;
case EOF: return lltok::Eof;
case 0:
case ' ':
case '\t':
case '\n':
case '\r':
// Ignore whitespace.
return LexToken();
case '+': return LexPositive();
case '@': return LexAt();
case '$': return LexDollar();
case '%': return LexPercent();
case '"': return LexQuote();
case '.':
if (const char *Ptr = isLabelTail(CurPtr)) {
CurPtr = Ptr;
StrVal.assign(TokStart, CurPtr-1);
return lltok::LabelStr;
}
if (CurPtr[0] == '.' && CurPtr[1] == '.') {
CurPtr += 2;
return lltok::dotdotdot;
}
return lltok::Error;
case ';':
SkipLineComment();
return LexToken();
case '!': return LexExclaim();
case '#': return LexHash();
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '-':
return LexDigitOrNegative();
case '=': return lltok::equal;
case '[': return lltok::lsquare;
case ']': return lltok::rsquare;
case '{': return lltok::lbrace;
case '}': return lltok::rbrace;
case '<': return lltok::less;
case '>': return lltok::greater;
case '(': return lltok::lparen;
case ')': return lltok::rparen;
case ',': return lltok::comma;
case '*': return lltok::star;
case '|': return lltok::bar;
}
}
void LLLexer::SkipLineComment() {
while (1) {
if (CurPtr[0] == '\n' || CurPtr[0] == '\r' || getNextChar() == EOF)
return;
}
}
/// Lex all tokens that start with an @ character.
/// GlobalVar @\"[^\"]*\"
/// GlobalVar @[-a-zA-Z$._][-a-zA-Z$._0-9]*
/// GlobalVarID @[0-9]+
lltok::Kind LLLexer::LexAt() {
return LexVar(lltok::GlobalVar, lltok::GlobalID);
}
lltok::Kind LLLexer::LexDollar() {
if (const char *Ptr = isLabelTail(TokStart)) {
CurPtr = Ptr;
StrVal.assign(TokStart, CurPtr - 1);
return lltok::LabelStr;
}
// Handle DollarStringConstant: $\"[^\"]*\"
if (CurPtr[0] == '"') {
++CurPtr;
while (1) {
int CurChar = getNextChar();
if (CurChar == EOF) {
Error("end of file in COMDAT variable name");
return lltok::Error;
}
if (CurChar == '"') {
StrVal.assign(TokStart + 2, CurPtr - 1);
UnEscapeLexed(StrVal);
if (StringRef(StrVal).find_first_of(0) != StringRef::npos) {
Error("Null bytes are not allowed in names");
return lltok::Error;
}
return lltok::ComdatVar;
}
}
}
// Handle ComdatVarName: $[-a-zA-Z$._][-a-zA-Z$._0-9]*
if (ReadVarName())
return lltok::ComdatVar;
return lltok::Error;
}
/// ReadString - Read a string until the closing quote.
lltok::Kind LLLexer::ReadString(lltok::Kind kind) {
const char *Start = CurPtr;
while (1) {
int CurChar = getNextChar();
if (CurChar == EOF) {
Error("end of file in string constant");
return lltok::Error;
}
if (CurChar == '"') {
StrVal.assign(Start, CurPtr-1);
UnEscapeLexed(StrVal);
return kind;
}
}
}
/// ReadVarName - Read the rest of a token containing a variable name.
bool LLLexer::ReadVarName() {
const char *NameStart = CurPtr;
if (isalpha(static_cast<unsigned char>(CurPtr[0])) ||
CurPtr[0] == '-' || CurPtr[0] == '$' ||
CurPtr[0] == '.' || CurPtr[0] == '_') {
++CurPtr;
while (isalnum(static_cast<unsigned char>(CurPtr[0])) ||
CurPtr[0] == '-' || CurPtr[0] == '$' ||
CurPtr[0] == '.' || CurPtr[0] == '_')
++CurPtr;
StrVal.assign(NameStart, CurPtr);
return true;
}
return false;
}
lltok::Kind LLLexer::LexVar(lltok::Kind Var, lltok::Kind VarID) {
// Handle StringConstant: \"[^\"]*\"
if (CurPtr[0] == '"') {
++CurPtr;
while (1) {
int CurChar = getNextChar();
if (CurChar == EOF) {
Error("end of file in global variable name");
return lltok::Error;
}
if (CurChar == '"') {
StrVal.assign(TokStart+2, CurPtr-1);
UnEscapeLexed(StrVal);
if (StringRef(StrVal).find_first_of(0) != StringRef::npos) {
Error("Null bytes are not allowed in names");
return lltok::Error;
}
return Var;
}
}
}
// Handle VarName: [-a-zA-Z$._][-a-zA-Z$._0-9]*
if (ReadVarName())
return Var;
// Handle VarID: [0-9]+
if (isdigit(static_cast<unsigned char>(CurPtr[0]))) {
for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
/*empty*/;
uint64_t Val = atoull(TokStart+1, CurPtr);
if ((unsigned)Val != Val)
Error("invalid value number (too large)!");
UIntVal = unsigned(Val);
return VarID;
}
return lltok::Error;
}
/// Lex all tokens that start with a % character.
/// LocalVar ::= %\"[^\"]*\"
/// LocalVar ::= %[-a-zA-Z$._][-a-zA-Z$._0-9]*
/// LocalVarID ::= %[0-9]+
lltok::Kind LLLexer::LexPercent() {
return LexVar(lltok::LocalVar, lltok::LocalVarID);
}
/// Lex all tokens that start with a " character.
/// QuoteLabel "[^"]+":
/// StringConstant "[^"]*"
lltok::Kind LLLexer::LexQuote() {
lltok::Kind kind = ReadString(lltok::StringConstant);
if (kind == lltok::Error || kind == lltok::Eof)
return kind;
if (CurPtr[0] == ':') {
++CurPtr;
if (StringRef(StrVal).find_first_of(0) != StringRef::npos) {
Error("Null bytes are not allowed in names");
kind = lltok::Error;
} else {
kind = lltok::LabelStr;
}
}
return kind;
}
/// Lex all tokens that start with a ! character.
/// !foo
/// !
lltok::Kind LLLexer::LexExclaim() {
// Lex a metadata name as a MetadataVar.
if (isalpha(static_cast<unsigned char>(CurPtr[0])) ||
CurPtr[0] == '-' || CurPtr[0] == '$' ||
CurPtr[0] == '.' || CurPtr[0] == '_' || CurPtr[0] == '\\') {
++CurPtr;
while (isalnum(static_cast<unsigned char>(CurPtr[0])) ||
CurPtr[0] == '-' || CurPtr[0] == '$' ||
CurPtr[0] == '.' || CurPtr[0] == '_' || CurPtr[0] == '\\')
++CurPtr;
StrVal.assign(TokStart+1, CurPtr); // Skip !
UnEscapeLexed(StrVal);
return lltok::MetadataVar;
}
return lltok::exclaim;
}
/// Lex all tokens that start with a # character.
/// AttrGrpID ::= #[0-9]+
lltok::Kind LLLexer::LexHash() {
// Handle AttrGrpID: #[0-9]+
if (isdigit(static_cast<unsigned char>(CurPtr[0]))) {
for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
/*empty*/;
uint64_t Val = atoull(TokStart+1, CurPtr);
if ((unsigned)Val != Val)
Error("invalid value number (too large)!");
UIntVal = unsigned(Val);
return lltok::AttrGrpID;
}
return lltok::Error;
}
/// Lex a label, integer type, keyword, or hexadecimal integer constant.
/// Label [-a-zA-Z$._0-9]+:
/// IntegerType i[0-9]+
/// Keyword sdiv, float, ...
/// HexIntConstant [us]0x[0-9A-Fa-f]+
lltok::Kind LLLexer::LexIdentifier() {
const char *StartChar = CurPtr;
const char *IntEnd = CurPtr[-1] == 'i' ? nullptr : StartChar;
const char *KeywordEnd = nullptr;
for (; isLabelChar(*CurPtr); ++CurPtr) {
// If we decide this is an integer, remember the end of the sequence.
if (!IntEnd && !isdigit(static_cast<unsigned char>(*CurPtr)))
IntEnd = CurPtr;
if (!KeywordEnd && !isalnum(static_cast<unsigned char>(*CurPtr)) &&
*CurPtr != '_')
KeywordEnd = CurPtr;
}
// If we stopped due to a colon, this really is a label.
if (*CurPtr == ':') {
StrVal.assign(StartChar-1, CurPtr++);
return lltok::LabelStr;
}
// Otherwise, this wasn't a label. If this was valid as an integer type,
// return it.
if (!IntEnd) IntEnd = CurPtr;
if (IntEnd != StartChar) {
CurPtr = IntEnd;
uint64_t NumBits = atoull(StartChar, CurPtr);
if (NumBits < IntegerType::MIN_INT_BITS ||
NumBits > IntegerType::MAX_INT_BITS) {
Error("bitwidth for integer type out of range!");
return lltok::Error;
}
TyVal = IntegerType::get(Context, NumBits);
return lltok::Type;
}
// Otherwise, this was a letter sequence. See which keyword this is.
if (!KeywordEnd) KeywordEnd = CurPtr;
CurPtr = KeywordEnd;
--StartChar;
StringRef Keyword(StartChar, CurPtr - StartChar);
#define KEYWORD(STR) \
do { \
if (Keyword == #STR) \
return lltok::kw_##STR; \
} while (0)
KEYWORD(true); KEYWORD(false);
KEYWORD(declare); KEYWORD(define);
KEYWORD(global); KEYWORD(constant);
KEYWORD(private);
KEYWORD(internal);
KEYWORD(available_externally);
KEYWORD(linkonce);
KEYWORD(linkonce_odr);
KEYWORD(weak); // Use as a linkage, and a modifier for "cmpxchg".
KEYWORD(weak_odr);
KEYWORD(appending);
KEYWORD(dllimport);
KEYWORD(dllexport);
KEYWORD(common);
KEYWORD(default);
KEYWORD(hidden);
KEYWORD(protected);
KEYWORD(unnamed_addr);
KEYWORD(externally_initialized);
KEYWORD(extern_weak);
KEYWORD(external);
KEYWORD(thread_local);
KEYWORD(localdynamic);
KEYWORD(initialexec);
KEYWORD(localexec);
KEYWORD(zeroinitializer);
KEYWORD(undef);
KEYWORD(null);
KEYWORD(to);
KEYWORD(tail);
KEYWORD(musttail);
KEYWORD(target);
KEYWORD(triple);
KEYWORD(unwind);
KEYWORD(deplibs); // FIXME: Remove in 4.0.
KEYWORD(datalayout);
KEYWORD(volatile);
KEYWORD(atomic);
KEYWORD(unordered);
KEYWORD(monotonic);
KEYWORD(acquire);
KEYWORD(release);
KEYWORD(acq_rel);
KEYWORD(seq_cst);
KEYWORD(singlethread);
KEYWORD(nnan);
KEYWORD(ninf);
KEYWORD(nsz);
KEYWORD(arcp);
KEYWORD(fast);
KEYWORD(nuw);
KEYWORD(nsw);
KEYWORD(exact);
KEYWORD(inbounds);
KEYWORD(align);
KEYWORD(addrspace);
KEYWORD(section);
KEYWORD(alias);
KEYWORD(module);
KEYWORD(asm);
KEYWORD(sideeffect);
KEYWORD(alignstack);
KEYWORD(inteldialect);
KEYWORD(gc);
KEYWORD(prefix);
KEYWORD(prologue);
KEYWORD(ccc);
KEYWORD(fastcc);
KEYWORD(coldcc);
KEYWORD(x86_stdcallcc);
KEYWORD(x86_fastcallcc);
KEYWORD(x86_thiscallcc);
KEYWORD(x86_vectorcallcc);
KEYWORD(arm_apcscc);
KEYWORD(arm_aapcscc);
KEYWORD(arm_aapcs_vfpcc);
KEYWORD(msp430_intrcc);
KEYWORD(ptx_kernel);
KEYWORD(ptx_device);
KEYWORD(spir_kernel);
KEYWORD(spir_func);
KEYWORD(intel_ocl_bicc);
KEYWORD(x86_64_sysvcc);
KEYWORD(x86_64_win64cc);
KEYWORD(webkit_jscc);
KEYWORD(anyregcc);
KEYWORD(preserve_mostcc);
KEYWORD(preserve_allcc);
KEYWORD(ghccc);
KEYWORD(cc);
KEYWORD(c);
KEYWORD(attributes);
KEYWORD(alwaysinline);
KEYWORD(argmemonly);
KEYWORD(builtin);
KEYWORD(byval);
KEYWORD(inalloca);
KEYWORD(cold);
KEYWORD(convergent);
KEYWORD(dereferenceable);
KEYWORD(dereferenceable_or_null);
KEYWORD(inlinehint);
KEYWORD(inreg);
KEYWORD(jumptable);
KEYWORD(minsize);
KEYWORD(naked);
KEYWORD(nest);
KEYWORD(noalias);
KEYWORD(nobuiltin);
KEYWORD(nocapture);
KEYWORD(noduplicate);
KEYWORD(noimplicitfloat);
KEYWORD(noinline);
KEYWORD(nonlazybind);
KEYWORD(nonnull);
KEYWORD(noredzone);
KEYWORD(noreturn);
KEYWORD(nounwind);
KEYWORD(optnone);
KEYWORD(optsize);
KEYWORD(readnone);
KEYWORD(readonly);
KEYWORD(returned);
KEYWORD(returns_twice);
KEYWORD(signext);
KEYWORD(sret);
KEYWORD(ssp);
KEYWORD(sspreq);
KEYWORD(sspstrong);
KEYWORD(safestack);
KEYWORD(sanitize_address);
KEYWORD(sanitize_thread);
KEYWORD(sanitize_memory);
KEYWORD(uwtable);
KEYWORD(zeroext);
KEYWORD(type);
KEYWORD(opaque);
KEYWORD(comdat);
// Comdat types
KEYWORD(any);
KEYWORD(exactmatch);
KEYWORD(largest);
KEYWORD(noduplicates);
KEYWORD(samesize);
KEYWORD(eq); KEYWORD(ne); KEYWORD(slt); KEYWORD(sgt); KEYWORD(sle);
KEYWORD(sge); KEYWORD(ult); KEYWORD(ugt); KEYWORD(ule); KEYWORD(uge);
KEYWORD(oeq); KEYWORD(one); KEYWORD(olt); KEYWORD(ogt); KEYWORD(ole);
KEYWORD(oge); KEYWORD(ord); KEYWORD(uno); KEYWORD(ueq); KEYWORD(une);
KEYWORD(xchg); KEYWORD(nand); KEYWORD(max); KEYWORD(min); KEYWORD(umax);
KEYWORD(umin);
KEYWORD(x);
KEYWORD(blockaddress);
// Metadata types.
KEYWORD(distinct);
// Use-list order directives.
KEYWORD(uselistorder);
KEYWORD(uselistorder_bb);
KEYWORD(personality);
KEYWORD(cleanup);
KEYWORD(catch);
KEYWORD(filter);
#undef KEYWORD
// Keywords for types.
#define TYPEKEYWORD(STR, LLVMTY) \
do { \
if (Keyword == STR) { \
TyVal = LLVMTY; \
return lltok::Type; \
} \
} while (false)
TYPEKEYWORD("void", Type::getVoidTy(Context));
TYPEKEYWORD("half", Type::getHalfTy(Context));
TYPEKEYWORD("float", Type::getFloatTy(Context));
TYPEKEYWORD("double", Type::getDoubleTy(Context));
TYPEKEYWORD("x86_fp80", Type::getX86_FP80Ty(Context));
TYPEKEYWORD("fp128", Type::getFP128Ty(Context));
TYPEKEYWORD("ppc_fp128", Type::getPPC_FP128Ty(Context));
TYPEKEYWORD("label", Type::getLabelTy(Context));
TYPEKEYWORD("metadata", Type::getMetadataTy(Context));
TYPEKEYWORD("x86_mmx", Type::getX86_MMXTy(Context));
#undef TYPEKEYWORD
// Keywords for instructions.
#define INSTKEYWORD(STR, Enum) \
do { \
if (Keyword == #STR) { \
UIntVal = Instruction::Enum; \
return lltok::kw_##STR; \
} \
} while (false)
INSTKEYWORD(add, Add); INSTKEYWORD(fadd, FAdd);
INSTKEYWORD(sub, Sub); INSTKEYWORD(fsub, FSub);
INSTKEYWORD(mul, Mul); INSTKEYWORD(fmul, FMul);
INSTKEYWORD(udiv, UDiv); INSTKEYWORD(sdiv, SDiv); INSTKEYWORD(fdiv, FDiv);
INSTKEYWORD(urem, URem); INSTKEYWORD(srem, SRem); INSTKEYWORD(frem, FRem);
INSTKEYWORD(shl, Shl); INSTKEYWORD(lshr, LShr); INSTKEYWORD(ashr, AShr);
INSTKEYWORD(and, And); INSTKEYWORD(or, Or); INSTKEYWORD(xor, Xor);
INSTKEYWORD(icmp, ICmp); INSTKEYWORD(fcmp, FCmp);
INSTKEYWORD(phi, PHI);
INSTKEYWORD(call, Call);
INSTKEYWORD(trunc, Trunc);
INSTKEYWORD(zext, ZExt);
INSTKEYWORD(sext, SExt);
INSTKEYWORD(fptrunc, FPTrunc);
INSTKEYWORD(fpext, FPExt);
INSTKEYWORD(uitofp, UIToFP);
INSTKEYWORD(sitofp, SIToFP);
INSTKEYWORD(fptoui, FPToUI);
INSTKEYWORD(fptosi, FPToSI);
INSTKEYWORD(inttoptr, IntToPtr);
INSTKEYWORD(ptrtoint, PtrToInt);
INSTKEYWORD(bitcast, BitCast);
INSTKEYWORD(addrspacecast, AddrSpaceCast);
INSTKEYWORD(select, Select);
INSTKEYWORD(va_arg, VAArg);
INSTKEYWORD(ret, Ret);
INSTKEYWORD(br, Br);
INSTKEYWORD(switch, Switch);
INSTKEYWORD(indirectbr, IndirectBr);
INSTKEYWORD(invoke, Invoke);
INSTKEYWORD(resume, Resume);
INSTKEYWORD(unreachable, Unreachable);
INSTKEYWORD(alloca, Alloca);
INSTKEYWORD(load, Load);
INSTKEYWORD(store, Store);
INSTKEYWORD(cmpxchg, AtomicCmpXchg);
INSTKEYWORD(atomicrmw, AtomicRMW);
INSTKEYWORD(fence, Fence);
INSTKEYWORD(getelementptr, GetElementPtr);
INSTKEYWORD(extractelement, ExtractElement);
INSTKEYWORD(insertelement, InsertElement);
INSTKEYWORD(shufflevector, ShuffleVector);
INSTKEYWORD(extractvalue, ExtractValue);
INSTKEYWORD(insertvalue, InsertValue);
INSTKEYWORD(landingpad, LandingPad);
#undef INSTKEYWORD
#define DWKEYWORD(TYPE, TOKEN) \
do { \
if (Keyword.startswith("DW_" #TYPE "_")) { \
StrVal.assign(Keyword.begin(), Keyword.end()); \
return lltok::TOKEN; \
} \
} while (false)
DWKEYWORD(TAG, DwarfTag);
DWKEYWORD(ATE, DwarfAttEncoding);
DWKEYWORD(VIRTUALITY, DwarfVirtuality);
DWKEYWORD(LANG, DwarfLang);
DWKEYWORD(OP, DwarfOp);
#undef DWKEYWORD
if (Keyword.startswith("DIFlag")) {
StrVal.assign(Keyword.begin(), Keyword.end());
return lltok::DIFlag;
}
// Check for [us]0x[0-9A-Fa-f]+ which are Hexadecimal constant generated by
// the CFE to avoid forcing it to deal with 64-bit numbers.
if ((TokStart[0] == 'u' || TokStart[0] == 's') &&
TokStart[1] == '0' && TokStart[2] == 'x' &&
isxdigit(static_cast<unsigned char>(TokStart[3]))) {
int len = CurPtr-TokStart-3;
uint32_t bits = len * 4;
StringRef HexStr(TokStart + 3, len);
if (!std::all_of(HexStr.begin(), HexStr.end(), isxdigit)) {
// Bad token, return it as an error.
CurPtr = TokStart+3;
return lltok::Error;
}
APInt Tmp(bits, HexStr, 16);
uint32_t activeBits = Tmp.getActiveBits();
if (activeBits > 0 && activeBits < bits)
Tmp = Tmp.trunc(activeBits);
APSIntVal = APSInt(Tmp, TokStart[0] == 'u');
return lltok::APSInt;
}
// If this is "cc1234", return this as just "cc".
if (TokStart[0] == 'c' && TokStart[1] == 'c') {
CurPtr = TokStart+2;
return lltok::kw_cc;
}
// Finally, if this isn't known, return an error.
CurPtr = TokStart+1;
return lltok::Error;
}
/// Lex all tokens that start with a 0x prefix, knowing they match and are not
/// labels.
/// HexFPConstant 0x[0-9A-Fa-f]+
/// HexFP80Constant 0xK[0-9A-Fa-f]+
/// HexFP128Constant 0xL[0-9A-Fa-f]+
/// HexPPC128Constant 0xM[0-9A-Fa-f]+
/// HexHalfConstant 0xH[0-9A-Fa-f]+
lltok::Kind LLLexer::Lex0x() {
CurPtr = TokStart + 2;
char Kind;
if ((CurPtr[0] >= 'K' && CurPtr[0] <= 'M') || CurPtr[0] == 'H') {
Kind = *CurPtr++;
} else {
Kind = 'J';
}
if (!isxdigit(static_cast<unsigned char>(CurPtr[0]))) {
// Bad token, return it as an error.
CurPtr = TokStart+1;
return lltok::Error;
}
while (isxdigit(static_cast<unsigned char>(CurPtr[0])))
++CurPtr;
if (Kind == 'J') {
// HexFPConstant - Floating point constant represented in IEEE format as a
// hexadecimal number for when exponential notation is not precise enough.
// Half, Float, and double only.
APFloatVal = APFloat(BitsToDouble(HexIntToVal(TokStart+2, CurPtr)));
return lltok::APFloat;
}
uint64_t Pair[2];
switch (Kind) {
default: llvm_unreachable("Unknown kind!");
case 'K':
// F80HexFPConstant - x87 long double in hexadecimal format (10 bytes)
FP80HexToIntPair(TokStart+3, CurPtr, Pair);
APFloatVal = APFloat(APFloat::x87DoubleExtended, APInt(80, Pair));
return lltok::APFloat;
case 'L':
// F128HexFPConstant - IEEE 128-bit in hexadecimal format (16 bytes)
HexToIntPair(TokStart+3, CurPtr, Pair);
APFloatVal = APFloat(APFloat::IEEEquad, APInt(128, Pair));
return lltok::APFloat;
case 'M':
// PPC128HexFPConstant - PowerPC 128-bit in hexadecimal format (16 bytes)
HexToIntPair(TokStart+3, CurPtr, Pair);
APFloatVal = APFloat(APFloat::PPCDoubleDouble, APInt(128, Pair));
return lltok::APFloat;
case 'H':
APFloatVal = APFloat(APFloat::IEEEhalf,
APInt(16,HexIntToVal(TokStart+3, CurPtr)));
return lltok::APFloat;
}
}
/// Lex tokens for a label or a numeric constant, possibly starting with -.
/// Label [-a-zA-Z$._0-9]+:
/// NInteger -[0-9]+
/// FPConstant [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
/// PInteger [0-9]+
/// HexFPConstant 0x[0-9A-Fa-f]+
/// HexFP80Constant 0xK[0-9A-Fa-f]+
/// HexFP128Constant 0xL[0-9A-Fa-f]+
/// HexPPC128Constant 0xM[0-9A-Fa-f]+
lltok::Kind LLLexer::LexDigitOrNegative() {
// If the letter after the negative is not a number, this is probably a label.
if (!isdigit(static_cast<unsigned char>(TokStart[0])) &&
!isdigit(static_cast<unsigned char>(CurPtr[0]))) {
// Okay, this is not a number after the -, it's probably a label.
if (const char *End = isLabelTail(CurPtr)) {
StrVal.assign(TokStart, End-1);
CurPtr = End;
return lltok::LabelStr;
}
return lltok::Error;
}
// At this point, it is either a label, int or fp constant.
// Skip digits, we have at least one.
for (; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
/*empty*/;
// Check to see if this really is a label afterall, e.g. "-1:".
if (isLabelChar(CurPtr[0]) || CurPtr[0] == ':') {
if (const char *End = isLabelTail(CurPtr)) {
StrVal.assign(TokStart, End-1);
CurPtr = End;
return lltok::LabelStr;
}
}
// If the next character is a '.', then it is a fp value, otherwise its
// integer.
if (CurPtr[0] != '.') {
if (TokStart[0] == '0' && TokStart[1] == 'x')
return Lex0x();
APSIntVal = APSInt(StringRef(TokStart, CurPtr - TokStart));
return lltok::APSInt;
}
++CurPtr;
// Skip over [0-9]*([eE][-+]?[0-9]+)?
while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
if (isdigit(static_cast<unsigned char>(CurPtr[1])) ||
((CurPtr[1] == '-' || CurPtr[1] == '+') &&
isdigit(static_cast<unsigned char>(CurPtr[2])))) {
CurPtr += 2;
while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
}
}
APFloatVal = APFloat(std::atof(TokStart));
return lltok::APFloat;
}
/// Lex a floating point constant starting with +.
/// FPConstant [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
lltok::Kind LLLexer::LexPositive() {
// If the letter after the negative is a number, this is probably not a
// label.
if (!isdigit(static_cast<unsigned char>(CurPtr[0])))
return lltok::Error;
// Skip digits.
for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
/*empty*/;
// At this point, we need a '.'.
if (CurPtr[0] != '.') {
CurPtr = TokStart+1;
return lltok::Error;
}
++CurPtr;
// Skip over [0-9]*([eE][-+]?[0-9]+)?
while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
if (isdigit(static_cast<unsigned char>(CurPtr[1])) ||
((CurPtr[1] == '-' || CurPtr[1] == '+') &&
isdigit(static_cast<unsigned char>(CurPtr[2])))) {
CurPtr += 2;
while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
}
}
APFloatVal = APFloat(std::atof(TokStart));
return lltok::APFloat;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/AsmParser/CMakeLists.txt | # AsmParser
add_llvm_library(LLVMAsmParser
LLLexer.cpp
LLParser.cpp
Parser.cpp
ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/Analysis
DEPENDS
intrinsics_gen
)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/AsmParser/LLParser.cpp | //===-- LLParser.cpp - Parser Class ---------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the parser class for .ll files.
//
//===----------------------------------------------------------------------===//
#include "LLParser.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/AsmParser/SlotMapping.h"
#include "llvm/IR/AutoUpgrade.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/ValueSymbolTable.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
static std::string getTypeString(Type *T) {
std::string Result;
raw_string_ostream Tmp(Result);
Tmp << *T;
return Tmp.str();
}
/// Run: module ::= toplevelentity*
bool LLParser::Run() {
// Prime the lexer.
Lex.Lex();
return ParseTopLevelEntities() ||
ValidateEndOfModule();
}
/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
/// module.
bool LLParser::ValidateEndOfModule() {
for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
// Handle any function attribute group forward references.
for (std::map<Value*, std::vector<unsigned> >::iterator
I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
I != E; ++I) {
Value *V = I->first;
std::vector<unsigned> &Vec = I->second;
AttrBuilder B;
for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
VI != VE; ++VI)
B.merge(NumberedAttrBuilders[*VI]);
if (Function *Fn = dyn_cast<Function>(V)) {
AttributeSet AS = Fn->getAttributes();
AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
AS.getFnAttributes());
FnAttrs.merge(B);
// If the alignment was parsed as an attribute, move to the alignment
// field.
if (FnAttrs.hasAlignmentAttr()) {
Fn->setAlignment(FnAttrs.getAlignment());
FnAttrs.removeAttribute(Attribute::Alignment);
}
AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
AttributeSet::get(Context,
AttributeSet::FunctionIndex,
FnAttrs));
Fn->setAttributes(AS);
} else if (CallInst *CI = dyn_cast<CallInst>(V)) {
AttributeSet AS = CI->getAttributes();
AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
AS.getFnAttributes());
FnAttrs.merge(B);
AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
AttributeSet::get(Context,
AttributeSet::FunctionIndex,
FnAttrs));
CI->setAttributes(AS);
} else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
AttributeSet AS = II->getAttributes();
AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
AS.getFnAttributes());
FnAttrs.merge(B);
AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
AttributeSet::get(Context,
AttributeSet::FunctionIndex,
FnAttrs));
II->setAttributes(AS);
} else {
llvm_unreachable("invalid object with forward attribute group reference");
}
}
// If there are entries in ForwardRefBlockAddresses at this point, the
// function was never defined.
if (!ForwardRefBlockAddresses.empty())
return Error(ForwardRefBlockAddresses.begin()->first.Loc,
"expected function name in blockaddress");
for (const auto &NT : NumberedTypes)
if (NT.second.second.isValid())
return Error(NT.second.second,
"use of undefined type '%" + Twine(NT.first) + "'");
for (StringMap<std::pair<Type*, LocTy> >::iterator I =
NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
if (I->second.second.isValid())
return Error(I->second.second,
"use of undefined type named '" + I->getKey() + "'");
if (!ForwardRefComdats.empty())
return Error(ForwardRefComdats.begin()->second,
"use of undefined comdat '$" +
ForwardRefComdats.begin()->first + "'");
if (!ForwardRefVals.empty())
return Error(ForwardRefVals.begin()->second.second,
"use of undefined value '@" + ForwardRefVals.begin()->first +
"'");
if (!ForwardRefValIDs.empty())
return Error(ForwardRefValIDs.begin()->second.second,
"use of undefined value '@" +
Twine(ForwardRefValIDs.begin()->first) + "'");
if (!ForwardRefMDNodes.empty())
return Error(ForwardRefMDNodes.begin()->second.second,
"use of undefined metadata '!" +
Twine(ForwardRefMDNodes.begin()->first) + "'");
// Resolve metadata cycles.
for (auto &N : NumberedMetadata) {
if (N.second && !N.second->isResolved())
N.second->resolveCycles();
}
// Look for intrinsic functions and CallInst that need to be upgraded
for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
UpgradeDebugInfo(*M);
if (!Slots)
return false;
// Initialize the slot mapping.
// Because by this point we've parsed and validated everything, we can "steal"
// the mapping from LLParser as it doesn't need it anymore.
Slots->GlobalValues = std::move(NumberedVals);
Slots->MetadataNodes = std::move(NumberedMetadata);
return false;
}
//===----------------------------------------------------------------------===//
// Top-Level Entities
//===----------------------------------------------------------------------===//
bool LLParser::ParseTopLevelEntities() {
while (1) {
switch (Lex.getKind()) {
default: return TokError("expected top-level entity");
case lltok::Eof: return false;
case lltok::kw_declare: if (ParseDeclare()) return true; break;
case lltok::kw_define: if (ParseDefine()) return true; break;
case lltok::kw_module: if (ParseModuleAsm()) return true; break;
case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
case lltok::LocalVar: if (ParseNamedType()) return true; break;
case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
case lltok::ComdatVar: if (parseComdat()) return true; break;
case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
// The Global variable production with no name can have many different
// optional leading prefixes, the production is:
// GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
// OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
// ('constant'|'global') ...
case lltok::kw_private: // OptionalLinkage
case lltok::kw_internal: // OptionalLinkage
case lltok::kw_weak: // OptionalLinkage
case lltok::kw_weak_odr: // OptionalLinkage
case lltok::kw_linkonce: // OptionalLinkage
case lltok::kw_linkonce_odr: // OptionalLinkage
case lltok::kw_appending: // OptionalLinkage
case lltok::kw_common: // OptionalLinkage
case lltok::kw_extern_weak: // OptionalLinkage
case lltok::kw_external: // OptionalLinkage
case lltok::kw_default: // OptionalVisibility
case lltok::kw_hidden: // OptionalVisibility
case lltok::kw_protected: // OptionalVisibility
case lltok::kw_dllimport: // OptionalDLLStorageClass
case lltok::kw_dllexport: // OptionalDLLStorageClass
case lltok::kw_thread_local: // OptionalThreadLocal
case lltok::kw_addrspace: // OptionalAddrSpace
case lltok::kw_constant: // GlobalType
case lltok::kw_global: { // GlobalType
unsigned Linkage, Visibility, DLLStorageClass;
bool UnnamedAddr;
GlobalVariable::ThreadLocalMode TLM;
bool HasLinkage;
if (ParseOptionalLinkage(Linkage, HasLinkage) ||
ParseOptionalVisibility(Visibility) ||
ParseOptionalDLLStorageClass(DLLStorageClass) ||
ParseOptionalThreadLocal(TLM) ||
parseOptionalUnnamedAddr(UnnamedAddr) ||
ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
DLLStorageClass, TLM, UnnamedAddr))
return true;
break;
}
case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
case lltok::kw_uselistorder_bb:
if (ParseUseListOrderBB()) return true; break;
}
}
}
/// toplevelentity
/// ::= 'module' 'asm' STRINGCONSTANT
bool LLParser::ParseModuleAsm() {
assert(Lex.getKind() == lltok::kw_module);
Lex.Lex();
std::string AsmStr;
if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
ParseStringConstant(AsmStr)) return true;
M->appendModuleInlineAsm(AsmStr);
return false;
}
/// toplevelentity
/// ::= 'target' 'triple' '=' STRINGCONSTANT
/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
bool LLParser::ParseTargetDefinition() {
assert(Lex.getKind() == lltok::kw_target);
std::string Str;
switch (Lex.Lex()) {
default: return TokError("unknown target property");
case lltok::kw_triple:
Lex.Lex();
if (ParseToken(lltok::equal, "expected '=' after target triple") ||
ParseStringConstant(Str))
return true;
M->setTargetTriple(Str);
return false;
case lltok::kw_datalayout:
Lex.Lex();
if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
ParseStringConstant(Str))
return true;
M->setDataLayout(Str);
return false;
}
}
/// toplevelentity
/// ::= 'deplibs' '=' '[' ']'
/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
/// FIXME: Remove in 4.0. Currently parse, but ignore.
bool LLParser::ParseDepLibs() {
assert(Lex.getKind() == lltok::kw_deplibs);
Lex.Lex();
if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
ParseToken(lltok::lsquare, "expected '=' after deplibs"))
return true;
if (EatIfPresent(lltok::rsquare))
return false;
do {
std::string Str;
if (ParseStringConstant(Str)) return true;
} while (EatIfPresent(lltok::comma));
return ParseToken(lltok::rsquare, "expected ']' at end of list");
}
/// ParseUnnamedType:
/// ::= LocalVarID '=' 'type' type
bool LLParser::ParseUnnamedType() {
LocTy TypeLoc = Lex.getLoc();
unsigned TypeID = Lex.getUIntVal();
Lex.Lex(); // eat LocalVarID;
if (ParseToken(lltok::equal, "expected '=' after name") ||
ParseToken(lltok::kw_type, "expected 'type' after '='"))
return true;
Type *Result = nullptr;
if (ParseStructDefinition(TypeLoc, "",
NumberedTypes[TypeID], Result)) return true;
if (!isa<StructType>(Result)) {
std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
if (Entry.first)
return Error(TypeLoc, "non-struct types may not be recursive");
Entry.first = Result;
Entry.second = SMLoc();
}
return false;
}
/// toplevelentity
/// ::= LocalVar '=' 'type' type
bool LLParser::ParseNamedType() {
std::string Name = Lex.getStrVal();
LocTy NameLoc = Lex.getLoc();
Lex.Lex(); // eat LocalVar.
if (ParseToken(lltok::equal, "expected '=' after name") ||
ParseToken(lltok::kw_type, "expected 'type' after name"))
return true;
Type *Result = nullptr;
if (ParseStructDefinition(NameLoc, Name,
NamedTypes[Name], Result)) return true;
if (!isa<StructType>(Result)) {
std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
if (Entry.first)
return Error(NameLoc, "non-struct types may not be recursive");
Entry.first = Result;
Entry.second = SMLoc();
}
return false;
}
/// toplevelentity
/// ::= 'declare' FunctionHeader
bool LLParser::ParseDeclare() {
assert(Lex.getKind() == lltok::kw_declare);
Lex.Lex();
Function *F;
return ParseFunctionHeader(F, false);
}
/// toplevelentity
/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
bool LLParser::ParseDefine() {
assert(Lex.getKind() == lltok::kw_define);
Lex.Lex();
Function *F;
return ParseFunctionHeader(F, true) ||
ParseOptionalFunctionMetadata(*F) ||
ParseFunctionBody(*F);
}
/// ParseGlobalType
/// ::= 'constant'
/// ::= 'global'
bool LLParser::ParseGlobalType(bool &IsConstant) {
if (Lex.getKind() == lltok::kw_constant)
IsConstant = true;
else if (Lex.getKind() == lltok::kw_global)
IsConstant = false;
else {
IsConstant = false;
return TokError("expected 'global' or 'constant'");
}
Lex.Lex();
return false;
}
/// ParseUnnamedGlobal:
/// OptionalVisibility ALIAS ...
/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
/// ... -> global variable
/// GlobalID '=' OptionalVisibility ALIAS ...
/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
/// ... -> global variable
bool LLParser::ParseUnnamedGlobal() {
unsigned VarID = NumberedVals.size();
std::string Name;
LocTy NameLoc = Lex.getLoc();
// Handle the GlobalID form.
if (Lex.getKind() == lltok::GlobalID) {
if (Lex.getUIntVal() != VarID)
return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Twine(VarID) + "'");
Lex.Lex(); // eat GlobalID;
if (ParseToken(lltok::equal, "expected '=' after name"))
return true;
}
bool HasLinkage;
unsigned Linkage, Visibility, DLLStorageClass;
GlobalVariable::ThreadLocalMode TLM;
bool UnnamedAddr;
if (ParseOptionalLinkage(Linkage, HasLinkage) ||
ParseOptionalVisibility(Visibility) ||
ParseOptionalDLLStorageClass(DLLStorageClass) ||
ParseOptionalThreadLocal(TLM) ||
parseOptionalUnnamedAddr(UnnamedAddr))
return true;
if (Lex.getKind() != lltok::kw_alias)
return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
DLLStorageClass, TLM, UnnamedAddr);
return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
UnnamedAddr);
}
/// ParseNamedGlobal:
/// GlobalVar '=' OptionalVisibility ALIAS ...
/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
/// ... -> global variable
bool LLParser::ParseNamedGlobal() {
assert(Lex.getKind() == lltok::GlobalVar);
LocTy NameLoc = Lex.getLoc();
std::string Name = Lex.getStrVal();
Lex.Lex();
bool HasLinkage;
unsigned Linkage, Visibility, DLLStorageClass;
GlobalVariable::ThreadLocalMode TLM;
bool UnnamedAddr;
if (ParseToken(lltok::equal, "expected '=' in global variable") ||
ParseOptionalLinkage(Linkage, HasLinkage) ||
ParseOptionalVisibility(Visibility) ||
ParseOptionalDLLStorageClass(DLLStorageClass) ||
ParseOptionalThreadLocal(TLM) ||
parseOptionalUnnamedAddr(UnnamedAddr))
return true;
if (Lex.getKind() != lltok::kw_alias)
return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
DLLStorageClass, TLM, UnnamedAddr);
return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
UnnamedAddr);
}
bool LLParser::parseComdat() {
assert(Lex.getKind() == lltok::ComdatVar);
std::string Name = Lex.getStrVal();
LocTy NameLoc = Lex.getLoc();
Lex.Lex();
if (ParseToken(lltok::equal, "expected '=' here"))
return true;
if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
return TokError("expected comdat type");
Comdat::SelectionKind SK;
switch (Lex.getKind()) {
default:
return TokError("unknown selection kind");
case lltok::kw_any:
SK = Comdat::Any;
break;
case lltok::kw_exactmatch:
SK = Comdat::ExactMatch;
break;
case lltok::kw_largest:
SK = Comdat::Largest;
break;
case lltok::kw_noduplicates:
SK = Comdat::NoDuplicates;
break;
case lltok::kw_samesize:
SK = Comdat::SameSize;
break;
}
Lex.Lex();
// See if the comdat was forward referenced, if so, use the comdat.
Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
Comdat *C;
if (I != ComdatSymTab.end())
C = &I->second;
else
C = M->getOrInsertComdat(Name);
C->setSelectionKind(SK);
return false;
}
// MDString:
// ::= '!' STRINGCONSTANT
bool LLParser::ParseMDString(MDString *&Result) {
std::string Str;
if (ParseStringConstant(Str)) return true;
llvm::UpgradeMDStringConstant(Str);
Result = MDString::get(Context, Str);
return false;
}
// MDNode:
// ::= '!' MDNodeNumber
bool LLParser::ParseMDNodeID(MDNode *&Result) {
// !{ ..., !42, ... }
unsigned MID = 0;
if (ParseUInt32(MID))
return true;
// If not a forward reference, just return it now.
if (NumberedMetadata.count(MID)) {
Result = NumberedMetadata[MID];
return false;
}
// Otherwise, create MDNode forward reference.
auto &FwdRef = ForwardRefMDNodes[MID];
FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Result = FwdRef.first.get();
NumberedMetadata[MID].reset(Result);
return false;
}
/// ParseNamedMetadata:
/// !foo = !{ !1, !2 }
bool LLParser::ParseNamedMetadata() {
assert(Lex.getKind() == lltok::MetadataVar);
std::string Name = Lex.getStrVal();
Lex.Lex();
if (ParseToken(lltok::equal, "expected '=' here") ||
ParseToken(lltok::exclaim, "Expected '!' here") ||
ParseToken(lltok::lbrace, "Expected '{' here"))
return true;
NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
if (Lex.getKind() != lltok::rbrace)
do {
if (ParseToken(lltok::exclaim, "Expected '!' here"))
return true;
MDNode *N = nullptr;
if (ParseMDNodeID(N)) return true;
NMD->addOperand(N);
} while (EatIfPresent(lltok::comma));
return ParseToken(lltok::rbrace, "expected end of metadata node");
}
/// ParseStandaloneMetadata:
/// !42 = !{...}
bool LLParser::ParseStandaloneMetadata() {
assert(Lex.getKind() == lltok::exclaim);
Lex.Lex();
unsigned MetadataID = 0;
MDNode *Init;
if (ParseUInt32(MetadataID) ||
ParseToken(lltok::equal, "expected '=' here"))
return true;
// Detect common error, from old metadata syntax.
if (Lex.getKind() == lltok::Type)
return TokError("unexpected type in metadata definition");
bool IsDistinct = EatIfPresent(lltok::kw_distinct);
if (Lex.getKind() == lltok::MetadataVar) {
if (ParseSpecializedMDNode(Init, IsDistinct))
return true;
} else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
ParseMDTuple(Init, IsDistinct))
return true;
// See if this was forward referenced, if so, handle it.
auto FI = ForwardRefMDNodes.find(MetadataID);
if (FI != ForwardRefMDNodes.end()) {
FI->second.first->replaceAllUsesWith(Init);
ForwardRefMDNodes.erase(FI);
assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
} else {
if (NumberedMetadata.count(MetadataID))
return TokError("Metadata id is already used");
NumberedMetadata[MetadataID].reset(Init);
}
return false;
}
static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
(GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
}
/// ParseAlias:
/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
/// OptionalDLLStorageClass OptionalThreadLocal
/// OptionalUnnamedAddr 'alias' Aliasee
///
/// Aliasee
/// ::= TypeAndValue
///
/// Everything through OptionalUnnamedAddr has already been parsed.
///
bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
unsigned Visibility, unsigned DLLStorageClass,
GlobalVariable::ThreadLocalMode TLM,
bool UnnamedAddr) {
assert(Lex.getKind() == lltok::kw_alias);
Lex.Lex();
GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
if(!GlobalAlias::isValidLinkage(Linkage))
return Error(NameLoc, "invalid linkage type for alias");
if (!isValidVisibilityForLinkage(Visibility, L))
return Error(NameLoc,
"symbol with local linkage must have default visibility");
Constant *Aliasee;
LocTy AliaseeLoc = Lex.getLoc();
if (Lex.getKind() != lltok::kw_bitcast &&
Lex.getKind() != lltok::kw_getelementptr &&
Lex.getKind() != lltok::kw_addrspacecast &&
Lex.getKind() != lltok::kw_inttoptr) {
if (ParseGlobalTypeAndValue(Aliasee))
return true;
} else {
// The bitcast dest type is not present, it is implied by the dest type.
ValID ID;
if (ParseValID(ID))
return true;
if (ID.Kind != ValID::t_Constant)
return Error(AliaseeLoc, "invalid aliasee");
Aliasee = ID.ConstantVal;
}
Type *AliaseeType = Aliasee->getType();
auto *PTy = dyn_cast<PointerType>(AliaseeType);
if (!PTy)
return Error(AliaseeLoc, "An alias must have pointer type");
// Okay, create the alias but do not insert it into the module yet.
std::unique_ptr<GlobalAlias> GA(
GlobalAlias::create(PTy, (GlobalValue::LinkageTypes)Linkage, Name,
Aliasee, /*Parent*/ nullptr));
GA->setThreadLocalMode(TLM);
GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
GA->setUnnamedAddr(UnnamedAddr);
if (Name.empty())
NumberedVals.push_back(GA.get());
// See if this value already exists in the symbol table. If so, it is either
// a redefinition or a definition of a forward reference.
if (GlobalValue *Val = M->getNamedValue(Name)) {
// See if this was a redefinition. If so, there is no entry in
// ForwardRefVals.
std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
I = ForwardRefVals.find(Name);
if (I == ForwardRefVals.end())
return Error(NameLoc, "redefinition of global named '@" + Name + "'");
// Otherwise, this was a definition of forward ref. Verify that types
// agree.
if (Val->getType() != GA->getType())
return Error(NameLoc,
"forward reference and definition of alias have different types");
// If they agree, just RAUW the old value with the alias and remove the
// forward ref info.
Val->replaceAllUsesWith(GA.get());
Val->eraseFromParent();
ForwardRefVals.erase(I);
}
// Insert into the module, we know its name won't collide now.
M->getAliasList().push_back(GA.get());
assert(GA->getName() == Name && "Should not be a name conflict!");
// The module owns this now
GA.release();
return false;
}
/// ParseGlobal
/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
/// OptionalExternallyInitialized GlobalType Type Const
/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
/// OptionalExternallyInitialized GlobalType Type Const
///
/// Everything up to and including OptionalUnnamedAddr has been parsed
/// already.
///
bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
unsigned Linkage, bool HasLinkage,
unsigned Visibility, unsigned DLLStorageClass,
GlobalVariable::ThreadLocalMode TLM,
bool UnnamedAddr) {
if (!isValidVisibilityForLinkage(Visibility, Linkage))
return Error(NameLoc,
"symbol with local linkage must have default visibility");
unsigned AddrSpace;
bool IsConstant, IsExternallyInitialized;
LocTy IsExternallyInitializedLoc;
LocTy TyLoc;
Type *Ty = nullptr;
if (ParseOptionalAddrSpace(AddrSpace) ||
ParseOptionalToken(lltok::kw_externally_initialized,
IsExternallyInitialized,
&IsExternallyInitializedLoc) ||
ParseGlobalType(IsConstant) ||
ParseType(Ty, TyLoc))
return true;
// If the linkage is specified and is external, then no initializer is
// present.
Constant *Init = nullptr;
if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Linkage != GlobalValue::ExternalLinkage)) {
if (ParseGlobalValue(Ty, Init))
return true;
}
if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
return Error(TyLoc, "invalid type for global variable");
GlobalValue *GVal = nullptr;
// See if the global was forward referenced, if so, use the global.
if (!Name.empty()) {
GVal = M->getNamedValue(Name);
if (GVal) {
if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
return Error(NameLoc, "redefinition of global '@" + Name + "'");
}
} else {
std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
I = ForwardRefValIDs.find(NumberedVals.size());
if (I != ForwardRefValIDs.end()) {
GVal = I->second.first;
ForwardRefValIDs.erase(I);
}
}
GlobalVariable *GV;
if (!GVal) {
GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
Name, nullptr, GlobalVariable::NotThreadLocal,
AddrSpace);
} else {
if (GVal->getValueType() != Ty)
return Error(TyLoc,
"forward reference and definition of global have different types");
GV = cast<GlobalVariable>(GVal);
// Move the forward-reference to the correct spot in the module.
M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
}
if (Name.empty())
NumberedVals.push_back(GV);
// Set the parsed properties on the global.
if (Init)
GV->setInitializer(Init);
GV->setConstant(IsConstant);
GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
GV->setExternallyInitialized(IsExternallyInitialized);
GV->setThreadLocalMode(TLM);
GV->setUnnamedAddr(UnnamedAddr);
// Parse attributes on the global.
while (Lex.getKind() == lltok::comma) {
Lex.Lex();
if (Lex.getKind() == lltok::kw_section) {
Lex.Lex();
GV->setSection(Lex.getStrVal());
if (ParseToken(lltok::StringConstant, "expected global section string"))
return true;
} else if (Lex.getKind() == lltok::kw_align) {
unsigned Alignment;
if (ParseOptionalAlignment(Alignment)) return true;
GV->setAlignment(Alignment);
} else {
Comdat *C;
if (parseOptionalComdat(Name, C))
return true;
if (C)
GV->setComdat(C);
else
return TokError("unknown global variable property!");
}
}
return false;
}
/// ParseUnnamedAttrGrp
/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
bool LLParser::ParseUnnamedAttrGrp() {
assert(Lex.getKind() == lltok::kw_attributes);
LocTy AttrGrpLoc = Lex.getLoc();
Lex.Lex();
if (Lex.getKind() != lltok::AttrGrpID)
return TokError("expected attribute group id");
unsigned VarID = Lex.getUIntVal();
std::vector<unsigned> unused;
LocTy BuiltinLoc;
Lex.Lex();
if (ParseToken(lltok::equal, "expected '=' here") ||
ParseToken(lltok::lbrace, "expected '{' here") ||
ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
BuiltinLoc) ||
ParseToken(lltok::rbrace, "expected end of attribute group"))
return true;
if (!NumberedAttrBuilders[VarID].hasAttributes())
return Error(AttrGrpLoc, "attribute group has no attributes");
return false;
}
/// ParseFnAttributeValuePairs
/// ::= <attr> | <attr> '=' <value>
bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
std::vector<unsigned> &FwdRefAttrGrps,
bool inAttrGrp, LocTy &BuiltinLoc) {
bool HaveError = false;
B.clear();
while (true) {
lltok::Kind Token = Lex.getKind();
if (Token == lltok::kw_builtin)
BuiltinLoc = Lex.getLoc();
switch (Token) {
default:
if (!inAttrGrp) return HaveError;
return Error(Lex.getLoc(), "unterminated attribute group");
case lltok::rbrace:
// Finished.
return false;
case lltok::AttrGrpID: {
// Allow a function to reference an attribute group:
//
// define void @foo() #1 { ... }
if (inAttrGrp)
HaveError |=
Error(Lex.getLoc(),
"cannot have an attribute group reference in an attribute group");
unsigned AttrGrpNum = Lex.getUIntVal();
if (inAttrGrp) break;
// Save the reference to the attribute group. We'll fill it in later.
FwdRefAttrGrps.push_back(AttrGrpNum);
break;
}
// Target-dependent attributes:
case lltok::StringConstant: {
std::string Attr = Lex.getStrVal();
Lex.Lex();
std::string Val;
if (EatIfPresent(lltok::equal) &&
ParseStringConstant(Val))
return true;
B.addAttribute(Attr, Val);
continue;
}
// Target-independent attributes:
case lltok::kw_align: {
// As a hack, we allow function alignment to be initially parsed as an
// attribute on a function declaration/definition or added to an attribute
// group and later moved to the alignment field.
unsigned Alignment;
if (inAttrGrp) {
Lex.Lex();
if (ParseToken(lltok::equal, "expected '=' here") ||
ParseUInt32(Alignment))
return true;
} else {
if (ParseOptionalAlignment(Alignment))
return true;
}
B.addAlignmentAttr(Alignment);
continue;
}
case lltok::kw_alignstack: {
unsigned Alignment;
if (inAttrGrp) {
Lex.Lex();
if (ParseToken(lltok::equal, "expected '=' here") ||
ParseUInt32(Alignment))
return true;
} else {
if (ParseOptionalStackAlignment(Alignment))
return true;
}
B.addStackAlignmentAttr(Alignment);
continue;
}
case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
case lltok::kw_noimplicitfloat:
B.addAttribute(Attribute::NoImplicitFloat); break;
case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
case lltok::kw_returns_twice:
B.addAttribute(Attribute::ReturnsTwice); break;
case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
case lltok::kw_sspstrong:
B.addAttribute(Attribute::StackProtectStrong); break;
case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
case lltok::kw_sanitize_address:
B.addAttribute(Attribute::SanitizeAddress); break;
case lltok::kw_sanitize_thread:
B.addAttribute(Attribute::SanitizeThread); break;
case lltok::kw_sanitize_memory:
B.addAttribute(Attribute::SanitizeMemory); break;
case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
// Error handling.
case lltok::kw_inreg:
case lltok::kw_signext:
case lltok::kw_zeroext:
HaveError |=
Error(Lex.getLoc(),
"invalid use of attribute on a function");
break;
case lltok::kw_byval:
case lltok::kw_dereferenceable:
case lltok::kw_dereferenceable_or_null:
case lltok::kw_inalloca:
case lltok::kw_nest:
case lltok::kw_noalias:
case lltok::kw_nocapture:
case lltok::kw_nonnull:
case lltok::kw_returned:
case lltok::kw_sret:
HaveError |=
Error(Lex.getLoc(),
"invalid use of parameter-only attribute on a function");
break;
}
Lex.Lex();
}
}
//===----------------------------------------------------------------------===//
// GlobalValue Reference/Resolution Routines.
//===----------------------------------------------------------------------===//
/// GetGlobalVal - Get a value with the specified name or ID, creating a
/// forward reference record if needed. This can return null if the value
/// exists but does not have the right type.
GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
LocTy Loc) {
PointerType *PTy = dyn_cast<PointerType>(Ty);
if (!PTy) {
Error(Loc, "global variable reference must have pointer type");
return nullptr;
}
// Look this name up in the normal function symbol table.
GlobalValue *Val =
cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
// If this is a forward reference for the value, see if we already created a
// forward ref record.
if (!Val) {
std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
I = ForwardRefVals.find(Name);
if (I != ForwardRefVals.end())
Val = I->second.first;
}
// If we have the value in the symbol table or fwd-ref table, return it.
if (Val) {
if (Val->getType() == Ty) return Val;
Error(Loc, "'@" + Name + "' defined with type '" +
getTypeString(Val->getType()) + "'");
return nullptr;
}
// Otherwise, create a new forward reference for this value and remember it.
GlobalValue *FwdVal;
if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
else
FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
GlobalValue::ExternalWeakLinkage, nullptr, Name,
nullptr, GlobalVariable::NotThreadLocal,
PTy->getAddressSpace());
ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
return FwdVal;
}
GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
PointerType *PTy = dyn_cast<PointerType>(Ty);
if (!PTy) {
Error(Loc, "global variable reference must have pointer type");
return nullptr;
}
GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
// If this is a forward reference for the value, see if we already created a
// forward ref record.
if (!Val) {
std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
I = ForwardRefValIDs.find(ID);
if (I != ForwardRefValIDs.end())
Val = I->second.first;
}
// If we have the value in the symbol table or fwd-ref table, return it.
if (Val) {
if (Val->getType() == Ty) return Val;
Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
getTypeString(Val->getType()) + "'");
return nullptr;
}
// Otherwise, create a new forward reference for this value and remember it.
GlobalValue *FwdVal;
if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
else
FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
GlobalValue::ExternalWeakLinkage, nullptr, "");
ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
return FwdVal;
}
//===----------------------------------------------------------------------===//
// Comdat Reference/Resolution Routines.
//===----------------------------------------------------------------------===//
Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
// Look this name up in the comdat symbol table.
Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
if (I != ComdatSymTab.end())
return &I->second;
// Otherwise, create a new forward reference for this value and remember it.
Comdat *C = M->getOrInsertComdat(Name);
ForwardRefComdats[Name] = Loc;
return C;
}
//===----------------------------------------------------------------------===//
// Helper Routines.
//===----------------------------------------------------------------------===//
/// ParseToken - If the current token has the specified kind, eat it and return
/// success. Otherwise, emit the specified error and return failure.
bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
if (Lex.getKind() != T)
return TokError(ErrMsg);
Lex.Lex();
return false;
}
/// ParseStringConstant
/// ::= StringConstant
bool LLParser::ParseStringConstant(std::string &Result) {
if (Lex.getKind() != lltok::StringConstant)
return TokError("expected string constant");
Result = Lex.getStrVal();
Lex.Lex();
return false;
}
/// ParseUInt32
/// ::= uint32
bool LLParser::ParseUInt32(unsigned &Val) {
if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
return TokError("expected integer");
uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
if (Val64 != unsigned(Val64))
return TokError("expected 32-bit integer (too large)");
Val = Val64;
Lex.Lex();
return false;
}
/// ParseUInt64
/// ::= uint64
bool LLParser::ParseUInt64(uint64_t &Val) {
if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
return TokError("expected integer");
Val = Lex.getAPSIntVal().getLimitedValue();
Lex.Lex();
return false;
}
/// ParseTLSModel
/// := 'localdynamic'
/// := 'initialexec'
/// := 'localexec'
bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
switch (Lex.getKind()) {
default:
return TokError("expected localdynamic, initialexec or localexec");
case lltok::kw_localdynamic:
TLM = GlobalVariable::LocalDynamicTLSModel;
break;
case lltok::kw_initialexec:
TLM = GlobalVariable::InitialExecTLSModel;
break;
case lltok::kw_localexec:
TLM = GlobalVariable::LocalExecTLSModel;
break;
}
Lex.Lex();
return false;
}
/// ParseOptionalThreadLocal
/// := /*empty*/
/// := 'thread_local'
/// := 'thread_local' '(' tlsmodel ')'
bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
TLM = GlobalVariable::NotThreadLocal;
if (!EatIfPresent(lltok::kw_thread_local))
return false;
TLM = GlobalVariable::GeneralDynamicTLSModel;
if (Lex.getKind() == lltok::lparen) {
Lex.Lex();
return ParseTLSModel(TLM) ||
ParseToken(lltok::rparen, "expected ')' after thread local model");
}
return false;
}
/// ParseOptionalAddrSpace
/// := /*empty*/
/// := 'addrspace' '(' uint32 ')'
bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
AddrSpace = 0;
if (!EatIfPresent(lltok::kw_addrspace))
return false;
return ParseToken(lltok::lparen, "expected '(' in address space") ||
ParseUInt32(AddrSpace) ||
ParseToken(lltok::rparen, "expected ')' in address space");
}
/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
bool HaveError = false;
B.clear();
while (1) {
lltok::Kind Token = Lex.getKind();
switch (Token) {
default: // End of attributes.
return HaveError;
case lltok::kw_align: {
unsigned Alignment;
if (ParseOptionalAlignment(Alignment))
return true;
B.addAlignmentAttr(Alignment);
continue;
}
case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
case lltok::kw_dereferenceable: {
uint64_t Bytes;
if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
return true;
B.addDereferenceableAttr(Bytes);
continue;
}
case lltok::kw_dereferenceable_or_null: {
uint64_t Bytes;
if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
return true;
B.addDereferenceableOrNullAttr(Bytes);
continue;
}
case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
case lltok::kw_alignstack:
case lltok::kw_alwaysinline:
case lltok::kw_argmemonly:
case lltok::kw_builtin:
case lltok::kw_inlinehint:
case lltok::kw_jumptable:
case lltok::kw_minsize:
case lltok::kw_naked:
case lltok::kw_nobuiltin:
case lltok::kw_noduplicate:
case lltok::kw_noimplicitfloat:
case lltok::kw_noinline:
case lltok::kw_nonlazybind:
case lltok::kw_noredzone:
case lltok::kw_noreturn:
case lltok::kw_nounwind:
case lltok::kw_optnone:
case lltok::kw_optsize:
case lltok::kw_returns_twice:
case lltok::kw_sanitize_address:
case lltok::kw_sanitize_memory:
case lltok::kw_sanitize_thread:
case lltok::kw_ssp:
case lltok::kw_sspreq:
case lltok::kw_sspstrong:
case lltok::kw_safestack:
case lltok::kw_uwtable:
HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
break;
}
Lex.Lex();
}
}
/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
bool HaveError = false;
B.clear();
while (1) {
lltok::Kind Token = Lex.getKind();
switch (Token) {
default: // End of attributes.
return HaveError;
case lltok::kw_dereferenceable: {
uint64_t Bytes;
if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
return true;
B.addDereferenceableAttr(Bytes);
continue;
}
case lltok::kw_dereferenceable_or_null: {
uint64_t Bytes;
if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
return true;
B.addDereferenceableOrNullAttr(Bytes);
continue;
}
case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
// Error handling.
case lltok::kw_align:
case lltok::kw_byval:
case lltok::kw_inalloca:
case lltok::kw_nest:
case lltok::kw_nocapture:
case lltok::kw_returned:
case lltok::kw_sret:
HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
break;
case lltok::kw_alignstack:
case lltok::kw_alwaysinline:
case lltok::kw_argmemonly:
case lltok::kw_builtin:
case lltok::kw_cold:
case lltok::kw_inlinehint:
case lltok::kw_jumptable:
case lltok::kw_minsize:
case lltok::kw_naked:
case lltok::kw_nobuiltin:
case lltok::kw_noduplicate:
case lltok::kw_noimplicitfloat:
case lltok::kw_noinline:
case lltok::kw_nonlazybind:
case lltok::kw_noredzone:
case lltok::kw_noreturn:
case lltok::kw_nounwind:
case lltok::kw_optnone:
case lltok::kw_optsize:
case lltok::kw_returns_twice:
case lltok::kw_sanitize_address:
case lltok::kw_sanitize_memory:
case lltok::kw_sanitize_thread:
case lltok::kw_ssp:
case lltok::kw_sspreq:
case lltok::kw_sspstrong:
case lltok::kw_safestack:
case lltok::kw_uwtable:
HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
break;
case lltok::kw_readnone:
case lltok::kw_readonly:
HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
}
Lex.Lex();
}
}
/// ParseOptionalLinkage
/// ::= /*empty*/
/// ::= 'private'
/// ::= 'internal'
/// ::= 'weak'
/// ::= 'weak_odr'
/// ::= 'linkonce'
/// ::= 'linkonce_odr'
/// ::= 'available_externally'
/// ::= 'appending'
/// ::= 'common'
/// ::= 'extern_weak'
/// ::= 'external'
bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
HasLinkage = false;
switch (Lex.getKind()) {
default: Res=GlobalValue::ExternalLinkage; return false;
case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
case lltok::kw_available_externally:
Res = GlobalValue::AvailableExternallyLinkage;
break;
case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
}
Lex.Lex();
HasLinkage = true;
return false;
}
/// ParseOptionalVisibility
/// ::= /*empty*/
/// ::= 'default'
/// ::= 'hidden'
/// ::= 'protected'
///
bool LLParser::ParseOptionalVisibility(unsigned &Res) {
switch (Lex.getKind()) {
default: Res = GlobalValue::DefaultVisibility; return false;
case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
}
Lex.Lex();
return false;
}
/// ParseOptionalDLLStorageClass
/// ::= /*empty*/
/// ::= 'dllimport'
/// ::= 'dllexport'
///
bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
switch (Lex.getKind()) {
default: Res = GlobalValue::DefaultStorageClass; return false;
case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
}
Lex.Lex();
return false;
}
/// ParseOptionalCallingConv
/// ::= /*empty*/
/// ::= 'ccc'
/// ::= 'fastcc'
/// ::= 'intel_ocl_bicc'
/// ::= 'coldcc'
/// ::= 'x86_stdcallcc'
/// ::= 'x86_fastcallcc'
/// ::= 'x86_thiscallcc'
/// ::= 'x86_vectorcallcc'
/// ::= 'arm_apcscc'
/// ::= 'arm_aapcscc'
/// ::= 'arm_aapcs_vfpcc'
/// ::= 'msp430_intrcc'
/// ::= 'ptx_kernel'
/// ::= 'ptx_device'
/// ::= 'spir_func'
/// ::= 'spir_kernel'
/// ::= 'x86_64_sysvcc'
/// ::= 'x86_64_win64cc'
/// ::= 'webkit_jscc'
/// ::= 'anyregcc'
/// ::= 'preserve_mostcc'
/// ::= 'preserve_allcc'
/// ::= 'ghccc'
/// ::= 'cc' UINT
///
bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
switch (Lex.getKind()) {
default: CC = CallingConv::C; return false;
case lltok::kw_ccc: CC = CallingConv::C; break;
case lltok::kw_fastcc: CC = CallingConv::Fast; break;
case lltok::kw_coldcc: CC = CallingConv::Cold; break;
case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
case lltok::kw_ghccc: CC = CallingConv::GHC; break;
case lltok::kw_cc: {
Lex.Lex();
return ParseUInt32(CC);
}
}
Lex.Lex();
return false;
}
/// ParseMetadataAttachment
/// ::= !dbg !42
bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
std::string Name = Lex.getStrVal();
Kind = M->getMDKindID(Name);
Lex.Lex();
return ParseMDNode(MD);
}
/// ParseInstructionMetadata
/// ::= !dbg !42 (',' !dbg !57)*
bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
do {
if (Lex.getKind() != lltok::MetadataVar)
return TokError("expected metadata after comma");
unsigned MDK;
MDNode *N;
if (ParseMetadataAttachment(MDK, N))
return true;
Inst.setMetadata(MDK, N);
if (MDK == LLVMContext::MD_tbaa)
InstsWithTBAATag.push_back(&Inst);
// If this is the end of the list, we're done.
} while (EatIfPresent(lltok::comma));
return false;
}
/// ParseOptionalFunctionMetadata
/// ::= (!dbg !57)*
bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
while (Lex.getKind() == lltok::MetadataVar) {
unsigned MDK;
MDNode *N;
if (ParseMetadataAttachment(MDK, N))
return true;
F.setMetadata(MDK, N);
}
return false;
}
/// ParseOptionalAlignment
/// ::= /* empty */
/// ::= 'align' 4
bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
Alignment = 0;
if (!EatIfPresent(lltok::kw_align))
return false;
LocTy AlignLoc = Lex.getLoc();
if (ParseUInt32(Alignment)) return true;
if (!isPowerOf2_32(Alignment))
return Error(AlignLoc, "alignment is not a power of two");
if (Alignment > Value::MaximumAlignment)
return Error(AlignLoc, "huge alignments are not supported yet");
return false;
}
/// ParseOptionalDerefAttrBytes
/// ::= /* empty */
/// ::= AttrKind '(' 4 ')'
///
/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
uint64_t &Bytes) {
assert((AttrKind == lltok::kw_dereferenceable ||
AttrKind == lltok::kw_dereferenceable_or_null) &&
"contract!");
Bytes = 0;
if (!EatIfPresent(AttrKind))
return false;
LocTy ParenLoc = Lex.getLoc();
if (!EatIfPresent(lltok::lparen))
return Error(ParenLoc, "expected '('");
LocTy DerefLoc = Lex.getLoc();
if (ParseUInt64(Bytes)) return true;
ParenLoc = Lex.getLoc();
if (!EatIfPresent(lltok::rparen))
return Error(ParenLoc, "expected ')'");
if (!Bytes)
return Error(DerefLoc, "dereferenceable bytes must be non-zero");
return false;
}
/// ParseOptionalCommaAlign
/// ::=
/// ::= ',' align 4
///
/// This returns with AteExtraComma set to true if it ate an excess comma at the
/// end.
bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
bool &AteExtraComma) {
AteExtraComma = false;
while (EatIfPresent(lltok::comma)) {
// Metadata at the end is an early exit.
if (Lex.getKind() == lltok::MetadataVar) {
AteExtraComma = true;
return false;
}
if (Lex.getKind() != lltok::kw_align)
return Error(Lex.getLoc(), "expected metadata or 'align'");
if (ParseOptionalAlignment(Alignment)) return true;
}
return false;
}
/// ParseScopeAndOrdering
/// if isAtomic: ::= 'singlethread'? AtomicOrdering
/// else: ::=
///
/// This sets Scope and Ordering to the parsed values.
bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
AtomicOrdering &Ordering) {
if (!isAtomic)
return false;
Scope = CrossThread;
if (EatIfPresent(lltok::kw_singlethread))
Scope = SingleThread;
return ParseOrdering(Ordering);
}
/// ParseOrdering
/// ::= AtomicOrdering
///
/// This sets Ordering to the parsed value.
bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
switch (Lex.getKind()) {
default: return TokError("Expected ordering on atomic instruction");
case lltok::kw_unordered: Ordering = Unordered; break;
case lltok::kw_monotonic: Ordering = Monotonic; break;
case lltok::kw_acquire: Ordering = Acquire; break;
case lltok::kw_release: Ordering = Release; break;
case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
}
Lex.Lex();
return false;
}
/// ParseOptionalStackAlignment
/// ::= /* empty */
/// ::= 'alignstack' '(' 4 ')'
bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
Alignment = 0;
if (!EatIfPresent(lltok::kw_alignstack))
return false;
LocTy ParenLoc = Lex.getLoc();
if (!EatIfPresent(lltok::lparen))
return Error(ParenLoc, "expected '('");
LocTy AlignLoc = Lex.getLoc();
if (ParseUInt32(Alignment)) return true;
ParenLoc = Lex.getLoc();
if (!EatIfPresent(lltok::rparen))
return Error(ParenLoc, "expected ')'");
if (!isPowerOf2_32(Alignment))
return Error(AlignLoc, "stack alignment is not a power of two");
return false;
}
/// ParseIndexList - This parses the index list for an insert/extractvalue
/// instruction. This sets AteExtraComma in the case where we eat an extra
/// comma at the end of the line and find that it is followed by metadata.
/// Clients that don't allow metadata can call the version of this function that
/// only takes one argument.
///
/// ParseIndexList
/// ::= (',' uint32)+
///
bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
bool &AteExtraComma) {
AteExtraComma = false;
if (Lex.getKind() != lltok::comma)
return TokError("expected ',' as start of index list");
while (EatIfPresent(lltok::comma)) {
if (Lex.getKind() == lltok::MetadataVar) {
if (Indices.empty()) return TokError("expected index");
AteExtraComma = true;
return false;
}
unsigned Idx = 0;
if (ParseUInt32(Idx)) return true;
Indices.push_back(Idx);
}
return false;
}
//===----------------------------------------------------------------------===//
// Type Parsing.
//===----------------------------------------------------------------------===//
/// ParseType - Parse a type.
bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
SMLoc TypeLoc = Lex.getLoc();
switch (Lex.getKind()) {
default:
return TokError(Msg);
case lltok::Type:
// Type ::= 'float' | 'void' (etc)
Result = Lex.getTyVal();
Lex.Lex();
break;
case lltok::lbrace:
// Type ::= StructType
if (ParseAnonStructType(Result, false))
return true;
break;
case lltok::lsquare:
// Type ::= '[' ... ']'
Lex.Lex(); // eat the lsquare.
if (ParseArrayVectorType(Result, false))
return true;
break;
case lltok::less: // Either vector or packed struct.
// Type ::= '<' ... '>'
Lex.Lex();
if (Lex.getKind() == lltok::lbrace) {
if (ParseAnonStructType(Result, true) ||
ParseToken(lltok::greater, "expected '>' at end of packed struct"))
return true;
} else if (ParseArrayVectorType(Result, true))
return true;
break;
case lltok::LocalVar: {
// Type ::= %foo
std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
// If the type hasn't been defined yet, create a forward definition and
// remember where that forward def'n was seen (in case it never is defined).
if (!Entry.first) {
Entry.first = StructType::create(Context, Lex.getStrVal());
Entry.second = Lex.getLoc();
}
Result = Entry.first;
Lex.Lex();
break;
}
case lltok::LocalVarID: {
// Type ::= %4
std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
// If the type hasn't been defined yet, create a forward definition and
// remember where that forward def'n was seen (in case it never is defined).
if (!Entry.first) {
Entry.first = StructType::create(Context);
Entry.second = Lex.getLoc();
}
Result = Entry.first;
Lex.Lex();
break;
}
}
// Parse the type suffixes.
while (1) {
switch (Lex.getKind()) {
// End of type.
default:
if (!AllowVoid && Result->isVoidTy())
return Error(TypeLoc, "void type only allowed for function results");
return false;
// Type ::= Type '*'
case lltok::star:
if (Result->isLabelTy())
return TokError("basic block pointers are invalid");
if (Result->isVoidTy())
return TokError("pointers to void are invalid - use i8* instead");
if (!PointerType::isValidElementType(Result))
return TokError("pointer to this type is invalid");
Result = PointerType::getUnqual(Result);
Lex.Lex();
break;
// Type ::= Type 'addrspace' '(' uint32 ')' '*'
case lltok::kw_addrspace: {
if (Result->isLabelTy())
return TokError("basic block pointers are invalid");
if (Result->isVoidTy())
return TokError("pointers to void are invalid; use i8* instead");
if (!PointerType::isValidElementType(Result))
return TokError("pointer to this type is invalid");
unsigned AddrSpace;
if (ParseOptionalAddrSpace(AddrSpace) ||
ParseToken(lltok::star, "expected '*' in address space"))
return true;
Result = PointerType::get(Result, AddrSpace);
break;
}
/// Types '(' ArgTypeListI ')' OptFuncAttrs
case lltok::lparen:
if (ParseFunctionType(Result))
return true;
break;
}
}
}
/// ParseParameterList
/// ::= '(' ')'
/// ::= '(' Arg (',' Arg)* ')'
/// Arg
/// ::= Type OptionalAttributes Value OptionalAttributes
bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
PerFunctionState &PFS, bool IsMustTailCall,
bool InVarArgsFunc) {
if (ParseToken(lltok::lparen, "expected '(' in call"))
return true;
unsigned AttrIndex = 1;
while (Lex.getKind() != lltok::rparen) {
// If this isn't the first argument, we need a comma.
if (!ArgList.empty() &&
ParseToken(lltok::comma, "expected ',' in argument list"))
return true;
// Parse an ellipsis if this is a musttail call in a variadic function.
if (Lex.getKind() == lltok::dotdotdot) {
const char *Msg = "unexpected ellipsis in argument list for ";
if (!IsMustTailCall)
return TokError(Twine(Msg) + "non-musttail call");
if (!InVarArgsFunc)
return TokError(Twine(Msg) + "musttail call in non-varargs function");
Lex.Lex(); // Lex the '...', it is purely for readability.
return ParseToken(lltok::rparen, "expected ')' at end of argument list");
}
// Parse the argument.
LocTy ArgLoc;
Type *ArgTy = nullptr;
AttrBuilder ArgAttrs;
Value *V;
if (ParseType(ArgTy, ArgLoc))
return true;
if (ArgTy->isMetadataTy()) {
if (ParseMetadataAsValue(V, PFS))
return true;
} else {
// Otherwise, handle normal operands.
if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
return true;
}
ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
AttrIndex++,
ArgAttrs)));
}
if (IsMustTailCall && InVarArgsFunc)
return TokError("expected '...' at end of argument list for musttail call "
"in varargs function");
Lex.Lex(); // Lex the ')'.
return false;
}
/// ParseArgumentList - Parse the argument list for a function type or function
/// prototype.
/// ::= '(' ArgTypeListI ')'
/// ArgTypeListI
/// ::= /*empty*/
/// ::= '...'
/// ::= ArgTypeList ',' '...'
/// ::= ArgType (',' ArgType)*
///
bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
bool &isVarArg){
isVarArg = false;
assert(Lex.getKind() == lltok::lparen);
Lex.Lex(); // eat the (.
if (Lex.getKind() == lltok::rparen) {
// empty
} else if (Lex.getKind() == lltok::dotdotdot) {
isVarArg = true;
Lex.Lex();
} else {
LocTy TypeLoc = Lex.getLoc();
Type *ArgTy = nullptr;
AttrBuilder Attrs;
std::string Name;
if (ParseType(ArgTy) ||
ParseOptionalParamAttrs(Attrs)) return true;
if (ArgTy->isVoidTy())
return Error(TypeLoc, "argument can not have void type");
if (Lex.getKind() == lltok::LocalVar) {
Name = Lex.getStrVal();
Lex.Lex();
}
if (!FunctionType::isValidArgumentType(ArgTy))
return Error(TypeLoc, "invalid type for function argument");
unsigned AttrIndex = 1;
ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
AttrIndex++, Attrs),
std::move(Name));
while (EatIfPresent(lltok::comma)) {
// Handle ... at end of arg list.
if (EatIfPresent(lltok::dotdotdot)) {
isVarArg = true;
break;
}
// Otherwise must be an argument type.
TypeLoc = Lex.getLoc();
if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
if (ArgTy->isVoidTy())
return Error(TypeLoc, "argument can not have void type");
if (Lex.getKind() == lltok::LocalVar) {
Name = Lex.getStrVal();
Lex.Lex();
} else {
Name = "";
}
if (!ArgTy->isFirstClassType())
return Error(TypeLoc, "invalid type for function argument");
ArgList.emplace_back(
TypeLoc, ArgTy,
AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
std::move(Name));
}
}
return ParseToken(lltok::rparen, "expected ')' at end of argument list");
}
/// ParseFunctionType
/// ::= Type ArgumentList OptionalAttrs
bool LLParser::ParseFunctionType(Type *&Result) {
assert(Lex.getKind() == lltok::lparen);
if (!FunctionType::isValidReturnType(Result))
return TokError("invalid function return type");
SmallVector<ArgInfo, 8> ArgList;
bool isVarArg;
if (ParseArgumentList(ArgList, isVarArg))
return true;
// Reject names on the arguments lists.
for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
if (!ArgList[i].Name.empty())
return Error(ArgList[i].Loc, "argument name invalid in function type");
if (ArgList[i].Attrs.hasAttributes(i + 1))
return Error(ArgList[i].Loc,
"argument attributes invalid in function type");
}
SmallVector<Type*, 16> ArgListTy;
for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
ArgListTy.push_back(ArgList[i].Ty);
Result = FunctionType::get(Result, ArgListTy, isVarArg);
return false;
}
/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
/// other structs.
bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
SmallVector<Type*, 8> Elts;
if (ParseStructBody(Elts)) return true;
Result = StructType::get(Context, Elts, Packed);
return false;
}
/// ParseStructDefinition - Parse a struct in a 'type' definition.
bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
std::pair<Type*, LocTy> &Entry,
Type *&ResultTy) {
// If the type was already defined, diagnose the redefinition.
if (Entry.first && !Entry.second.isValid())
return Error(TypeLoc, "redefinition of type");
// If we have opaque, just return without filling in the definition for the
// struct. This counts as a definition as far as the .ll file goes.
if (EatIfPresent(lltok::kw_opaque)) {
// This type is being defined, so clear the location to indicate this.
Entry.second = SMLoc();
// If this type number has never been uttered, create it.
if (!Entry.first)
Entry.first = StructType::create(Context, Name);
ResultTy = Entry.first;
return false;
}
// If the type starts with '<', then it is either a packed struct or a vector.
bool isPacked = EatIfPresent(lltok::less);
// If we don't have a struct, then we have a random type alias, which we
// accept for compatibility with old files. These types are not allowed to be
// forward referenced and not allowed to be recursive.
if (Lex.getKind() != lltok::lbrace) {
if (Entry.first)
return Error(TypeLoc, "forward references to non-struct type");
ResultTy = nullptr;
if (isPacked)
return ParseArrayVectorType(ResultTy, true);
return ParseType(ResultTy);
}
// This type is being defined, so clear the location to indicate this.
Entry.second = SMLoc();
// If this type number has never been uttered, create it.
if (!Entry.first)
Entry.first = StructType::create(Context, Name);
StructType *STy = cast<StructType>(Entry.first);
SmallVector<Type*, 8> Body;
if (ParseStructBody(Body) ||
(isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
return true;
STy->setBody(Body, isPacked);
ResultTy = STy;
return false;
}
/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
/// StructType
/// ::= '{' '}'
/// ::= '{' Type (',' Type)* '}'
/// ::= '<' '{' '}' '>'
/// ::= '<' '{' Type (',' Type)* '}' '>'
bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
assert(Lex.getKind() == lltok::lbrace);
Lex.Lex(); // Consume the '{'
// Handle the empty struct.
if (EatIfPresent(lltok::rbrace))
return false;
LocTy EltTyLoc = Lex.getLoc();
Type *Ty = nullptr;
if (ParseType(Ty)) return true;
Body.push_back(Ty);
if (!StructType::isValidElementType(Ty))
return Error(EltTyLoc, "invalid element type for struct");
while (EatIfPresent(lltok::comma)) {
EltTyLoc = Lex.getLoc();
if (ParseType(Ty)) return true;
if (!StructType::isValidElementType(Ty))
return Error(EltTyLoc, "invalid element type for struct");
Body.push_back(Ty);
}
return ParseToken(lltok::rbrace, "expected '}' at end of struct");
}
/// ParseArrayVectorType - Parse an array or vector type, assuming the first
/// token has already been consumed.
/// Type
/// ::= '[' APSINTVAL 'x' Types ']'
/// ::= '<' APSINTVAL 'x' Types '>'
bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
Lex.getAPSIntVal().getBitWidth() > 64)
return TokError("expected number in address space");
LocTy SizeLoc = Lex.getLoc();
uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Lex.Lex();
if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
return true;
LocTy TypeLoc = Lex.getLoc();
Type *EltTy = nullptr;
if (ParseType(EltTy)) return true;
if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
"expected end of sequential type"))
return true;
if (isVector) {
if (Size == 0)
return Error(SizeLoc, "zero element vector is illegal");
if ((unsigned)Size != Size)
return Error(SizeLoc, "size too large for vector");
if (!VectorType::isValidElementType(EltTy))
return Error(TypeLoc, "invalid vector element type");
Result = VectorType::get(EltTy, unsigned(Size));
} else {
if (!ArrayType::isValidElementType(EltTy))
return Error(TypeLoc, "invalid array element type");
Result = ArrayType::get(EltTy, Size);
}
return false;
}
//===----------------------------------------------------------------------===//
// Function Semantic Analysis.
//===----------------------------------------------------------------------===//
LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
int functionNumber)
: P(p), F(f), FunctionNumber(functionNumber) {
// Insert unnamed arguments into the NumberedVals list.
for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
AI != E; ++AI)
if (!AI->hasName())
NumberedVals.push_back(AI);
}
LLParser::PerFunctionState::~PerFunctionState() {
// If there were any forward referenced non-basicblock values, delete them.
for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
if (!isa<BasicBlock>(I->second.first)) {
I->second.first->replaceAllUsesWith(
UndefValue::get(I->second.first->getType()));
delete I->second.first;
I->second.first = nullptr;
}
for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
if (!isa<BasicBlock>(I->second.first)) {
I->second.first->replaceAllUsesWith(
UndefValue::get(I->second.first->getType()));
delete I->second.first;
I->second.first = nullptr;
}
}
bool LLParser::PerFunctionState::FinishFunction() {
if (!ForwardRefVals.empty())
return P.Error(ForwardRefVals.begin()->second.second,
"use of undefined value '%" + ForwardRefVals.begin()->first +
"'");
if (!ForwardRefValIDs.empty())
return P.Error(ForwardRefValIDs.begin()->second.second,
"use of undefined value '%" +
Twine(ForwardRefValIDs.begin()->first) + "'");
return false;
}
/// GetVal - Get a value with the specified name or ID, creating a
/// forward reference record if needed. This can return null if the value
/// exists but does not have the right type.
Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Type *Ty, LocTy Loc) {
// Look this name up in the normal function symbol table.
Value *Val = F.getValueSymbolTable().lookup(Name);
// If this is a forward reference for the value, see if we already created a
// forward ref record.
if (!Val) {
std::map<std::string, std::pair<Value*, LocTy> >::iterator
I = ForwardRefVals.find(Name);
if (I != ForwardRefVals.end())
Val = I->second.first;
}
// If we have the value in the symbol table or fwd-ref table, return it.
if (Val) {
if (Val->getType() == Ty) return Val;
if (Ty->isLabelTy())
P.Error(Loc, "'%" + Name + "' is not a basic block");
else
P.Error(Loc, "'%" + Name + "' defined with type '" +
getTypeString(Val->getType()) + "'");
return nullptr;
}
// Don't make placeholders with invalid type.
if (!Ty->isFirstClassType()) {
P.Error(Loc, "invalid use of a non-first-class type");
return nullptr;
}
// Otherwise, create a new forward reference for this value and remember it.
Value *FwdVal;
if (Ty->isLabelTy())
FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
else
FwdVal = new Argument(Ty, Name);
ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
return FwdVal;
}
Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
LocTy Loc) {
// Look this name up in the normal function symbol table.
Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
// If this is a forward reference for the value, see if we already created a
// forward ref record.
if (!Val) {
std::map<unsigned, std::pair<Value*, LocTy> >::iterator
I = ForwardRefValIDs.find(ID);
if (I != ForwardRefValIDs.end())
Val = I->second.first;
}
// If we have the value in the symbol table or fwd-ref table, return it.
if (Val) {
if (Val->getType() == Ty) return Val;
if (Ty->isLabelTy())
P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
else
P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
getTypeString(Val->getType()) + "'");
return nullptr;
}
if (!Ty->isFirstClassType()) {
P.Error(Loc, "invalid use of a non-first-class type");
return nullptr;
}
// Otherwise, create a new forward reference for this value and remember it.
Value *FwdVal;
if (Ty->isLabelTy())
FwdVal = BasicBlock::Create(F.getContext(), "", &F);
else
FwdVal = new Argument(Ty);
ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
return FwdVal;
}
/// SetInstName - After an instruction is parsed and inserted into its
/// basic block, this installs its name.
bool LLParser::PerFunctionState::SetInstName(int NameID,
const std::string &NameStr,
LocTy NameLoc, Instruction *Inst) {
// If this instruction has void type, it cannot have a name or ID specified.
if (Inst->getType()->isVoidTy()) {
if (NameID != -1 || !NameStr.empty())
return P.Error(NameLoc, "instructions returning void cannot have a name");
return false;
}
// If this was a numbered instruction, verify that the instruction is the
// expected value and resolve any forward references.
if (NameStr.empty()) {
// If neither a name nor an ID was specified, just use the next ID.
if (NameID == -1)
NameID = NumberedVals.size();
if (unsigned(NameID) != NumberedVals.size())
return P.Error(NameLoc, "instruction expected to be numbered '%" +
Twine(NumberedVals.size()) + "'");
std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
ForwardRefValIDs.find(NameID);
if (FI != ForwardRefValIDs.end()) {
if (FI->second.first->getType() != Inst->getType())
return P.Error(NameLoc, "instruction forward referenced with type '" +
getTypeString(FI->second.first->getType()) + "'");
FI->second.first->replaceAllUsesWith(Inst);
delete FI->second.first;
ForwardRefValIDs.erase(FI);
}
NumberedVals.push_back(Inst);
return false;
}
// Otherwise, the instruction had a name. Resolve forward refs and set it.
std::map<std::string, std::pair<Value*, LocTy> >::iterator
FI = ForwardRefVals.find(NameStr);
if (FI != ForwardRefVals.end()) {
if (FI->second.first->getType() != Inst->getType())
return P.Error(NameLoc, "instruction forward referenced with type '" +
getTypeString(FI->second.first->getType()) + "'");
FI->second.first->replaceAllUsesWith(Inst);
delete FI->second.first;
ForwardRefVals.erase(FI);
}
// Set the name on the instruction.
Inst->setName(NameStr);
if (Inst->getName() != NameStr)
return P.Error(NameLoc, "multiple definition of local value named '" +
NameStr + "'");
return false;
}
/// GetBB - Get a basic block with the specified name or ID, creating a
/// forward reference record if needed.
BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
LocTy Loc) {
return dyn_cast_or_null<BasicBlock>(GetVal(Name,
Type::getLabelTy(F.getContext()), Loc));
}
BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
return dyn_cast_or_null<BasicBlock>(GetVal(ID,
Type::getLabelTy(F.getContext()), Loc));
}
/// DefineBB - Define the specified basic block, which is either named or
/// unnamed. If there is an error, this returns null otherwise it returns
/// the block being defined.
BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
LocTy Loc) {
BasicBlock *BB;
if (Name.empty())
BB = GetBB(NumberedVals.size(), Loc);
else
BB = GetBB(Name, Loc);
if (!BB) return nullptr; // Already diagnosed error.
// Move the block to the end of the function. Forward ref'd blocks are
// inserted wherever they happen to be referenced.
F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
// Remove the block from forward ref sets.
if (Name.empty()) {
ForwardRefValIDs.erase(NumberedVals.size());
NumberedVals.push_back(BB);
} else {
// BB forward references are already in the function symbol table.
ForwardRefVals.erase(Name);
}
return BB;
}
//===----------------------------------------------------------------------===//
// Constants.
//===----------------------------------------------------------------------===//
/// ParseValID - Parse an abstract value that doesn't necessarily have a
/// type implied. For example, if we parse "4" we don't know what integer type
/// it has. The value will later be combined with its type and checked for
/// sanity. PFS is used to convert function-local operands of metadata (since
/// metadata operands are not just parsed here but also converted to values).
/// PFS can be null when we are not parsing metadata values inside a function.
bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
ID.Loc = Lex.getLoc();
switch (Lex.getKind()) {
default: return TokError("expected value token");
case lltok::GlobalID: // @42
ID.UIntVal = Lex.getUIntVal();
ID.Kind = ValID::t_GlobalID;
break;
case lltok::GlobalVar: // @foo
ID.StrVal = Lex.getStrVal();
ID.Kind = ValID::t_GlobalName;
break;
case lltok::LocalVarID: // %42
ID.UIntVal = Lex.getUIntVal();
ID.Kind = ValID::t_LocalID;
break;
case lltok::LocalVar: // %foo
ID.StrVal = Lex.getStrVal();
ID.Kind = ValID::t_LocalName;
break;
case lltok::APSInt:
ID.APSIntVal = Lex.getAPSIntVal();
ID.Kind = ValID::t_APSInt;
break;
case lltok::APFloat:
ID.APFloatVal = Lex.getAPFloatVal();
ID.Kind = ValID::t_APFloat;
break;
case lltok::kw_true:
ID.ConstantVal = ConstantInt::getTrue(Context);
ID.Kind = ValID::t_Constant;
break;
case lltok::kw_false:
ID.ConstantVal = ConstantInt::getFalse(Context);
ID.Kind = ValID::t_Constant;
break;
case lltok::kw_null: ID.Kind = ValID::t_Null; break;
case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
case lltok::lbrace: {
// ValID ::= '{' ConstVector '}'
Lex.Lex();
SmallVector<Constant*, 16> Elts;
if (ParseGlobalValueVector(Elts) ||
ParseToken(lltok::rbrace, "expected end of struct constant"))
return true;
ID.ConstantStructElts = new Constant*[Elts.size()];
ID.UIntVal = Elts.size();
memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
ID.Kind = ValID::t_ConstantStruct;
return false;
}
case lltok::less: {
// ValID ::= '<' ConstVector '>' --> Vector.
// ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
Lex.Lex();
bool isPackedStruct = EatIfPresent(lltok::lbrace);
SmallVector<Constant*, 16> Elts;
LocTy FirstEltLoc = Lex.getLoc();
if (ParseGlobalValueVector(Elts) ||
(isPackedStruct &&
ParseToken(lltok::rbrace, "expected end of packed struct")) ||
ParseToken(lltok::greater, "expected end of constant"))
return true;
if (isPackedStruct) {
ID.ConstantStructElts = new Constant*[Elts.size()];
memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
ID.UIntVal = Elts.size();
ID.Kind = ValID::t_PackedConstantStruct;
return false;
}
if (Elts.empty())
return Error(ID.Loc, "constant vector must not be empty");
if (!Elts[0]->getType()->isIntegerTy() &&
!Elts[0]->getType()->isFloatingPointTy() &&
!Elts[0]->getType()->isPointerTy())
return Error(FirstEltLoc,
"vector elements must have integer, pointer or floating point type");
// Verify that all the vector elements have the same type.
for (unsigned i = 1, e = Elts.size(); i != e; ++i)
if (Elts[i]->getType() != Elts[0]->getType())
return Error(FirstEltLoc,
"vector element #" + Twine(i) +
" is not of type '" + getTypeString(Elts[0]->getType()));
ID.ConstantVal = ConstantVector::get(Elts);
ID.Kind = ValID::t_Constant;
return false;
}
case lltok::lsquare: { // Array Constant
Lex.Lex();
SmallVector<Constant*, 16> Elts;
LocTy FirstEltLoc = Lex.getLoc();
if (ParseGlobalValueVector(Elts) ||
ParseToken(lltok::rsquare, "expected end of array constant"))
return true;
// Handle empty element.
if (Elts.empty()) {
// Use undef instead of an array because it's inconvenient to determine
// the element type at this point, there being no elements to examine.
ID.Kind = ValID::t_EmptyArray;
return false;
}
if (!Elts[0]->getType()->isFirstClassType())
return Error(FirstEltLoc, "invalid array element type: " +
getTypeString(Elts[0]->getType()));
ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
// Verify all elements are correct type!
for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
if (Elts[i]->getType() != Elts[0]->getType())
return Error(FirstEltLoc,
"array element #" + Twine(i) +
" is not of type '" + getTypeString(Elts[0]->getType()));
}
ID.ConstantVal = ConstantArray::get(ATy, Elts);
ID.Kind = ValID::t_Constant;
return false;
}
case lltok::kw_c: // c "foo"
Lex.Lex();
ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
false);
if (ParseToken(lltok::StringConstant, "expected string")) return true;
ID.Kind = ValID::t_Constant;
return false;
case lltok::kw_asm: {
// ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
// STRINGCONSTANT
bool HasSideEffect, AlignStack, AsmDialect;
Lex.Lex();
if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
ParseStringConstant(ID.StrVal) ||
ParseToken(lltok::comma, "expected comma in inline asm expression") ||
ParseToken(lltok::StringConstant, "expected constraint string"))
return true;
ID.StrVal2 = Lex.getStrVal();
ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
(unsigned(AsmDialect)<<2);
ID.Kind = ValID::t_InlineAsm;
return false;
}
case lltok::kw_blockaddress: {
// ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
Lex.Lex();
ValID Fn, Label;
if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
ParseValID(Fn) ||
ParseToken(lltok::comma, "expected comma in block address expression")||
ParseValID(Label) ||
ParseToken(lltok::rparen, "expected ')' in block address expression"))
return true;
if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
return Error(Fn.Loc, "expected function name in blockaddress");
if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
return Error(Label.Loc, "expected basic block name in blockaddress");
// Try to find the function (but skip it if it's forward-referenced).
GlobalValue *GV = nullptr;
if (Fn.Kind == ValID::t_GlobalID) {
if (Fn.UIntVal < NumberedVals.size())
GV = NumberedVals[Fn.UIntVal];
} else if (!ForwardRefVals.count(Fn.StrVal)) {
GV = M->getNamedValue(Fn.StrVal);
}
Function *F = nullptr;
if (GV) {
// Confirm that it's actually a function with a definition.
if (!isa<Function>(GV))
return Error(Fn.Loc, "expected function name in blockaddress");
F = cast<Function>(GV);
if (F->isDeclaration())
return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
}
if (!F) {
// Make a global variable as a placeholder for this reference.
GlobalValue *&FwdRef =
ForwardRefBlockAddresses.insert(std::make_pair(
std::move(Fn),
std::map<ValID, GlobalValue *>()))
.first->second.insert(std::make_pair(std::move(Label), nullptr))
.first->second;
if (!FwdRef)
FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
GlobalValue::InternalLinkage, nullptr, "");
ID.ConstantVal = FwdRef;
ID.Kind = ValID::t_Constant;
return false;
}
// We found the function; now find the basic block. Don't use PFS, since we
// might be inside a constant expression.
BasicBlock *BB;
if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
if (Label.Kind == ValID::t_LocalID)
BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
else
BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
if (!BB)
return Error(Label.Loc, "referenced value is not a basic block");
} else {
if (Label.Kind == ValID::t_LocalID)
return Error(Label.Loc, "cannot take address of numeric label after "
"the function is defined");
BB = dyn_cast_or_null<BasicBlock>(
F->getValueSymbolTable().lookup(Label.StrVal));
if (!BB)
return Error(Label.Loc, "referenced value is not a basic block");
}
ID.ConstantVal = BlockAddress::get(F, BB);
ID.Kind = ValID::t_Constant;
return false;
}
case lltok::kw_trunc:
case lltok::kw_zext:
case lltok::kw_sext:
case lltok::kw_fptrunc:
case lltok::kw_fpext:
case lltok::kw_bitcast:
case lltok::kw_addrspacecast:
case lltok::kw_uitofp:
case lltok::kw_sitofp:
case lltok::kw_fptoui:
case lltok::kw_fptosi:
case lltok::kw_inttoptr:
case lltok::kw_ptrtoint: {
unsigned Opc = Lex.getUIntVal();
Type *DestTy = nullptr;
Constant *SrcVal;
Lex.Lex();
if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
ParseGlobalTypeAndValue(SrcVal) ||
ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
ParseType(DestTy) ||
ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
return true;
if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
return Error(ID.Loc, "invalid cast opcode for cast from '" +
getTypeString(SrcVal->getType()) + "' to '" +
getTypeString(DestTy) + "'");
ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
SrcVal, DestTy);
ID.Kind = ValID::t_Constant;
return false;
}
case lltok::kw_extractvalue: {
Lex.Lex();
Constant *Val;
SmallVector<unsigned, 4> Indices;
if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
ParseGlobalTypeAndValue(Val) ||
ParseIndexList(Indices) ||
ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
return true;
if (!Val->getType()->isAggregateType())
return Error(ID.Loc, "extractvalue operand must be aggregate type");
if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
return Error(ID.Loc, "invalid indices for extractvalue");
ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
ID.Kind = ValID::t_Constant;
return false;
}
case lltok::kw_insertvalue: {
Lex.Lex();
Constant *Val0, *Val1;
SmallVector<unsigned, 4> Indices;
if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
ParseGlobalTypeAndValue(Val0) ||
ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
ParseGlobalTypeAndValue(Val1) ||
ParseIndexList(Indices) ||
ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
return true;
if (!Val0->getType()->isAggregateType())
return Error(ID.Loc, "insertvalue operand must be aggregate type");
Type *IndexedType =
ExtractValueInst::getIndexedType(Val0->getType(), Indices);
if (!IndexedType)
return Error(ID.Loc, "invalid indices for insertvalue");
if (IndexedType != Val1->getType())
return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
getTypeString(Val1->getType()) +
"' instead of '" + getTypeString(IndexedType) +
"'");
ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
ID.Kind = ValID::t_Constant;
return false;
}
case lltok::kw_icmp:
case lltok::kw_fcmp: {
unsigned PredVal, Opc = Lex.getUIntVal();
Constant *Val0, *Val1;
Lex.Lex();
if (ParseCmpPredicate(PredVal, Opc) ||
ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
ParseGlobalTypeAndValue(Val0) ||
ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
ParseGlobalTypeAndValue(Val1) ||
ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
return true;
if (Val0->getType() != Val1->getType())
return Error(ID.Loc, "compare operands must have the same type");
CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
if (Opc == Instruction::FCmp) {
if (!Val0->getType()->isFPOrFPVectorTy())
return Error(ID.Loc, "fcmp requires floating point operands");
ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
} else {
assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
if (!Val0->getType()->isIntOrIntVectorTy() &&
!Val0->getType()->getScalarType()->isPointerTy())
return Error(ID.Loc, "icmp requires pointer or integer operands");
ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
}
ID.Kind = ValID::t_Constant;
return false;
}
// Binary Operators.
case lltok::kw_add:
case lltok::kw_fadd:
case lltok::kw_sub:
case lltok::kw_fsub:
case lltok::kw_mul:
case lltok::kw_fmul:
case lltok::kw_udiv:
case lltok::kw_sdiv:
case lltok::kw_fdiv:
case lltok::kw_urem:
case lltok::kw_srem:
case lltok::kw_frem:
case lltok::kw_shl:
case lltok::kw_lshr:
case lltok::kw_ashr: {
bool NUW = false;
bool NSW = false;
bool Exact = false;
unsigned Opc = Lex.getUIntVal();
Constant *Val0, *Val1;
Lex.Lex();
LocTy ModifierLoc = Lex.getLoc();
if (Opc == Instruction::Add || Opc == Instruction::Sub ||
Opc == Instruction::Mul || Opc == Instruction::Shl) {
if (EatIfPresent(lltok::kw_nuw))
NUW = true;
if (EatIfPresent(lltok::kw_nsw)) {
NSW = true;
if (EatIfPresent(lltok::kw_nuw))
NUW = true;
}
} else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
Opc == Instruction::LShr || Opc == Instruction::AShr) {
if (EatIfPresent(lltok::kw_exact))
Exact = true;
}
if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
ParseGlobalTypeAndValue(Val0) ||
ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
ParseGlobalTypeAndValue(Val1) ||
ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
return true;
if (Val0->getType() != Val1->getType())
return Error(ID.Loc, "operands of constexpr must have same type");
if (!Val0->getType()->isIntOrIntVectorTy()) {
if (NUW)
return Error(ModifierLoc, "nuw only applies to integer operations");
if (NSW)
return Error(ModifierLoc, "nsw only applies to integer operations");
}
// Check that the type is valid for the operator.
switch (Opc) {
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
case Instruction::UDiv:
case Instruction::SDiv:
case Instruction::URem:
case Instruction::SRem:
case Instruction::Shl:
case Instruction::AShr:
case Instruction::LShr:
if (!Val0->getType()->isIntOrIntVectorTy())
return Error(ID.Loc, "constexpr requires integer operands");
break;
case Instruction::FAdd:
case Instruction::FSub:
case Instruction::FMul:
case Instruction::FDiv:
case Instruction::FRem:
if (!Val0->getType()->isFPOrFPVectorTy())
return Error(ID.Loc, "constexpr requires fp operands");
break;
default: llvm_unreachable("Unknown binary operator!");
}
unsigned Flags = 0;
if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
if (Exact) Flags |= PossiblyExactOperator::IsExact;
Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
ID.ConstantVal = C;
ID.Kind = ValID::t_Constant;
return false;
}
// Logical Operations
case lltok::kw_and:
case lltok::kw_or:
case lltok::kw_xor: {
unsigned Opc = Lex.getUIntVal();
Constant *Val0, *Val1;
Lex.Lex();
if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
ParseGlobalTypeAndValue(Val0) ||
ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
ParseGlobalTypeAndValue(Val1) ||
ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
return true;
if (Val0->getType() != Val1->getType())
return Error(ID.Loc, "operands of constexpr must have same type");
if (!Val0->getType()->isIntOrIntVectorTy())
return Error(ID.Loc,
"constexpr requires integer or integer vector operands");
ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
ID.Kind = ValID::t_Constant;
return false;
}
case lltok::kw_getelementptr:
case lltok::kw_shufflevector:
case lltok::kw_insertelement:
case lltok::kw_extractelement:
case lltok::kw_select: {
unsigned Opc = Lex.getUIntVal();
SmallVector<Constant*, 16> Elts;
bool InBounds = false;
Type *Ty;
Lex.Lex();
if (Opc == Instruction::GetElementPtr)
InBounds = EatIfPresent(lltok::kw_inbounds);
if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
return true;
LocTy ExplicitTypeLoc = Lex.getLoc();
if (Opc == Instruction::GetElementPtr) {
if (ParseType(Ty) ||
ParseToken(lltok::comma, "expected comma after getelementptr's type"))
return true;
}
if (ParseGlobalValueVector(Elts) ||
ParseToken(lltok::rparen, "expected ')' in constantexpr"))
return true;
if (Opc == Instruction::GetElementPtr) {
if (Elts.size() == 0 ||
!Elts[0]->getType()->getScalarType()->isPointerTy())
return Error(ID.Loc, "base of getelementptr must be a pointer");
Type *BaseType = Elts[0]->getType();
auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
if (Ty != BasePointerType->getElementType())
return Error(
ExplicitTypeLoc,
"explicit pointee type doesn't match operand's pointee type");
ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
for (Constant *Val : Indices) {
Type *ValTy = Val->getType();
if (!ValTy->getScalarType()->isIntegerTy())
return Error(ID.Loc, "getelementptr index must be an integer");
if (ValTy->isVectorTy() != BaseType->isVectorTy())
return Error(ID.Loc, "getelementptr index type missmatch");
if (ValTy->isVectorTy()) {
unsigned ValNumEl = ValTy->getVectorNumElements();
unsigned PtrNumEl = BaseType->getVectorNumElements();
if (ValNumEl != PtrNumEl)
return Error(
ID.Loc,
"getelementptr vector index has a wrong number of elements");
}
}
SmallPtrSet<const Type*, 4> Visited;
if (!Indices.empty() && !Ty->isSized(&Visited))
return Error(ID.Loc, "base element of getelementptr must be sized");
if (!GetElementPtrInst::getIndexedType(Ty, Indices))
return Error(ID.Loc, "invalid getelementptr indices");
ID.ConstantVal =
ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
} else if (Opc == Instruction::Select) {
if (Elts.size() != 3)
return Error(ID.Loc, "expected three operands to select");
if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
Elts[2]))
return Error(ID.Loc, Reason);
ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
} else if (Opc == Instruction::ShuffleVector) {
if (Elts.size() != 3)
return Error(ID.Loc, "expected three operands to shufflevector");
if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
return Error(ID.Loc, "invalid operands to shufflevector");
ID.ConstantVal =
ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
} else if (Opc == Instruction::ExtractElement) {
if (Elts.size() != 2)
return Error(ID.Loc, "expected two operands to extractelement");
if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
return Error(ID.Loc, "invalid extractelement operands");
ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
} else {
assert(Opc == Instruction::InsertElement && "Unknown opcode");
if (Elts.size() != 3)
return Error(ID.Loc, "expected three operands to insertelement");
if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
return Error(ID.Loc, "invalid insertelement operands");
ID.ConstantVal =
ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
}
ID.Kind = ValID::t_Constant;
return false;
}
}
Lex.Lex();
return false;
}
/// ParseGlobalValue - Parse a global value with the specified type.
bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
C = nullptr;
ValID ID;
Value *V = nullptr;
bool Parsed = ParseValID(ID) ||
ConvertValIDToValue(Ty, ID, V, nullptr);
if (V && !(C = dyn_cast<Constant>(V)))
return Error(ID.Loc, "global values must be constants");
return Parsed;
}
bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Type *Ty = nullptr;
return ParseType(Ty) ||
ParseGlobalValue(Ty, V);
}
bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
C = nullptr;
LocTy KwLoc = Lex.getLoc();
if (!EatIfPresent(lltok::kw_comdat))
return false;
if (EatIfPresent(lltok::lparen)) {
if (Lex.getKind() != lltok::ComdatVar)
return TokError("expected comdat variable");
C = getComdat(Lex.getStrVal(), Lex.getLoc());
Lex.Lex();
if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
return true;
} else {
if (GlobalName.empty())
return TokError("comdat cannot be unnamed");
C = getComdat(GlobalName, KwLoc);
}
return false;
}
/// ParseGlobalValueVector
/// ::= /*empty*/
/// ::= TypeAndValue (',' TypeAndValue)*
bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
// Empty list.
if (Lex.getKind() == lltok::rbrace ||
Lex.getKind() == lltok::rsquare ||
Lex.getKind() == lltok::greater ||
Lex.getKind() == lltok::rparen)
return false;
Constant *C;
if (ParseGlobalTypeAndValue(C)) return true;
Elts.push_back(C);
while (EatIfPresent(lltok::comma)) {
if (ParseGlobalTypeAndValue(C)) return true;
Elts.push_back(C);
}
return false;
}
bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
SmallVector<Metadata *, 16> Elts;
if (ParseMDNodeVector(Elts))
return true;
MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
return false;
}
/// MDNode:
/// ::= !{ ... }
/// ::= !7
/// ::= !DILocation(...)
bool LLParser::ParseMDNode(MDNode *&N) {
if (Lex.getKind() == lltok::MetadataVar)
return ParseSpecializedMDNode(N);
return ParseToken(lltok::exclaim, "expected '!' here") ||
ParseMDNodeTail(N);
}
bool LLParser::ParseMDNodeTail(MDNode *&N) {
// !{ ... }
if (Lex.getKind() == lltok::lbrace)
return ParseMDTuple(N);
// !42
return ParseMDNodeID(N);
}
namespace {
/// Structure to represent an optional metadata field.
template <class FieldTy> struct MDFieldImpl {
typedef MDFieldImpl ImplTy;
FieldTy Val;
bool Seen;
void assign(FieldTy Val) {
Seen = true;
this->Val = std::move(Val);
}
explicit MDFieldImpl(FieldTy Default)
: Val(std::move(Default)), Seen(false) {}
};
struct MDUnsignedField : public MDFieldImpl<uint64_t> {
uint64_t Max;
MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
: ImplTy(Default), Max(Max) {}
};
struct LineField : public MDUnsignedField {
LineField() : MDUnsignedField(0, UINT32_MAX) {}
};
struct ColumnField : public MDUnsignedField {
ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
};
struct DwarfTagField : public MDUnsignedField {
DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
DwarfTagField(dwarf::Tag DefaultTag)
: MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
};
struct DwarfAttEncodingField : public MDUnsignedField {
DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
};
struct DwarfVirtualityField : public MDUnsignedField {
DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
};
struct DwarfLangField : public MDUnsignedField {
DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
};
struct DIFlagField : public MDUnsignedField {
DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
};
struct MDSignedField : public MDFieldImpl<int64_t> {
int64_t Min;
int64_t Max;
MDSignedField(int64_t Default = 0)
: ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
MDSignedField(int64_t Default, int64_t Min, int64_t Max)
: ImplTy(Default), Min(Min), Max(Max) {}
};
struct MDBoolField : public MDFieldImpl<bool> {
MDBoolField(bool Default = false) : ImplTy(Default) {}
};
struct MDField : public MDFieldImpl<Metadata *> {
bool AllowNull;
MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
};
struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
MDConstant() : ImplTy(nullptr) {}
};
struct MDStringField : public MDFieldImpl<MDString *> {
bool AllowEmpty;
MDStringField(bool AllowEmpty = true)
: ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
};
struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
};
} // end namespace
namespace llvm {
template <>
bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
MDUnsignedField &Result) {
if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
return TokError("expected unsigned integer");
auto &U = Lex.getAPSIntVal();
if (U.ugt(Result.Max))
return TokError("value for '" + Name + "' too large, limit is " +
Twine(Result.Max));
Result.assign(U.getZExtValue());
assert(Result.Val <= Result.Max && "Expected value in range");
Lex.Lex();
return false;
}
template <>
bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
}
template <>
bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
}
template <>
bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
if (Lex.getKind() == lltok::APSInt)
return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
if (Lex.getKind() != lltok::DwarfTag)
return TokError("expected DWARF tag");
unsigned Tag = dwarf::getTag(Lex.getStrVal());
if (Tag == dwarf::DW_TAG_invalid)
return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
assert(Tag <= Result.Max && "Expected valid DWARF tag");
Result.assign(Tag);
Lex.Lex();
return false;
}
template <>
bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
DwarfVirtualityField &Result) {
if (Lex.getKind() == lltok::APSInt)
return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
if (Lex.getKind() != lltok::DwarfVirtuality)
return TokError("expected DWARF virtuality code");
unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
if (!Virtuality)
return TokError("invalid DWARF virtuality code" + Twine(" '") +
Lex.getStrVal() + "'");
assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
Result.assign(Virtuality);
Lex.Lex();
return false;
}
template <>
bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
if (Lex.getKind() == lltok::APSInt)
return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
if (Lex.getKind() != lltok::DwarfLang)
return TokError("expected DWARF language");
unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
if (!Lang)
return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
"'");
assert(Lang <= Result.Max && "Expected valid DWARF language");
Result.assign(Lang);
Lex.Lex();
return false;
}
template <>
bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
DwarfAttEncodingField &Result) {
if (Lex.getKind() == lltok::APSInt)
return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
if (Lex.getKind() != lltok::DwarfAttEncoding)
return TokError("expected DWARF type attribute encoding");
unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
if (!Encoding)
return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
Lex.getStrVal() + "'");
assert(Encoding <= Result.Max && "Expected valid DWARF language");
Result.assign(Encoding);
Lex.Lex();
return false;
}
/// DIFlagField
/// ::= uint32
/// ::= DIFlagVector
/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
template <>
bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
// Parser for a single flag.
auto parseFlag = [&](unsigned &Val) {
if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
return ParseUInt32(Val);
if (Lex.getKind() != lltok::DIFlag)
return TokError("expected debug info flag");
Val = DINode::getFlag(Lex.getStrVal());
if (!Val)
return TokError(Twine("invalid debug info flag flag '") +
Lex.getStrVal() + "'");
Lex.Lex();
return false;
};
// Parse the flags and combine them together.
unsigned Combined = 0;
do {
unsigned Val;
if (parseFlag(Val))
return true;
Combined |= Val;
} while (EatIfPresent(lltok::bar));
Result.assign(Combined);
return false;
}
template <>
bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
MDSignedField &Result) {
if (Lex.getKind() != lltok::APSInt)
return TokError("expected signed integer");
auto &S = Lex.getAPSIntVal();
if (S < Result.Min)
return TokError("value for '" + Name + "' too small, limit is " +
Twine(Result.Min));
if (S > Result.Max)
return TokError("value for '" + Name + "' too large, limit is " +
Twine(Result.Max));
Result.assign(S.getExtValue());
assert(Result.Val >= Result.Min && "Expected value in range");
assert(Result.Val <= Result.Max && "Expected value in range");
Lex.Lex();
return false;
}
template <>
bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
switch (Lex.getKind()) {
default:
return TokError("expected 'true' or 'false'");
case lltok::kw_true:
Result.assign(true);
break;
case lltok::kw_false:
Result.assign(false);
break;
}
Lex.Lex();
return false;
}
template <>
bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
if (Lex.getKind() == lltok::kw_null) {
if (!Result.AllowNull)
return TokError("'" + Name + "' cannot be null");
Lex.Lex();
Result.assign(nullptr);
return false;
}
Metadata *MD;
if (ParseMetadata(MD, nullptr))
return true;
Result.assign(MD);
return false;
}
template <>
bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
Metadata *MD;
if (ParseValueAsMetadata(MD, "expected constant", nullptr))
return true;
Result.assign(cast<ConstantAsMetadata>(MD));
return false;
}
template <>
bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
LocTy ValueLoc = Lex.getLoc();
std::string S;
if (ParseStringConstant(S))
return true;
if (!Result.AllowEmpty && S.empty())
return Error(ValueLoc, "'" + Name + "' cannot be empty");
Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
return false;
}
template <>
bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
SmallVector<Metadata *, 4> MDs;
if (ParseMDNodeVector(MDs))
return true;
Result.assign(std::move(MDs));
return false;
}
} // end namespace llvm
template <class ParserTy>
bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
do {
if (Lex.getKind() != lltok::LabelStr)
return TokError("expected field label here");
if (parseField())
return true;
} while (EatIfPresent(lltok::comma));
return false;
}
template <class ParserTy>
bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Lex.Lex();
if (ParseToken(lltok::lparen, "expected '(' here"))
return true;
if (Lex.getKind() != lltok::rparen)
if (ParseMDFieldsImplBody(parseField))
return true;
ClosingLoc = Lex.getLoc();
return ParseToken(lltok::rparen, "expected ')' here");
}
template <class FieldTy>
bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
if (Result.Seen)
return TokError("field '" + Name + "' cannot be specified more than once");
LocTy Loc = Lex.getLoc();
Lex.Lex();
return ParseMDField(Loc, Name, Result);
}
bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
if (Lex.getStrVal() == #CLASS) \
return Parse##CLASS(N, IsDistinct);
#include "llvm/IR/Metadata.def"
return TokError("expected metadata type");
}
#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
#define NOP_FIELD(NAME, TYPE, INIT)
#define REQUIRE_FIELD(NAME, TYPE, INIT) \
if (!NAME.Seen) \
return Error(ClosingLoc, "missing required field '" #NAME "'");
#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
if (Lex.getStrVal() == #NAME) \
return ParseMDField(#NAME, NAME);
#define PARSE_MD_FIELDS() \
VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
do { \
LocTy ClosingLoc; \
if (ParseMDFieldsImpl([&]() -> bool { \
VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
}, ClosingLoc)) \
return true; \
VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
} while (false)
#define GET_OR_DISTINCT(CLASS, ARGS) \
(IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
/// ParseDILocationFields:
/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
OPTIONAL(line, LineField, ); \
OPTIONAL(column, ColumnField, ); \
REQUIRED(scope, MDField, (/* AllowNull */ false)); \
OPTIONAL(inlinedAt, MDField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(
DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
return false;
}
/// ParseGenericDINode:
/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
REQUIRED(tag, DwarfTagField, ); \
OPTIONAL(header, MDStringField, ); \
OPTIONAL(operands, MDFieldList, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(GenericDINode,
(Context, tag.Val, header.Val, operands.Val));
return false;
}
/// ParseDISubrange:
/// ::= !DISubrange(count: 30, lowerBound: 2)
bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
OPTIONAL(lowerBound, MDSignedField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
return false;
}
/// ParseDIEnumerator:
/// ::= !DIEnumerator(value: 30, name: "SomeKind")
bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
REQUIRED(name, MDStringField, ); \
REQUIRED(value, MDSignedField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
return false;
}
/// ParseDIBasicType:
/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
OPTIONAL(name, MDStringField, ); \
OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
OPTIONAL(encoding, DwarfAttEncodingField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
align.Val, encoding.Val));
return false;
}
/// ParseDIDerivedType:
/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
/// line: 7, scope: !1, baseType: !2, size: 32,
/// align: 32, offset: 0, flags: 0, extraData: !3)
bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
REQUIRED(tag, DwarfTagField, ); \
OPTIONAL(name, MDStringField, ); \
OPTIONAL(file, MDField, ); \
OPTIONAL(line, LineField, ); \
OPTIONAL(scope, MDField, ); \
REQUIRED(baseType, MDField, ); \
OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
OPTIONAL(flags, DIFlagField, ); \
OPTIONAL(extraData, MDField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(DIDerivedType,
(Context, tag.Val, name.Val, file.Val, line.Val,
scope.Val, baseType.Val, size.Val, align.Val,
offset.Val, flags.Val, extraData.Val));
return false;
}
bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
REQUIRED(tag, DwarfTagField, ); \
OPTIONAL(name, MDStringField, ); \
OPTIONAL(file, MDField, ); \
OPTIONAL(line, LineField, ); \
OPTIONAL(scope, MDField, ); \
OPTIONAL(baseType, MDField, ); \
OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
OPTIONAL(flags, DIFlagField, ); \
OPTIONAL(elements, MDField, ); \
OPTIONAL(runtimeLang, DwarfLangField, ); \
OPTIONAL(vtableHolder, MDField, ); \
OPTIONAL(templateParams, MDField, ); \
OPTIONAL(identifier, MDStringField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(
DICompositeType,
(Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
size.Val, align.Val, offset.Val, flags.Val, elements.Val,
runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
return false;
}
bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
OPTIONAL(flags, DIFlagField, ); \
REQUIRED(types, MDField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
return false;
}
/// ParseDIFileType:
/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
REQUIRED(filename, MDStringField, ); \
REQUIRED(directory, MDStringField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
return false;
}
/// ParseDICompileUnit:
/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
/// splitDebugFilename: "abc.debug", emissionKind: 1,
/// enums: !1, retainedTypes: !2, subprograms: !3,
/// globals: !4, imports: !5, dwoId: 0x0abcd)
bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
REQUIRED(language, DwarfLangField, ); \
REQUIRED(file, MDField, (/* AllowNull */ false)); \
OPTIONAL(producer, MDStringField, ); \
OPTIONAL(isOptimized, MDBoolField, ); \
OPTIONAL(flags, MDStringField, ); \
OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
OPTIONAL(splitDebugFilename, MDStringField, ); \
OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
OPTIONAL(enums, MDField, ); \
OPTIONAL(retainedTypes, MDField, ); \
OPTIONAL(subprograms, MDField, ); \
OPTIONAL(globals, MDField, ); \
OPTIONAL(imports, MDField, ); \
OPTIONAL(dwoId, MDUnsignedField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(DICompileUnit,
(Context, language.Val, file.Val, producer.Val,
isOptimized.Val, flags.Val, runtimeVersion.Val,
splitDebugFilename.Val, emissionKind.Val, enums.Val,
retainedTypes.Val, subprograms.Val, globals.Val,
imports.Val, dwoId.Val));
return false;
}
/// ParseDISubprogram:
/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
/// file: !1, line: 7, type: !2, isLocal: false,
/// isDefinition: true, scopeLine: 8, containingType: !3,
/// virtuality: DW_VIRTUALTIY_pure_virtual,
/// virtualIndex: 10, flags: 11,
/// isOptimized: false, function: void ()* @_Z3foov,
/// templateParams: !4, declaration: !5, variables: !6)
bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
OPTIONAL(scope, MDField, ); \
OPTIONAL(name, MDStringField, ); \
OPTIONAL(linkageName, MDStringField, ); \
OPTIONAL(file, MDField, ); \
OPTIONAL(line, LineField, ); \
OPTIONAL(type, MDField, ); \
OPTIONAL(isLocal, MDBoolField, ); \
OPTIONAL(isDefinition, MDBoolField, (true)); \
OPTIONAL(scopeLine, LineField, ); \
OPTIONAL(containingType, MDField, ); \
OPTIONAL(virtuality, DwarfVirtualityField, ); \
OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
OPTIONAL(flags, DIFlagField, ); \
OPTIONAL(isOptimized, MDBoolField, ); \
OPTIONAL(function, MDConstant, ); \
OPTIONAL(templateParams, MDField, ); \
OPTIONAL(declaration, MDField, ); \
OPTIONAL(variables, MDField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(
DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
line.Val, type.Val, isLocal.Val, isDefinition.Val,
scopeLine.Val, containingType.Val, virtuality.Val,
virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
templateParams.Val, declaration.Val, variables.Val));
return false;
}
/// ParseDILexicalBlock:
/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
REQUIRED(scope, MDField, (/* AllowNull */ false)); \
OPTIONAL(file, MDField, ); \
OPTIONAL(line, LineField, ); \
OPTIONAL(column, ColumnField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(
DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
return false;
}
/// ParseDILexicalBlockFile:
/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
REQUIRED(scope, MDField, (/* AllowNull */ false)); \
OPTIONAL(file, MDField, ); \
REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(DILexicalBlockFile,
(Context, scope.Val, file.Val, discriminator.Val));
return false;
}
/// ParseDINamespace:
/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
REQUIRED(scope, MDField, ); \
OPTIONAL(file, MDField, ); \
OPTIONAL(name, MDStringField, ); \
OPTIONAL(line, LineField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(DINamespace,
(Context, scope.Val, file.Val, name.Val, line.Val));
return false;
}
/// ParseDIModule:
/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
/// includePath: "/usr/include", isysroot: "/")
bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
REQUIRED(scope, MDField, ); \
REQUIRED(name, MDStringField, ); \
OPTIONAL(configMacros, MDStringField, ); \
OPTIONAL(includePath, MDStringField, ); \
OPTIONAL(isysroot, MDStringField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
configMacros.Val, includePath.Val, isysroot.Val));
return false;
}
/// ParseDITemplateTypeParameter:
/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
OPTIONAL(name, MDStringField, ); \
REQUIRED(type, MDField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result =
GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
return false;
}
/// ParseDITemplateValueParameter:
/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
/// name: "V", type: !1, value: i32 7)
bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
OPTIONAL(name, MDStringField, ); \
OPTIONAL(type, MDField, ); \
REQUIRED(value, MDField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(DITemplateValueParameter,
(Context, tag.Val, name.Val, type.Val, value.Val));
return false;
}
/// ParseDIGlobalVariable:
/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
/// file: !1, line: 7, type: !2, isLocal: false,
/// isDefinition: true, variable: i32* @foo,
/// declaration: !3)
bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
OPTIONAL(scope, MDField, ); \
OPTIONAL(linkageName, MDStringField, ); \
OPTIONAL(file, MDField, ); \
OPTIONAL(line, LineField, ); \
OPTIONAL(type, MDField, ); \
OPTIONAL(isLocal, MDBoolField, ); \
OPTIONAL(isDefinition, MDBoolField, (true)); \
OPTIONAL(variable, MDConstant, ); \
OPTIONAL(declaration, MDField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(DIGlobalVariable,
(Context, scope.Val, name.Val, linkageName.Val,
file.Val, line.Val, type.Val, isLocal.Val,
isDefinition.Val, variable.Val, declaration.Val));
return false;
}
/// ParseDILocalVariable:
/// ::= !DILocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
REQUIRED(tag, DwarfTagField, ); \
REQUIRED(scope, MDField, (/* AllowNull */ false)); \
OPTIONAL(name, MDStringField, ); \
OPTIONAL(file, MDField, ); \
OPTIONAL(line, LineField, ); \
OPTIONAL(type, MDField, ); \
OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
OPTIONAL(flags, DIFlagField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(DILocalVariable,
(Context, tag.Val, scope.Val, name.Val, file.Val,
line.Val, type.Val, arg.Val, flags.Val));
return false;
}
/// ParseDIExpression:
/// ::= !DIExpression(0, 7, -1)
bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Lex.Lex();
if (ParseToken(lltok::lparen, "expected '(' here"))
return true;
SmallVector<uint64_t, 8> Elements;
if (Lex.getKind() != lltok::rparen)
do {
if (Lex.getKind() == lltok::DwarfOp) {
if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
Lex.Lex();
Elements.push_back(Op);
continue;
}
return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
}
if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
return TokError("expected unsigned integer");
auto &U = Lex.getAPSIntVal();
if (U.ugt(UINT64_MAX))
return TokError("element too large, limit is " + Twine(UINT64_MAX));
Elements.push_back(U.getZExtValue());
Lex.Lex();
} while (EatIfPresent(lltok::comma));
if (ParseToken(lltok::rparen, "expected ')' here"))
return true;
Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
return false;
}
/// ParseDIObjCProperty:
/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
/// getter: "getFoo", attributes: 7, type: !2)
bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
OPTIONAL(name, MDStringField, ); \
OPTIONAL(file, MDField, ); \
OPTIONAL(line, LineField, ); \
OPTIONAL(setter, MDStringField, ); \
OPTIONAL(getter, MDStringField, ); \
OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
OPTIONAL(type, MDField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(DIObjCProperty,
(Context, name.Val, file.Val, line.Val, setter.Val,
getter.Val, attributes.Val, type.Val));
return false;
}
/// ParseDIImportedEntity:
/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
/// line: 7, name: "foo")
bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
REQUIRED(tag, DwarfTagField, ); \
REQUIRED(scope, MDField, ); \
OPTIONAL(entity, MDField, ); \
OPTIONAL(line, LineField, ); \
OPTIONAL(name, MDStringField, );
PARSE_MD_FIELDS();
#undef VISIT_MD_FIELDS
Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
entity.Val, line.Val, name.Val));
return false;
}
#undef PARSE_MD_FIELD
#undef NOP_FIELD
#undef REQUIRE_FIELD
#undef DECLARE_FIELD
/// ParseMetadataAsValue
/// ::= metadata i32 %local
/// ::= metadata i32 @global
/// ::= metadata i32 7
/// ::= metadata !0
/// ::= metadata !{...}
/// ::= metadata !"string"
bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
// Note: the type 'metadata' has already been parsed.
Metadata *MD;
if (ParseMetadata(MD, &PFS))
return true;
V = MetadataAsValue::get(Context, MD);
return false;
}
/// ParseValueAsMetadata
/// ::= i32 %local
/// ::= i32 @global
/// ::= i32 7
bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
PerFunctionState *PFS) {
Type *Ty;
LocTy Loc;
if (ParseType(Ty, TypeMsg, Loc))
return true;
if (Ty->isMetadataTy())
return Error(Loc, "invalid metadata-value-metadata roundtrip");
Value *V;
if (ParseValue(Ty, V, PFS))
return true;
MD = ValueAsMetadata::get(V);
return false;
}
/// ParseMetadata
/// ::= i32 %local
/// ::= i32 @global
/// ::= i32 7
/// ::= !42
/// ::= !{...}
/// ::= !"string"
/// ::= !DILocation(...)
bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
if (Lex.getKind() == lltok::MetadataVar) {
MDNode *N;
if (ParseSpecializedMDNode(N))
return true;
MD = N;
return false;
}
// ValueAsMetadata:
// <type> <value>
if (Lex.getKind() != lltok::exclaim)
return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
// '!'.
assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
Lex.Lex();
// MDString:
// ::= '!' STRINGCONSTANT
if (Lex.getKind() == lltok::StringConstant) {
MDString *S;
if (ParseMDString(S))
return true;
MD = S;
return false;
}
// MDNode:
// !{ ... }
// !7
MDNode *N;
if (ParseMDNodeTail(N))
return true;
MD = N;
return false;
}
//===----------------------------------------------------------------------===//
// Function Parsing.
//===----------------------------------------------------------------------===//
bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
PerFunctionState *PFS) {
if (Ty->isFunctionTy())
return Error(ID.Loc, "functions are not values, refer to them as pointers");
switch (ID.Kind) {
case ValID::t_LocalID:
if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
return V == nullptr;
case ValID::t_LocalName:
if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
return V == nullptr;
case ValID::t_InlineAsm: {
PointerType *PTy = dyn_cast<PointerType>(Ty);
FunctionType *FTy =
PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
return Error(ID.Loc, "invalid type for inline asm constraint string");
V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
(ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
return false;
}
case ValID::t_GlobalName:
V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
return V == nullptr;
case ValID::t_GlobalID:
V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
return V == nullptr;
case ValID::t_APSInt:
if (!Ty->isIntegerTy())
return Error(ID.Loc, "integer constant must have integer type");
ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
V = ConstantInt::get(Context, ID.APSIntVal);
return false;
case ValID::t_APFloat:
if (!Ty->isFloatingPointTy() ||
!ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
return Error(ID.Loc, "floating point constant invalid for type");
// The lexer has no type info, so builds all half, float, and double FP
// constants as double. Fix this here. Long double does not need this.
if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
bool Ignored;
if (Ty->isHalfTy())
ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
&Ignored);
else if (Ty->isFloatTy())
ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
&Ignored);
}
V = ConstantFP::get(Context, ID.APFloatVal);
if (V->getType() != Ty)
return Error(ID.Loc, "floating point constant does not have type '" +
getTypeString(Ty) + "'");
return false;
case ValID::t_Null:
if (!Ty->isPointerTy())
return Error(ID.Loc, "null must be a pointer type");
V = ConstantPointerNull::get(cast<PointerType>(Ty));
return false;
case ValID::t_Undef:
// FIXME: LabelTy should not be a first-class type.
if (!Ty->isFirstClassType() || Ty->isLabelTy())
return Error(ID.Loc, "invalid type for undef constant");
V = UndefValue::get(Ty);
return false;
case ValID::t_EmptyArray:
if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
return Error(ID.Loc, "invalid empty array initializer");
V = UndefValue::get(Ty);
return false;
case ValID::t_Zero:
// FIXME: LabelTy should not be a first-class type.
if (!Ty->isFirstClassType() || Ty->isLabelTy())
return Error(ID.Loc, "invalid type for null constant");
V = Constant::getNullValue(Ty);
return false;
case ValID::t_Constant:
if (ID.ConstantVal->getType() != Ty)
return Error(ID.Loc, "constant expression type mismatch");
V = ID.ConstantVal;
return false;
case ValID::t_ConstantStruct:
case ValID::t_PackedConstantStruct:
if (StructType *ST = dyn_cast<StructType>(Ty)) {
if (ST->getNumElements() != ID.UIntVal)
return Error(ID.Loc,
"initializer with struct type has wrong # elements");
if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
return Error(ID.Loc, "packed'ness of initializer and type don't match");
// Verify that the elements are compatible with the structtype.
for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
return Error(ID.Loc, "element " + Twine(i) +
" of struct initializer doesn't match struct element type");
V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
ID.UIntVal));
} else
return Error(ID.Loc, "constant expression type mismatch");
return false;
}
llvm_unreachable("Invalid ValID");
}
bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
V = nullptr;
ValID ID;
return ParseValID(ID, PFS) ||
ConvertValIDToValue(Ty, ID, V, PFS);
}
bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Type *Ty = nullptr;
return ParseType(Ty) ||
ParseValue(Ty, V, PFS);
}
bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
PerFunctionState &PFS) {
Value *V;
Loc = Lex.getLoc();
if (ParseTypeAndValue(V, PFS)) return true;
if (!isa<BasicBlock>(V))
return Error(Loc, "expected a basic block");
BB = cast<BasicBlock>(V);
return false;
}
/// FunctionHeader
/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
// Parse the linkage.
LocTy LinkageLoc = Lex.getLoc();
unsigned Linkage;
unsigned Visibility;
unsigned DLLStorageClass;
AttrBuilder RetAttrs;
unsigned CC;
Type *RetType = nullptr;
LocTy RetTypeLoc = Lex.getLoc();
if (ParseOptionalLinkage(Linkage) ||
ParseOptionalVisibility(Visibility) ||
ParseOptionalDLLStorageClass(DLLStorageClass) ||
ParseOptionalCallingConv(CC) ||
ParseOptionalReturnAttrs(RetAttrs) ||
ParseType(RetType, RetTypeLoc, true /*void allowed*/))
return true;
// Verify that the linkage is ok.
switch ((GlobalValue::LinkageTypes)Linkage) {
case GlobalValue::ExternalLinkage:
break; // always ok.
case GlobalValue::ExternalWeakLinkage:
if (isDefine)
return Error(LinkageLoc, "invalid linkage for function definition");
break;
case GlobalValue::PrivateLinkage:
case GlobalValue::InternalLinkage:
case GlobalValue::AvailableExternallyLinkage:
case GlobalValue::LinkOnceAnyLinkage:
case GlobalValue::LinkOnceODRLinkage:
case GlobalValue::WeakAnyLinkage:
case GlobalValue::WeakODRLinkage:
if (!isDefine)
return Error(LinkageLoc, "invalid linkage for function declaration");
break;
case GlobalValue::AppendingLinkage:
case GlobalValue::CommonLinkage:
return Error(LinkageLoc, "invalid function linkage type");
}
if (!isValidVisibilityForLinkage(Visibility, Linkage))
return Error(LinkageLoc,
"symbol with local linkage must have default visibility");
if (!FunctionType::isValidReturnType(RetType))
return Error(RetTypeLoc, "invalid function return type");
LocTy NameLoc = Lex.getLoc();
std::string FunctionName;
if (Lex.getKind() == lltok::GlobalVar) {
FunctionName = Lex.getStrVal();
} else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
unsigned NameID = Lex.getUIntVal();
if (NameID != NumberedVals.size())
return TokError("function expected to be numbered '%" +
Twine(NumberedVals.size()) + "'");
} else {
return TokError("expected function name");
}
Lex.Lex();
if (Lex.getKind() != lltok::lparen)
return TokError("expected '(' in function argument list");
SmallVector<ArgInfo, 8> ArgList;
bool isVarArg;
AttrBuilder FuncAttrs;
std::vector<unsigned> FwdRefAttrGrps;
LocTy BuiltinLoc;
std::string Section;
unsigned Alignment;
std::string GC;
bool UnnamedAddr;
LocTy UnnamedAddrLoc;
Constant *Prefix = nullptr;
Constant *Prologue = nullptr;
Constant *PersonalityFn = nullptr;
Comdat *C;
if (ParseArgumentList(ArgList, isVarArg) ||
ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
&UnnamedAddrLoc) ||
ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
BuiltinLoc) ||
(EatIfPresent(lltok::kw_section) &&
ParseStringConstant(Section)) ||
parseOptionalComdat(FunctionName, C) ||
ParseOptionalAlignment(Alignment) ||
(EatIfPresent(lltok::kw_gc) &&
ParseStringConstant(GC)) ||
(EatIfPresent(lltok::kw_prefix) &&
ParseGlobalTypeAndValue(Prefix)) ||
(EatIfPresent(lltok::kw_prologue) &&
ParseGlobalTypeAndValue(Prologue)) ||
(EatIfPresent(lltok::kw_personality) &&
ParseGlobalTypeAndValue(PersonalityFn)))
return true;
if (FuncAttrs.contains(Attribute::Builtin))
return Error(BuiltinLoc, "'builtin' attribute not valid on function");
// If the alignment was parsed as an attribute, move to the alignment field.
if (FuncAttrs.hasAlignmentAttr()) {
Alignment = FuncAttrs.getAlignment();
FuncAttrs.removeAttribute(Attribute::Alignment);
}
// Okay, if we got here, the function is syntactically valid. Convert types
// and do semantic checks.
std::vector<Type*> ParamTypeList;
SmallVector<AttributeSet, 8> Attrs;
if (RetAttrs.hasAttributes())
Attrs.push_back(AttributeSet::get(RetType->getContext(),
AttributeSet::ReturnIndex,
RetAttrs));
for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
ParamTypeList.push_back(ArgList[i].Ty);
if (ArgList[i].Attrs.hasAttributes(i + 1)) {
AttrBuilder B(ArgList[i].Attrs, i + 1);
Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
}
}
if (FuncAttrs.hasAttributes())
Attrs.push_back(AttributeSet::get(RetType->getContext(),
AttributeSet::FunctionIndex,
FuncAttrs));
AttributeSet PAL = AttributeSet::get(Context, Attrs);
if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
return Error(RetTypeLoc, "functions with 'sret' argument must return void");
FunctionType *FT =
FunctionType::get(RetType, ParamTypeList, isVarArg);
PointerType *PFT = PointerType::getUnqual(FT);
Fn = nullptr;
if (!FunctionName.empty()) {
// If this was a definition of a forward reference, remove the definition
// from the forward reference table and fill in the forward ref.
std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
ForwardRefVals.find(FunctionName);
if (FRVI != ForwardRefVals.end()) {
Fn = M->getFunction(FunctionName);
if (!Fn)
return Error(FRVI->second.second, "invalid forward reference to "
"function as global value!");
if (Fn->getType() != PFT)
return Error(FRVI->second.second, "invalid forward reference to "
"function '" + FunctionName + "' with wrong type!");
ForwardRefVals.erase(FRVI);
} else if ((Fn = M->getFunction(FunctionName))) {
// Reject redefinitions.
return Error(NameLoc, "invalid redefinition of function '" +
FunctionName + "'");
} else if (M->getNamedValue(FunctionName)) {
return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
}
} else {
// If this is a definition of a forward referenced function, make sure the
// types agree.
std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
= ForwardRefValIDs.find(NumberedVals.size());
if (I != ForwardRefValIDs.end()) {
Fn = cast<Function>(I->second.first);
if (Fn->getType() != PFT)
return Error(NameLoc, "type of definition and forward reference of '@" +
Twine(NumberedVals.size()) + "' disagree");
ForwardRefValIDs.erase(I);
}
}
if (!Fn)
Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
else // Move the forward-reference to the correct spot in the module.
M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
if (FunctionName.empty())
NumberedVals.push_back(Fn);
Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Fn->setCallingConv(CC);
Fn->setAttributes(PAL);
Fn->setUnnamedAddr(UnnamedAddr);
Fn->setAlignment(Alignment);
Fn->setSection(Section);
Fn->setComdat(C);
Fn->setPersonalityFn(PersonalityFn);
if (!GC.empty()) Fn->setGC(GC.c_str());
Fn->setPrefixData(Prefix);
Fn->setPrologueData(Prologue);
ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
// Add all of the arguments we parsed to the function.
Function::arg_iterator ArgIt = Fn->arg_begin();
for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
// If the argument has a name, insert it into the argument symbol table.
if (ArgList[i].Name.empty()) continue;
// Set the name, if it conflicted, it will be auto-renamed.
ArgIt->setName(ArgList[i].Name);
if (ArgIt->getName() != ArgList[i].Name)
return Error(ArgList[i].Loc, "redefinition of argument '%" +
ArgList[i].Name + "'");
}
if (isDefine)
return false;
// Check the declaration has no block address forward references.
ValID ID;
if (FunctionName.empty()) {
ID.Kind = ValID::t_GlobalID;
ID.UIntVal = NumberedVals.size() - 1;
} else {
ID.Kind = ValID::t_GlobalName;
ID.StrVal = FunctionName;
}
auto Blocks = ForwardRefBlockAddresses.find(ID);
if (Blocks != ForwardRefBlockAddresses.end())
return Error(Blocks->first.Loc,
"cannot take blockaddress inside a declaration");
return false;
}
bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
ValID ID;
if (FunctionNumber == -1) {
ID.Kind = ValID::t_GlobalName;
ID.StrVal = F.getName();
} else {
ID.Kind = ValID::t_GlobalID;
ID.UIntVal = FunctionNumber;
}
auto Blocks = P.ForwardRefBlockAddresses.find(ID);
if (Blocks == P.ForwardRefBlockAddresses.end())
return false;
for (const auto &I : Blocks->second) {
const ValID &BBID = I.first;
GlobalValue *GV = I.second;
assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
"Expected local id or name");
BasicBlock *BB;
if (BBID.Kind == ValID::t_LocalName)
BB = GetBB(BBID.StrVal, BBID.Loc);
else
BB = GetBB(BBID.UIntVal, BBID.Loc);
if (!BB)
return P.Error(BBID.Loc, "referenced value is not a basic block");
GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
GV->eraseFromParent();
}
P.ForwardRefBlockAddresses.erase(Blocks);
return false;
}
/// ParseFunctionBody
/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
bool LLParser::ParseFunctionBody(Function &Fn) {
if (Lex.getKind() != lltok::lbrace)
return TokError("expected '{' in function body");
Lex.Lex(); // eat the {.
int FunctionNumber = -1;
if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
PerFunctionState PFS(*this, Fn, FunctionNumber);
// Resolve block addresses and allow basic blocks to be forward-declared
// within this function.
if (PFS.resolveForwardRefBlockAddresses())
return true;
SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
// We need at least one basic block.
if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
return TokError("function body requires at least one basic block");
while (Lex.getKind() != lltok::rbrace &&
Lex.getKind() != lltok::kw_uselistorder)
if (ParseBasicBlock(PFS)) return true;
while (Lex.getKind() != lltok::rbrace)
if (ParseUseListOrder(&PFS))
return true;
// Eat the }.
Lex.Lex();
// Verify function is ok.
return PFS.FinishFunction();
}
/// ParseBasicBlock
/// ::= LabelStr? Instruction*
bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
// If this basic block starts out with a name, remember it.
std::string Name;
LocTy NameLoc = Lex.getLoc();
if (Lex.getKind() == lltok::LabelStr) {
Name = Lex.getStrVal();
Lex.Lex();
}
BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
if (!BB)
return Error(NameLoc,
"unable to create block named '" + Name + "'");
std::string NameStr;
// Parse the instructions in this block until we get a terminator.
Instruction *Inst;
do {
// This instruction may have three possibilities for a name: a) none
// specified, b) name specified "%foo =", c) number specified: "%4 =".
LocTy NameLoc = Lex.getLoc();
int NameID = -1;
NameStr = "";
if (Lex.getKind() == lltok::LocalVarID) {
NameID = Lex.getUIntVal();
Lex.Lex();
if (ParseToken(lltok::equal, "expected '=' after instruction id"))
return true;
} else if (Lex.getKind() == lltok::LocalVar) {
NameStr = Lex.getStrVal();
Lex.Lex();
if (ParseToken(lltok::equal, "expected '=' after instruction name"))
return true;
}
switch (ParseInstruction(Inst, BB, PFS)) {
default: llvm_unreachable("Unknown ParseInstruction result!");
case InstError: return true;
case InstNormal:
BB->getInstList().push_back(Inst);
// With a normal result, we check to see if the instruction is followed by
// a comma and metadata.
if (EatIfPresent(lltok::comma))
if (ParseInstructionMetadata(*Inst))
return true;
break;
case InstExtraComma:
BB->getInstList().push_back(Inst);
// If the instruction parser ate an extra comma at the end of it, it
// *must* be followed by metadata.
if (ParseInstructionMetadata(*Inst))
return true;
break;
}
// Set the name on the instruction.
if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
} while (!isa<TerminatorInst>(Inst));
return false;
}
//===----------------------------------------------------------------------===//
// Instruction Parsing.
//===----------------------------------------------------------------------===//
/// ParseInstruction - Parse one of the many different instructions.
///
int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
PerFunctionState &PFS) {
lltok::Kind Token = Lex.getKind();
if (Token == lltok::Eof)
return TokError("found end of file when expecting more instructions");
LocTy Loc = Lex.getLoc();
unsigned KeywordVal = Lex.getUIntVal();
Lex.Lex(); // Eat the keyword.
switch (Token) {
default: return Error(Loc, "expected instruction opcode");
// Terminator Instructions.
case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
case lltok::kw_br: return ParseBr(Inst, PFS);
case lltok::kw_switch: return ParseSwitch(Inst, PFS);
case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
case lltok::kw_resume: return ParseResume(Inst, PFS);
// Binary Operators.
case lltok::kw_add:
case lltok::kw_sub:
case lltok::kw_mul:
case lltok::kw_shl: {
bool NUW = EatIfPresent(lltok::kw_nuw);
bool NSW = EatIfPresent(lltok::kw_nsw);
if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
return false;
}
case lltok::kw_fadd:
case lltok::kw_fsub:
case lltok::kw_fmul:
case lltok::kw_fdiv:
case lltok::kw_frem: {
FastMathFlags FMF = EatFastMathFlagsIfPresent();
int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
if (Res != 0)
return Res;
if (FMF.any())
Inst->setFastMathFlags(FMF);
return 0;
}
case lltok::kw_sdiv:
case lltok::kw_udiv:
case lltok::kw_lshr:
case lltok::kw_ashr: {
bool Exact = EatIfPresent(lltok::kw_exact);
if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
return false;
}
case lltok::kw_urem:
case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
case lltok::kw_and:
case lltok::kw_or:
case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
case lltok::kw_fcmp: {
FastMathFlags FMF = EatFastMathFlagsIfPresent();
int Res = ParseCompare(Inst, PFS, KeywordVal);
if (Res != 0)
return Res;
if (FMF.any())
Inst->setFastMathFlags(FMF);
return 0;
}
// Casts.
case lltok::kw_trunc:
case lltok::kw_zext:
case lltok::kw_sext:
case lltok::kw_fptrunc:
case lltok::kw_fpext:
case lltok::kw_bitcast:
case lltok::kw_addrspacecast:
case lltok::kw_uitofp:
case lltok::kw_sitofp:
case lltok::kw_fptoui:
case lltok::kw_fptosi:
case lltok::kw_inttoptr:
case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
// Other.
case lltok::kw_select: return ParseSelect(Inst, PFS);
case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
case lltok::kw_phi: return ParsePHI(Inst, PFS);
case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
// Call.
case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
// Memory.
case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
case lltok::kw_load: return ParseLoad(Inst, PFS);
case lltok::kw_store: return ParseStore(Inst, PFS);
case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
case lltok::kw_fence: return ParseFence(Inst, PFS);
case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
}
}
/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
if (Opc == Instruction::FCmp) {
switch (Lex.getKind()) {
default: return TokError("expected fcmp predicate (e.g. 'oeq')");
case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
}
} else {
switch (Lex.getKind()) {
default: return TokError("expected icmp predicate (e.g. 'eq')");
case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
}
}
Lex.Lex();
return false;
}
//===----------------------------------------------------------------------===//
// Terminator Instructions.
//===----------------------------------------------------------------------===//
/// ParseRet - Parse a return instruction.
/// ::= 'ret' void (',' !dbg, !1)*
/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
PerFunctionState &PFS) {
SMLoc TypeLoc = Lex.getLoc();
Type *Ty = nullptr;
if (ParseType(Ty, true /*void allowed*/)) return true;
Type *ResType = PFS.getFunction().getReturnType();
if (Ty->isVoidTy()) {
if (!ResType->isVoidTy())
return Error(TypeLoc, "value doesn't match function result type '" +
getTypeString(ResType) + "'");
Inst = ReturnInst::Create(Context);
return false;
}
Value *RV;
if (ParseValue(Ty, RV, PFS)) return true;
if (ResType != RV->getType())
return Error(TypeLoc, "value doesn't match function result type '" +
getTypeString(ResType) + "'");
Inst = ReturnInst::Create(Context, RV);
return false;
}
/// ParseBr
/// ::= 'br' TypeAndValue
/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
LocTy Loc, Loc2;
Value *Op0;
BasicBlock *Op1, *Op2;
if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
Inst = BranchInst::Create(BB);
return false;
}
if (Op0->getType() != Type::getInt1Ty(Context))
return Error(Loc, "branch condition must have 'i1' type");
if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
ParseToken(lltok::comma, "expected ',' after true destination") ||
ParseTypeAndBasicBlock(Op2, Loc2, PFS))
return true;
Inst = BranchInst::Create(Op1, Op2, Op0);
return false;
}
/// ParseSwitch
/// Instruction
/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
/// JumpTable
/// ::= (TypeAndValue ',' TypeAndValue)*
bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
LocTy CondLoc, BBLoc;
Value *Cond;
BasicBlock *DefaultBB;
if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
ParseToken(lltok::comma, "expected ',' after switch condition") ||
ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
ParseToken(lltok::lsquare, "expected '[' with switch table"))
return true;
if (!Cond->getType()->isIntegerTy())
return Error(CondLoc, "switch condition must have integer type");
// Parse the jump table pairs.
SmallPtrSet<Value*, 32> SeenCases;
SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
while (Lex.getKind() != lltok::rsquare) {
Value *Constant;
BasicBlock *DestBB;
if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
ParseToken(lltok::comma, "expected ',' after case value") ||
ParseTypeAndBasicBlock(DestBB, PFS))
return true;
if (!SeenCases.insert(Constant).second)
return Error(CondLoc, "duplicate case value in switch");
if (!isa<ConstantInt>(Constant))
return Error(CondLoc, "case value is not a constant integer");
Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
}
Lex.Lex(); // Eat the ']'.
SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
for (unsigned i = 0, e = Table.size(); i != e; ++i)
SI->addCase(Table[i].first, Table[i].second);
Inst = SI;
return false;
}
/// ParseIndirectBr
/// Instruction
/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
LocTy AddrLoc;
Value *Address;
if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
return true;
if (!Address->getType()->isPointerTy())
return Error(AddrLoc, "indirectbr address must have pointer type");
// Parse the destination list.
SmallVector<BasicBlock*, 16> DestList;
if (Lex.getKind() != lltok::rsquare) {
BasicBlock *DestBB;
if (ParseTypeAndBasicBlock(DestBB, PFS))
return true;
DestList.push_back(DestBB);
while (EatIfPresent(lltok::comma)) {
if (ParseTypeAndBasicBlock(DestBB, PFS))
return true;
DestList.push_back(DestBB);
}
}
if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
return true;
IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
for (unsigned i = 0, e = DestList.size(); i != e; ++i)
IBI->addDestination(DestList[i]);
Inst = IBI;
return false;
}
/// ParseInvoke
/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
LocTy CallLoc = Lex.getLoc();
AttrBuilder RetAttrs, FnAttrs;
std::vector<unsigned> FwdRefAttrGrps;
LocTy NoBuiltinLoc;
unsigned CC;
Type *RetType = nullptr;
LocTy RetTypeLoc;
ValID CalleeID;
SmallVector<ParamInfo, 16> ArgList;
BasicBlock *NormalBB, *UnwindBB;
if (ParseOptionalCallingConv(CC) ||
ParseOptionalReturnAttrs(RetAttrs) ||
ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
ParseValID(CalleeID) ||
ParseParameterList(ArgList, PFS) ||
ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
NoBuiltinLoc) ||
ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
ParseTypeAndBasicBlock(NormalBB, PFS) ||
ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
ParseTypeAndBasicBlock(UnwindBB, PFS))
return true;
// If RetType is a non-function pointer type, then this is the short syntax
// for the call, which means that RetType is just the return type. Infer the
// rest of the function argument types from the arguments that are present.
FunctionType *Ty = dyn_cast<FunctionType>(RetType);
if (!Ty) {
// Pull out the types of all of the arguments...
std::vector<Type*> ParamTypes;
for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
ParamTypes.push_back(ArgList[i].V->getType());
if (!FunctionType::isValidReturnType(RetType))
return Error(RetTypeLoc, "Invalid result type for LLVM function");
Ty = FunctionType::get(RetType, ParamTypes, false);
}
// Look up the callee.
Value *Callee;
if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
return true;
// Set up the Attribute for the function.
SmallVector<AttributeSet, 8> Attrs;
if (RetAttrs.hasAttributes())
Attrs.push_back(AttributeSet::get(RetType->getContext(),
AttributeSet::ReturnIndex,
RetAttrs));
SmallVector<Value*, 8> Args;
// Loop through FunctionType's arguments and ensure they are specified
// correctly. Also, gather any parameter attributes.
FunctionType::param_iterator I = Ty->param_begin();
FunctionType::param_iterator E = Ty->param_end();
for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Type *ExpectedTy = nullptr;
if (I != E) {
ExpectedTy = *I++;
} else if (!Ty->isVarArg()) {
return Error(ArgList[i].Loc, "too many arguments specified");
}
if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
return Error(ArgList[i].Loc, "argument is not of expected type '" +
getTypeString(ExpectedTy) + "'");
Args.push_back(ArgList[i].V);
if (ArgList[i].Attrs.hasAttributes(i + 1)) {
AttrBuilder B(ArgList[i].Attrs, i + 1);
Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
}
}
if (I != E)
return Error(CallLoc, "not enough parameters specified for call");
if (FnAttrs.hasAttributes()) {
if (FnAttrs.hasAlignmentAttr())
return Error(CallLoc, "invoke instructions may not have an alignment");
Attrs.push_back(AttributeSet::get(RetType->getContext(),
AttributeSet::FunctionIndex,
FnAttrs));
}
// Finish off the Attribute and check them
AttributeSet PAL = AttributeSet::get(Context, Attrs);
InvokeInst *II = InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args);
II->setCallingConv(CC);
II->setAttributes(PAL);
ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Inst = II;
return false;
}
/// ParseResume
/// ::= 'resume' TypeAndValue
bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
Value *Exn; LocTy ExnLoc;
if (ParseTypeAndValue(Exn, ExnLoc, PFS))
return true;
ResumeInst *RI = ResumeInst::Create(Exn);
Inst = RI;
return false;
}
//===----------------------------------------------------------------------===//
// Binary Operators.
//===----------------------------------------------------------------------===//
/// ParseArithmetic
/// ::= ArithmeticOps TypeAndValue ',' Value
///
/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
unsigned Opc, unsigned OperandType) {
LocTy Loc; Value *LHS, *RHS;
if (ParseTypeAndValue(LHS, Loc, PFS) ||
ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
ParseValue(LHS->getType(), RHS, PFS))
return true;
bool Valid;
switch (OperandType) {
default: llvm_unreachable("Unknown operand type!");
case 0: // int or FP.
Valid = LHS->getType()->isIntOrIntVectorTy() ||
LHS->getType()->isFPOrFPVectorTy();
break;
case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
}
if (!Valid)
return Error(Loc, "invalid operand type for instruction");
Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
return false;
}
/// ParseLogical
/// ::= ArithmeticOps TypeAndValue ',' Value {
bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
unsigned Opc) {
LocTy Loc; Value *LHS, *RHS;
if (ParseTypeAndValue(LHS, Loc, PFS) ||
ParseToken(lltok::comma, "expected ',' in logical operation") ||
ParseValue(LHS->getType(), RHS, PFS))
return true;
if (!LHS->getType()->isIntOrIntVectorTy())
return Error(Loc,"instruction requires integer or integer vector operands");
Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
return false;
}
/// ParseCompare
/// ::= 'icmp' IPredicates TypeAndValue ',' Value
/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
unsigned Opc) {
// Parse the integer/fp comparison predicate.
LocTy Loc;
unsigned Pred;
Value *LHS, *RHS;
if (ParseCmpPredicate(Pred, Opc) ||
ParseTypeAndValue(LHS, Loc, PFS) ||
ParseToken(lltok::comma, "expected ',' after compare value") ||
ParseValue(LHS->getType(), RHS, PFS))
return true;
if (Opc == Instruction::FCmp) {
if (!LHS->getType()->isFPOrFPVectorTy())
return Error(Loc, "fcmp requires floating point operands");
Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
} else {
assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
if (!LHS->getType()->isIntOrIntVectorTy() &&
!LHS->getType()->getScalarType()->isPointerTy())
return Error(Loc, "icmp requires integer operands");
Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
}
return false;
}
//===----------------------------------------------------------------------===//
// Other Instructions.
//===----------------------------------------------------------------------===//
/// ParseCast
/// ::= CastOpc TypeAndValue 'to' Type
bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
unsigned Opc) {
LocTy Loc;
Value *Op;
Type *DestTy = nullptr;
if (ParseTypeAndValue(Op, Loc, PFS) ||
ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
ParseType(DestTy))
return true;
if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
return Error(Loc, "invalid cast opcode for cast from '" +
getTypeString(Op->getType()) + "' to '" +
getTypeString(DestTy) + "'");
}
Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
return false;
}
/// ParseSelect
/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
LocTy Loc;
Value *Op0, *Op1, *Op2;
if (ParseTypeAndValue(Op0, Loc, PFS) ||
ParseToken(lltok::comma, "expected ',' after select condition") ||
ParseTypeAndValue(Op1, PFS) ||
ParseToken(lltok::comma, "expected ',' after select value") ||
ParseTypeAndValue(Op2, PFS))
return true;
if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
return Error(Loc, Reason);
Inst = SelectInst::Create(Op0, Op1, Op2);
return false;
}
/// ParseVA_Arg
/// ::= 'va_arg' TypeAndValue ',' Type
bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Value *Op;
Type *EltTy = nullptr;
LocTy TypeLoc;
if (ParseTypeAndValue(Op, PFS) ||
ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
ParseType(EltTy, TypeLoc))
return true;
if (!EltTy->isFirstClassType())
return Error(TypeLoc, "va_arg requires operand with first class type");
Inst = new VAArgInst(Op, EltTy);
return false;
}
/// ParseExtractElement
/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
LocTy Loc;
Value *Op0, *Op1;
if (ParseTypeAndValue(Op0, Loc, PFS) ||
ParseToken(lltok::comma, "expected ',' after extract value") ||
ParseTypeAndValue(Op1, PFS))
return true;
if (!ExtractElementInst::isValidOperands(Op0, Op1))
return Error(Loc, "invalid extractelement operands");
Inst = ExtractElementInst::Create(Op0, Op1);
return false;
}
/// ParseInsertElement
/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
LocTy Loc;
Value *Op0, *Op1, *Op2;
if (ParseTypeAndValue(Op0, Loc, PFS) ||
ParseToken(lltok::comma, "expected ',' after insertelement value") ||
ParseTypeAndValue(Op1, PFS) ||
ParseToken(lltok::comma, "expected ',' after insertelement value") ||
ParseTypeAndValue(Op2, PFS))
return true;
if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
return Error(Loc, "invalid insertelement operands");
Inst = InsertElementInst::Create(Op0, Op1, Op2);
return false;
}
/// ParseShuffleVector
/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
LocTy Loc;
Value *Op0, *Op1, *Op2;
if (ParseTypeAndValue(Op0, Loc, PFS) ||
ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
ParseTypeAndValue(Op1, PFS) ||
ParseToken(lltok::comma, "expected ',' after shuffle value") ||
ParseTypeAndValue(Op2, PFS))
return true;
if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
return Error(Loc, "invalid shufflevector operands");
Inst = new ShuffleVectorInst(Op0, Op1, Op2);
return false;
}
/// ParsePHI
/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Type *Ty = nullptr; LocTy TypeLoc;
Value *Op0, *Op1;
if (ParseType(Ty, TypeLoc) ||
ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
ParseValue(Ty, Op0, PFS) ||
ParseToken(lltok::comma, "expected ',' after insertelement value") ||
ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
ParseToken(lltok::rsquare, "expected ']' in phi value list"))
return true;
bool AteExtraComma = false;
SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
while (1) {
PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
if (!EatIfPresent(lltok::comma))
break;
if (Lex.getKind() == lltok::MetadataVar) {
AteExtraComma = true;
break;
}
if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
ParseValue(Ty, Op0, PFS) ||
ParseToken(lltok::comma, "expected ',' after insertelement value") ||
ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
ParseToken(lltok::rsquare, "expected ']' in phi value list"))
return true;
}
if (!Ty->isFirstClassType())
return Error(TypeLoc, "phi node must have first class type");
PHINode *PN = PHINode::Create(Ty, PHIVals.size());
for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
Inst = PN;
return AteExtraComma ? InstExtraComma : InstNormal;
}
/// ParseLandingPad
/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
/// Clause
/// ::= 'catch' TypeAndValue
/// ::= 'filter'
/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Type *Ty = nullptr; LocTy TyLoc;
if (ParseType(Ty, TyLoc))
return true;
std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
LandingPadInst::ClauseType CT;
if (EatIfPresent(lltok::kw_catch))
CT = LandingPadInst::Catch;
else if (EatIfPresent(lltok::kw_filter))
CT = LandingPadInst::Filter;
else
return TokError("expected 'catch' or 'filter' clause type");
Value *V;
LocTy VLoc;
if (ParseTypeAndValue(V, VLoc, PFS))
return true;
// A 'catch' type expects a non-array constant. A filter clause expects an
// array constant.
if (CT == LandingPadInst::Catch) {
if (isa<ArrayType>(V->getType()))
Error(VLoc, "'catch' clause has an invalid type");
} else {
if (!isa<ArrayType>(V->getType()))
Error(VLoc, "'filter' clause has an invalid type");
}
Constant *CV = dyn_cast<Constant>(V);
if (!CV)
return Error(VLoc, "clause argument must be a constant");
LP->addClause(CV);
}
Inst = LP.release();
return false;
}
/// ParseCall
/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
/// ParameterList OptionalAttrs
/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
/// ParameterList OptionalAttrs
/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
/// ParameterList OptionalAttrs
bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
CallInst::TailCallKind TCK) {
AttrBuilder RetAttrs, FnAttrs;
std::vector<unsigned> FwdRefAttrGrps;
LocTy BuiltinLoc;
unsigned CC;
Type *RetType = nullptr;
LocTy RetTypeLoc;
ValID CalleeID;
SmallVector<ParamInfo, 16> ArgList;
LocTy CallLoc = Lex.getLoc();
if ((TCK != CallInst::TCK_None &&
ParseToken(lltok::kw_call, "expected 'tail call'")) ||
ParseOptionalCallingConv(CC) ||
ParseOptionalReturnAttrs(RetAttrs) ||
ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
ParseValID(CalleeID) ||
ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
PFS.getFunction().isVarArg()) ||
ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
BuiltinLoc))
return true;
// If RetType is a non-function pointer type, then this is the short syntax
// for the call, which means that RetType is just the return type. Infer the
// rest of the function argument types from the arguments that are present.
FunctionType *Ty = dyn_cast<FunctionType>(RetType);
if (!Ty) {
// Pull out the types of all of the arguments...
std::vector<Type*> ParamTypes;
for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
ParamTypes.push_back(ArgList[i].V->getType());
if (!FunctionType::isValidReturnType(RetType))
return Error(RetTypeLoc, "Invalid result type for LLVM function");
Ty = FunctionType::get(RetType, ParamTypes, false);
}
// Look up the callee.
Value *Callee;
if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
return true;
// Set up the Attribute for the function.
SmallVector<AttributeSet, 8> Attrs;
if (RetAttrs.hasAttributes())
Attrs.push_back(AttributeSet::get(RetType->getContext(),
AttributeSet::ReturnIndex,
RetAttrs));
SmallVector<Value*, 8> Args;
// Loop through FunctionType's arguments and ensure they are specified
// correctly. Also, gather any parameter attributes.
FunctionType::param_iterator I = Ty->param_begin();
FunctionType::param_iterator E = Ty->param_end();
for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Type *ExpectedTy = nullptr;
if (I != E) {
ExpectedTy = *I++;
} else if (!Ty->isVarArg()) {
return Error(ArgList[i].Loc, "too many arguments specified");
}
if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
return Error(ArgList[i].Loc, "argument is not of expected type '" +
getTypeString(ExpectedTy) + "'");
Args.push_back(ArgList[i].V);
if (ArgList[i].Attrs.hasAttributes(i + 1)) {
AttrBuilder B(ArgList[i].Attrs, i + 1);
Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
}
}
if (I != E)
return Error(CallLoc, "not enough parameters specified for call");
if (FnAttrs.hasAttributes()) {
if (FnAttrs.hasAlignmentAttr())
return Error(CallLoc, "call instructions may not have an alignment");
Attrs.push_back(AttributeSet::get(RetType->getContext(),
AttributeSet::FunctionIndex,
FnAttrs));
}
// Finish off the Attribute and check them
AttributeSet PAL = AttributeSet::get(Context, Attrs);
CallInst *CI = CallInst::Create(Ty, Callee, Args);
CI->setTailCallKind(TCK);
CI->setCallingConv(CC);
CI->setAttributes(PAL);
ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Inst = CI;
return false;
}
//===----------------------------------------------------------------------===//
// Memory Instructions.
//===----------------------------------------------------------------------===//
/// ParseAlloc
/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Value *Size = nullptr;
LocTy SizeLoc, TyLoc;
unsigned Alignment = 0;
Type *Ty = nullptr;
bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
if (ParseType(Ty, TyLoc)) return true;
if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
return Error(TyLoc, "invalid type for alloca");
bool AteExtraComma = false;
if (EatIfPresent(lltok::comma)) {
if (Lex.getKind() == lltok::kw_align) {
if (ParseOptionalAlignment(Alignment)) return true;
} else if (Lex.getKind() == lltok::MetadataVar) {
AteExtraComma = true;
} else {
if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
ParseOptionalCommaAlign(Alignment, AteExtraComma))
return true;
}
}
if (Size && !Size->getType()->isIntegerTy())
return Error(SizeLoc, "element count must have integer type");
AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
AI->setUsedWithInAlloca(IsInAlloca);
Inst = AI;
return AteExtraComma ? InstExtraComma : InstNormal;
}
/// ParseLoad
/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Value *Val; LocTy Loc;
unsigned Alignment = 0;
bool AteExtraComma = false;
bool isAtomic = false;
AtomicOrdering Ordering = NotAtomic;
SynchronizationScope Scope = CrossThread;
if (Lex.getKind() == lltok::kw_atomic) {
isAtomic = true;
Lex.Lex();
}
bool isVolatile = false;
if (Lex.getKind() == lltok::kw_volatile) {
isVolatile = true;
Lex.Lex();
}
Type *Ty;
LocTy ExplicitTypeLoc = Lex.getLoc();
if (ParseType(Ty) ||
ParseToken(lltok::comma, "expected comma after load's type") ||
ParseTypeAndValue(Val, Loc, PFS) ||
ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
ParseOptionalCommaAlign(Alignment, AteExtraComma))
return true;
if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
return Error(Loc, "load operand must be a pointer to a first class type");
if (isAtomic && !Alignment)
return Error(Loc, "atomic load must have explicit non-zero alignment");
if (Ordering == Release || Ordering == AcquireRelease)
return Error(Loc, "atomic load cannot use Release ordering");
if (Ty != cast<PointerType>(Val->getType())->getElementType())
return Error(ExplicitTypeLoc,
"explicit pointee type doesn't match operand's pointee type");
Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
return AteExtraComma ? InstExtraComma : InstNormal;
}
/// ParseStore
/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Value *Val, *Ptr; LocTy Loc, PtrLoc;
unsigned Alignment = 0;
bool AteExtraComma = false;
bool isAtomic = false;
AtomicOrdering Ordering = NotAtomic;
SynchronizationScope Scope = CrossThread;
if (Lex.getKind() == lltok::kw_atomic) {
isAtomic = true;
Lex.Lex();
}
bool isVolatile = false;
if (Lex.getKind() == lltok::kw_volatile) {
isVolatile = true;
Lex.Lex();
}
if (ParseTypeAndValue(Val, Loc, PFS) ||
ParseToken(lltok::comma, "expected ',' after store operand") ||
ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
ParseOptionalCommaAlign(Alignment, AteExtraComma))
return true;
if (!Ptr->getType()->isPointerTy())
return Error(PtrLoc, "store operand must be a pointer");
if (!Val->getType()->isFirstClassType())
return Error(Loc, "store operand must be a first class value");
if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
return Error(Loc, "stored value and pointer type do not match");
if (isAtomic && !Alignment)
return Error(Loc, "atomic store must have explicit non-zero alignment");
if (Ordering == Acquire || Ordering == AcquireRelease)
return Error(Loc, "atomic store cannot use Acquire ordering");
Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
return AteExtraComma ? InstExtraComma : InstNormal;
}
/// ParseCmpXchg
/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
bool AteExtraComma = false;
AtomicOrdering SuccessOrdering = NotAtomic;
AtomicOrdering FailureOrdering = NotAtomic;
SynchronizationScope Scope = CrossThread;
bool isVolatile = false;
bool isWeak = false;
if (EatIfPresent(lltok::kw_weak))
isWeak = true;
if (EatIfPresent(lltok::kw_volatile))
isVolatile = true;
if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
ParseTypeAndValue(New, NewLoc, PFS) ||
ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
ParseOrdering(FailureOrdering))
return true;
if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
return TokError("cmpxchg cannot be unordered");
if (SuccessOrdering < FailureOrdering)
return TokError("cmpxchg must be at least as ordered on success as failure");
if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
return TokError("cmpxchg failure ordering cannot include release semantics");
if (!Ptr->getType()->isPointerTy())
return Error(PtrLoc, "cmpxchg operand must be a pointer");
if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
return Error(CmpLoc, "compare value and pointer type do not match");
if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
return Error(NewLoc, "new value and pointer type do not match");
if (!New->getType()->isIntegerTy())
return Error(NewLoc, "cmpxchg operand must be an integer");
unsigned Size = New->getType()->getPrimitiveSizeInBits();
if (Size < 8 || (Size & (Size - 1)))
return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
" integer");
AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
CXI->setVolatile(isVolatile);
CXI->setWeak(isWeak);
Inst = CXI;
return AteExtraComma ? InstExtraComma : InstNormal;
}
/// ParseAtomicRMW
/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
/// 'singlethread'? AtomicOrdering
int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
bool AteExtraComma = false;
AtomicOrdering Ordering = NotAtomic;
SynchronizationScope Scope = CrossThread;
bool isVolatile = false;
AtomicRMWInst::BinOp Operation;
if (EatIfPresent(lltok::kw_volatile))
isVolatile = true;
switch (Lex.getKind()) {
default: return TokError("expected binary operation in atomicrmw");
case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
case lltok::kw_and: Operation = AtomicRMWInst::And; break;
case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
}
Lex.Lex(); // Eat the operation.
if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
ParseTypeAndValue(Val, ValLoc, PFS) ||
ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
return true;
if (Ordering == Unordered)
return TokError("atomicrmw cannot be unordered");
if (!Ptr->getType()->isPointerTy())
return Error(PtrLoc, "atomicrmw operand must be a pointer");
if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
return Error(ValLoc, "atomicrmw value and pointer type do not match");
if (!Val->getType()->isIntegerTy())
return Error(ValLoc, "atomicrmw operand must be an integer");
unsigned Size = Val->getType()->getPrimitiveSizeInBits();
if (Size < 8 || (Size & (Size - 1)))
return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
" integer");
AtomicRMWInst *RMWI =
new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
RMWI->setVolatile(isVolatile);
Inst = RMWI;
return AteExtraComma ? InstExtraComma : InstNormal;
}
/// ParseFence
/// ::= 'fence' 'singlethread'? AtomicOrdering
int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
AtomicOrdering Ordering = NotAtomic;
SynchronizationScope Scope = CrossThread;
if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
return true;
if (Ordering == Unordered)
return TokError("fence cannot be unordered");
if (Ordering == Monotonic)
return TokError("fence cannot be monotonic");
Inst = new FenceInst(Context, Ordering, Scope);
return InstNormal;
}
/// ParseGetElementPtr
/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Value *Ptr = nullptr;
Value *Val = nullptr;
LocTy Loc, EltLoc;
bool InBounds = EatIfPresent(lltok::kw_inbounds);
Type *Ty = nullptr;
LocTy ExplicitTypeLoc = Lex.getLoc();
if (ParseType(Ty) ||
ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
ParseTypeAndValue(Ptr, Loc, PFS))
return true;
Type *BaseType = Ptr->getType();
PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
if (!BasePointerType)
return Error(Loc, "base of getelementptr must be a pointer");
if (Ty != BasePointerType->getElementType())
return Error(ExplicitTypeLoc,
"explicit pointee type doesn't match operand's pointee type");
SmallVector<Value*, 16> Indices;
bool AteExtraComma = false;
// GEP returns a vector of pointers if at least one of parameters is a vector.
// All vector parameters should have the same vector width.
unsigned GEPWidth = BaseType->isVectorTy() ?
BaseType->getVectorNumElements() : 0;
while (EatIfPresent(lltok::comma)) {
if (Lex.getKind() == lltok::MetadataVar) {
AteExtraComma = true;
break;
}
if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
if (!Val->getType()->getScalarType()->isIntegerTy())
return Error(EltLoc, "getelementptr index must be an integer");
if (Val->getType()->isVectorTy()) {
unsigned ValNumEl = Val->getType()->getVectorNumElements();
if (GEPWidth && GEPWidth != ValNumEl)
return Error(EltLoc,
"getelementptr vector index has a wrong number of elements");
GEPWidth = ValNumEl;
}
Indices.push_back(Val);
}
SmallPtrSet<const Type*, 4> Visited;
if (!Indices.empty() && !Ty->isSized(&Visited))
return Error(Loc, "base element of getelementptr must be sized");
if (!GetElementPtrInst::getIndexedType(Ty, Indices))
return Error(Loc, "invalid getelementptr indices");
Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
if (InBounds)
cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
return AteExtraComma ? InstExtraComma : InstNormal;
}
/// ParseExtractValue
/// ::= 'extractvalue' TypeAndValue (',' uint32)+
int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Value *Val; LocTy Loc;
SmallVector<unsigned, 4> Indices;
bool AteExtraComma;
if (ParseTypeAndValue(Val, Loc, PFS) ||
ParseIndexList(Indices, AteExtraComma))
return true;
if (!Val->getType()->isAggregateType())
return Error(Loc, "extractvalue operand must be aggregate type");
if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
return Error(Loc, "invalid indices for extractvalue");
Inst = ExtractValueInst::Create(Val, Indices);
return AteExtraComma ? InstExtraComma : InstNormal;
}
/// ParseInsertValue
/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Value *Val0, *Val1; LocTy Loc0, Loc1;
SmallVector<unsigned, 4> Indices;
bool AteExtraComma;
if (ParseTypeAndValue(Val0, Loc0, PFS) ||
ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
ParseTypeAndValue(Val1, Loc1, PFS) ||
ParseIndexList(Indices, AteExtraComma))
return true;
if (!Val0->getType()->isAggregateType())
return Error(Loc0, "insertvalue operand must be aggregate type");
Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
if (!IndexedType)
return Error(Loc0, "invalid indices for insertvalue");
if (IndexedType != Val1->getType())
return Error(Loc1, "insertvalue operand and field disagree in type: '" +
getTypeString(Val1->getType()) + "' instead of '" +
getTypeString(IndexedType) + "'");
Inst = InsertValueInst::Create(Val0, Val1, Indices);
return AteExtraComma ? InstExtraComma : InstNormal;
}
//===----------------------------------------------------------------------===//
// Embedded metadata.
//===----------------------------------------------------------------------===//
/// ParseMDNodeVector
/// ::= { Element (',' Element)* }
/// Element
/// ::= 'null' | TypeAndValue
bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
if (ParseToken(lltok::lbrace, "expected '{' here"))
return true;
// Check for an empty list.
if (EatIfPresent(lltok::rbrace))
return false;
do {
// Null is a special case since it is typeless.
if (EatIfPresent(lltok::kw_null)) {
Elts.push_back(nullptr);
continue;
}
Metadata *MD;
if (ParseMetadata(MD, nullptr))
return true;
Elts.push_back(MD);
} while (EatIfPresent(lltok::comma));
return ParseToken(lltok::rbrace, "expected end of metadata node");
}
//===----------------------------------------------------------------------===//
// Use-list order directives.
//===----------------------------------------------------------------------===//
bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
SMLoc Loc) {
if (V->use_empty())
return Error(Loc, "value has no uses");
unsigned NumUses = 0;
SmallDenseMap<const Use *, unsigned, 16> Order;
for (const Use &U : V->uses()) {
if (++NumUses > Indexes.size())
break;
Order[&U] = Indexes[NumUses - 1];
}
if (NumUses < 2)
return Error(Loc, "value only has one use");
if (Order.size() != Indexes.size() || NumUses > Indexes.size())
return Error(Loc, "wrong number of indexes, expected " +
Twine(std::distance(V->use_begin(), V->use_end())));
V->sortUseList([&](const Use &L, const Use &R) {
return Order.lookup(&L) < Order.lookup(&R);
});
return false;
}
/// ParseUseListOrderIndexes
/// ::= '{' uint32 (',' uint32)+ '}'
bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
SMLoc Loc = Lex.getLoc();
if (ParseToken(lltok::lbrace, "expected '{' here"))
return true;
if (Lex.getKind() == lltok::rbrace)
return Lex.Error("expected non-empty list of uselistorder indexes");
// Use Offset, Max, and IsOrdered to check consistency of indexes. The
// indexes should be distinct numbers in the range [0, size-1], and should
// not be in order.
unsigned Offset = 0;
unsigned Max = 0;
bool IsOrdered = true;
assert(Indexes.empty() && "Expected empty order vector");
do {
unsigned Index;
if (ParseUInt32(Index))
return true;
// Update consistency checks.
Offset += Index - Indexes.size();
Max = std::max(Max, Index);
IsOrdered &= Index == Indexes.size();
Indexes.push_back(Index);
} while (EatIfPresent(lltok::comma));
if (ParseToken(lltok::rbrace, "expected '}' here"))
return true;
if (Indexes.size() < 2)
return Error(Loc, "expected >= 2 uselistorder indexes");
if (Offset != 0 || Max >= Indexes.size())
return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
if (IsOrdered)
return Error(Loc, "expected uselistorder indexes to change the order");
return false;
}
/// ParseUseListOrder
/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
SMLoc Loc = Lex.getLoc();
if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
return true;
Value *V;
SmallVector<unsigned, 16> Indexes;
if (ParseTypeAndValue(V, PFS) ||
ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
ParseUseListOrderIndexes(Indexes))
return true;
return sortUseListOrder(V, Indexes, Loc);
}
/// ParseUseListOrderBB
/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
bool LLParser::ParseUseListOrderBB() {
assert(Lex.getKind() == lltok::kw_uselistorder_bb);
SMLoc Loc = Lex.getLoc();
Lex.Lex();
ValID Fn, Label;
SmallVector<unsigned, 16> Indexes;
if (ParseValID(Fn) ||
ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
ParseValID(Label) ||
ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
ParseUseListOrderIndexes(Indexes))
return true;
// Check the function.
GlobalValue *GV;
if (Fn.Kind == ValID::t_GlobalName)
GV = M->getNamedValue(Fn.StrVal);
else if (Fn.Kind == ValID::t_GlobalID)
GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
else
return Error(Fn.Loc, "expected function name in uselistorder_bb");
if (!GV)
return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
auto *F = dyn_cast<Function>(GV);
if (!F)
return Error(Fn.Loc, "expected function name in uselistorder_bb");
if (F->isDeclaration())
return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
// Check the basic block.
if (Label.Kind == ValID::t_LocalID)
return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
if (Label.Kind != ValID::t_LocalName)
return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
if (!V)
return Error(Label.Loc, "invalid basic block in uselistorder_bb");
if (!isa<BasicBlock>(V))
return Error(Label.Loc, "expected basic block in uselistorder_bb");
return sortUseListOrder(V, Indexes, Loc);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/AsmParser/LLVMBuild.txt | ;===- ./lib/AsmParser/LLVMBuild.txt ----------------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Library
name = AsmParser
parent = Libraries
required_libraries = Core Support
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/AsmParser/module.modulemap | module AsmParser { requires cplusplus umbrella "." module * { export * } }
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/AsmParser/LLParser.h | //===-- LLParser.h - Parser Class -------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the parser class for .ll files.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_ASMPARSER_LLPARSER_H
#define LLVM_LIB_ASMPARSER_LLPARSER_H
#include "LLLexer.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/ValueHandle.h"
#include <map>
namespace llvm {
class Module;
class OpaqueType;
class Function;
class Value;
class BasicBlock;
class Instruction;
class Constant;
class GlobalValue;
class Comdat;
class MDString;
class MDNode;
struct SlotMapping;
class StructType;
/// ValID - Represents a reference of a definition of some sort with no type.
/// There are several cases where we have to parse the value but where the
/// type can depend on later context. This may either be a numeric reference
/// or a symbolic (%var) reference. This is just a discriminated union.
struct ValID {
enum {
t_LocalID, t_GlobalID, // ID in UIntVal.
t_LocalName, t_GlobalName, // Name in StrVal.
t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
t_Null, t_Undef, t_Zero, // No value.
t_EmptyArray, // No value: []
t_Constant, // Value in ConstantVal.
t_InlineAsm, // Value in StrVal/StrVal2/UIntVal.
t_ConstantStruct, // Value in ConstantStructElts.
t_PackedConstantStruct // Value in ConstantStructElts.
} Kind;
LLLexer::LocTy Loc;
unsigned UIntVal;
std::string StrVal, StrVal2;
APSInt APSIntVal;
APFloat APFloatVal;
Constant *ConstantVal;
Constant **ConstantStructElts;
ValID() : Kind(t_LocalID), APFloatVal(0.0) {}
~ValID() {
if (Kind == t_ConstantStruct || Kind == t_PackedConstantStruct)
delete [] ConstantStructElts;
}
bool operator<(const ValID &RHS) const {
if (Kind == t_LocalID || Kind == t_GlobalID)
return UIntVal < RHS.UIntVal;
assert((Kind == t_LocalName || Kind == t_GlobalName ||
Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) &&
"Ordering not defined for this ValID kind yet");
return StrVal < RHS.StrVal;
}
};
class LLParser {
public:
typedef LLLexer::LocTy LocTy;
private:
LLVMContext &Context;
LLLexer Lex;
Module *M;
SlotMapping *Slots;
// Instruction metadata resolution. Each instruction can have a list of
// MDRef info associated with them.
//
// The simpler approach of just creating temporary MDNodes and then calling
// RAUW on them when the definition is processed doesn't work because some
// instruction metadata kinds, such as dbg, get stored in the IR in an
// "optimized" format which doesn't participate in the normal value use
// lists. This means that RAUW doesn't work, even on temporary MDNodes
// which otherwise support RAUW. Instead, we defer resolving MDNode
// references until the definitions have been processed.
struct MDRef {
SMLoc Loc;
unsigned MDKind, MDSlot;
};
SmallVector<Instruction*, 64> InstsWithTBAATag;
// Type resolution handling data structures. The location is set when we
// have processed a use of the type but not a definition yet.
StringMap<std::pair<Type*, LocTy> > NamedTypes;
std::map<unsigned, std::pair<Type*, LocTy> > NumberedTypes;
std::map<unsigned, TrackingMDNodeRef> NumberedMetadata;
std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
// Global Value reference information.
std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
std::vector<GlobalValue*> NumberedVals;
// Comdat forward reference information.
std::map<std::string, LocTy> ForwardRefComdats;
// References to blockaddress. The key is the function ValID, the value is
// a list of references to blocks in that function.
std::map<ValID, std::map<ValID, GlobalValue *>> ForwardRefBlockAddresses;
class PerFunctionState;
/// Reference to per-function state to allow basic blocks to be
/// forward-referenced by blockaddress instructions within the same
/// function.
PerFunctionState *BlockAddressPFS;
// Attribute builder reference information.
std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
public:
LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *M,
SlotMapping *Slots = nullptr)
: Context(M->getContext()), Lex(F, SM, Err, M->getContext()), M(M),
Slots(Slots), BlockAddressPFS(nullptr) {}
bool Run();
LLVMContext &getContext() { return Context; }
private:
bool Error(LocTy L, const Twine &Msg) const {
return Lex.Error(L, Msg);
}
bool TokError(const Twine &Msg) const {
return Error(Lex.getLoc(), Msg);
}
/// GetGlobalVal - Get a value with the specified name or ID, creating a
/// forward reference record if needed. This can return null if the value
/// exists but does not have the right type.
GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
/// Get a Comdat with the specified name, creating a forward reference
/// record if needed.
Comdat *getComdat(const std::string &N, LocTy Loc);
// Helper Routines.
bool ParseToken(lltok::Kind T, const char *ErrMsg);
bool EatIfPresent(lltok::Kind T) {
if (Lex.getKind() != T) return false;
Lex.Lex();
return true;
}
FastMathFlags EatFastMathFlagsIfPresent() {
FastMathFlags FMF;
while (true)
switch (Lex.getKind()) {
case lltok::kw_fast: FMF.setUnsafeAlgebra(); Lex.Lex(); continue;
case lltok::kw_nnan: FMF.setNoNaNs(); Lex.Lex(); continue;
case lltok::kw_ninf: FMF.setNoInfs(); Lex.Lex(); continue;
case lltok::kw_nsz: FMF.setNoSignedZeros(); Lex.Lex(); continue;
case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
default: return FMF;
}
return FMF;
}
bool ParseOptionalToken(lltok::Kind T, bool &Present,
LocTy *Loc = nullptr) {
if (Lex.getKind() != T) {
Present = false;
} else {
if (Loc)
*Loc = Lex.getLoc();
Lex.Lex();
Present = true;
}
return false;
}
bool ParseStringConstant(std::string &Result);
bool ParseUInt32(unsigned &Val);
bool ParseUInt32(unsigned &Val, LocTy &Loc) {
Loc = Lex.getLoc();
return ParseUInt32(Val);
}
bool ParseUInt64(uint64_t &Val);
bool ParseUInt64(uint64_t &Val, LocTy &Loc) {
Loc = Lex.getLoc();
return ParseUInt64(Val);
}
bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
bool parseOptionalUnnamedAddr(bool &UnnamedAddr) {
return ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr);
}
bool ParseOptionalAddrSpace(unsigned &AddrSpace);
bool ParseOptionalParamAttrs(AttrBuilder &B);
bool ParseOptionalReturnAttrs(AttrBuilder &B);
bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
bool ParseOptionalLinkage(unsigned &Linkage) {
bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
}
bool ParseOptionalVisibility(unsigned &Visibility);
bool ParseOptionalDLLStorageClass(unsigned &DLLStorageClass);
bool ParseOptionalCallingConv(unsigned &CC);
bool ParseOptionalAlignment(unsigned &Alignment);
bool ParseOptionalDerefAttrBytes(lltok::Kind AttrKind, uint64_t &Bytes);
bool ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
AtomicOrdering &Ordering);
bool ParseOrdering(AtomicOrdering &Ordering);
bool ParseOptionalStackAlignment(unsigned &Alignment);
bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
bool ParseOptionalCommaInAlloca(bool &IsInAlloca);
bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,bool &AteExtraComma);
bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
bool AteExtraComma;
if (ParseIndexList(Indices, AteExtraComma)) return true;
if (AteExtraComma)
return TokError("expected index");
return false;
}
// Top-Level Entities
bool ParseTopLevelEntities();
bool ValidateEndOfModule();
bool ParseTargetDefinition();
bool ParseModuleAsm();
bool ParseDepLibs(); // FIXME: Remove in 4.0.
bool ParseUnnamedType();
bool ParseNamedType();
bool ParseDeclare();
bool ParseDefine();
bool ParseGlobalType(bool &IsConstant);
bool ParseUnnamedGlobal();
bool ParseNamedGlobal();
bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
bool HasLinkage, unsigned Visibility,
unsigned DLLStorageClass,
GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Linkage,
unsigned Visibility, unsigned DLLStorageClass,
GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
bool parseComdat();
bool ParseStandaloneMetadata();
bool ParseNamedMetadata();
bool ParseMDString(MDString *&Result);
bool ParseMDNodeID(MDNode *&Result);
bool ParseUnnamedAttrGrp();
bool ParseFnAttributeValuePairs(AttrBuilder &B,
std::vector<unsigned> &FwdRefAttrGrps,
bool inAttrGrp, LocTy &BuiltinLoc);
// Type Parsing.
bool ParseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
bool ParseType(Type *&Result, bool AllowVoid = false) {
return ParseType(Result, "expected type", AllowVoid);
}
bool ParseType(Type *&Result, const Twine &Msg, LocTy &Loc,
bool AllowVoid = false) {
Loc = Lex.getLoc();
return ParseType(Result, Msg, AllowVoid);
}
bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
Loc = Lex.getLoc();
return ParseType(Result, AllowVoid);
}
bool ParseAnonStructType(Type *&Result, bool Packed);
bool ParseStructBody(SmallVectorImpl<Type*> &Body);
bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
std::pair<Type*, LocTy> &Entry,
Type *&ResultTy);
bool ParseArrayVectorType(Type *&Result, bool isVector);
bool ParseFunctionType(Type *&Result);
// Function Semantic Analysis.
class PerFunctionState {
LLParser &P;
Function &F;
std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
std::vector<Value*> NumberedVals;
/// FunctionNumber - If this is an unnamed function, this is the slot
/// number of it, otherwise it is -1.
int FunctionNumber;
public:
PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
~PerFunctionState();
Function &getFunction() const { return F; }
bool FinishFunction();
/// GetVal - Get a value with the specified name or ID, creating a
/// forward reference record if needed. This can return null if the value
/// exists but does not have the right type.
Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc);
Value *GetVal(unsigned ID, Type *Ty, LocTy Loc);
/// SetInstName - After an instruction is parsed and inserted into its
/// basic block, this installs its name.
bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
Instruction *Inst);
/// GetBB - Get a basic block with the specified name or ID, creating a
/// forward reference record if needed. This can return null if the value
/// is not a BasicBlock.
BasicBlock *GetBB(const std::string &Name, LocTy Loc);
BasicBlock *GetBB(unsigned ID, LocTy Loc);
/// DefineBB - Define the specified basic block, which is either named or
/// unnamed. If there is an error, this returns null otherwise it returns
/// the block being defined.
BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
bool resolveForwardRefBlockAddresses();
};
bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
PerFunctionState *PFS);
bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
return ParseValue(Ty, V, &PFS);
}
bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
PerFunctionState &PFS) {
Loc = Lex.getLoc();
return ParseValue(Ty, V, &PFS);
}
bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
return ParseTypeAndValue(V, &PFS);
}
bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
Loc = Lex.getLoc();
return ParseTypeAndValue(V, PFS);
}
bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
PerFunctionState &PFS);
bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
LocTy Loc;
return ParseTypeAndBasicBlock(BB, Loc, PFS);
}
struct ParamInfo {
LocTy Loc;
Value *V;
AttributeSet Attrs;
ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
: Loc(loc), V(v), Attrs(attrs) {}
};
bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
PerFunctionState &PFS,
bool IsMustTailCall = false,
bool InVarArgsFunc = false);
// Constant Parsing.
bool ParseValID(ValID &ID, PerFunctionState *PFS = nullptr);
bool ParseGlobalValue(Type *Ty, Constant *&V);
bool ParseGlobalTypeAndValue(Constant *&V);
bool ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts);
bool parseOptionalComdat(StringRef GlobalName, Comdat *&C);
bool ParseMetadataAsValue(Value *&V, PerFunctionState &PFS);
bool ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
PerFunctionState *PFS);
bool ParseMetadata(Metadata *&MD, PerFunctionState *PFS);
bool ParseMDTuple(MDNode *&MD, bool IsDistinct = false);
bool ParseMDNode(MDNode *&MD);
bool ParseMDNodeTail(MDNode *&MD);
bool ParseMDNodeVector(SmallVectorImpl<Metadata *> &MDs);
bool ParseMetadataAttachment(unsigned &Kind, MDNode *&MD);
bool ParseInstructionMetadata(Instruction &Inst);
bool ParseOptionalFunctionMetadata(Function &F);
template <class FieldTy>
bool ParseMDField(LocTy Loc, StringRef Name, FieldTy &Result);
template <class FieldTy> bool ParseMDField(StringRef Name, FieldTy &Result);
template <class ParserTy>
bool ParseMDFieldsImplBody(ParserTy parseField);
template <class ParserTy>
bool ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc);
bool ParseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
bool Parse##CLASS(MDNode *&Result, bool IsDistinct);
#include "llvm/IR/Metadata.def"
// Function Parsing.
struct ArgInfo {
LocTy Loc;
Type *Ty;
AttributeSet Attrs;
std::string Name;
ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
: Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
};
bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
bool ParseFunctionHeader(Function *&Fn, bool isDefine);
bool ParseFunctionBody(Function &Fn);
bool ParseBasicBlock(PerFunctionState &PFS);
enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
// Instruction Parsing. Each instruction parsing routine can return with a
// normal result, an error result, or return having eaten an extra comma.
enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
PerFunctionState &PFS);
bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
bool ParseArithmetic(Instruction *&I, PerFunctionState &PFS, unsigned Opc,
unsigned OperandType);
bool ParseLogical(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
bool ParseCompare(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
bool ParseCast(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
bool ParseSelect(Instruction *&I, PerFunctionState &PFS);
bool ParseVA_Arg(Instruction *&I, PerFunctionState &PFS);
bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS);
bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS);
bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS);
int ParsePHI(Instruction *&I, PerFunctionState &PFS);
bool ParseLandingPad(Instruction *&I, PerFunctionState &PFS);
bool ParseCall(Instruction *&I, PerFunctionState &PFS,
CallInst::TailCallKind IsTail);
int ParseAlloc(Instruction *&I, PerFunctionState &PFS);
int ParseLoad(Instruction *&I, PerFunctionState &PFS);
int ParseStore(Instruction *&I, PerFunctionState &PFS);
int ParseCmpXchg(Instruction *&I, PerFunctionState &PFS);
int ParseAtomicRMW(Instruction *&I, PerFunctionState &PFS);
int ParseFence(Instruction *&I, PerFunctionState &PFS);
int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS);
int ParseExtractValue(Instruction *&I, PerFunctionState &PFS);
int ParseInsertValue(Instruction *&I, PerFunctionState &PFS);
// Use-list order directives.
bool ParseUseListOrder(PerFunctionState *PFS = nullptr);
bool ParseUseListOrderBB();
bool ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
};
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/AsmParser/Parser.cpp | //===- Parser.cpp - Main dispatch module for the Parser library -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This library implements the functionality defined in llvm/AsmParser/Parser.h
//
//===----------------------------------------------------------------------===//
#include "llvm/AsmParser/Parser.h"
#include "LLParser.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include <cstring>
#include <system_error>
using namespace llvm;
bool llvm::parseAssemblyInto(MemoryBufferRef F, Module &M, SMDiagnostic &Err,
SlotMapping *Slots) {
SourceMgr SM;
std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(F);
SM.AddNewSourceBuffer(std::move(Buf), SMLoc());
return LLParser(F.getBuffer(), SM, Err, &M, Slots).Run();
}
std::unique_ptr<Module> llvm::parseAssembly(MemoryBufferRef F,
SMDiagnostic &Err,
LLVMContext &Context,
SlotMapping *Slots) {
std::unique_ptr<Module> M =
make_unique<Module>(F.getBufferIdentifier(), Context);
if (parseAssemblyInto(F, *M, Err, Slots))
return nullptr;
return M;
}
std::unique_ptr<Module> llvm::parseAssemblyFile(StringRef Filename,
SMDiagnostic &Err,
LLVMContext &Context,
SlotMapping *Slots) {
ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
MemoryBuffer::getFileOrSTDIN(Filename);
if (std::error_code EC = FileOrErr.getError()) {
Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
"Could not open input file: " + EC.message());
return nullptr;
}
return parseAssembly(FileOrErr.get()->getMemBufferRef(), Err, Context, Slots);
}
std::unique_ptr<Module> llvm::parseAssemblyString(StringRef AsmString,
SMDiagnostic &Err,
LLVMContext &Context,
SlotMapping *Slots) {
MemoryBufferRef F(AsmString, "<string>");
return parseAssembly(F, Err, Context, Slots);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/AsmParser/LLLexer.h | //===- LLLexer.h - Lexer for LLVM Assembly Files ----------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class represents the Lexer for .ll files.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_ASMPARSER_LLLEXER_H
#define LLVM_LIB_ASMPARSER_LLLEXER_H
#include "LLToken.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/Support/SourceMgr.h"
#include <string>
namespace llvm {
class MemoryBuffer;
class Type;
class SMDiagnostic;
class LLVMContext;
class LLLexer {
const char *CurPtr;
StringRef CurBuf;
SMDiagnostic &ErrorInfo;
SourceMgr &SM;
LLVMContext &Context;
// Information about the current token.
const char *TokStart;
lltok::Kind CurKind;
std::string StrVal;
unsigned UIntVal;
Type *TyVal;
APFloat APFloatVal;
APSInt APSIntVal;
public:
explicit LLLexer(StringRef StartBuf, SourceMgr &SM, SMDiagnostic &,
LLVMContext &C);
lltok::Kind Lex() {
return CurKind = LexToken();
}
typedef SMLoc LocTy;
LocTy getLoc() const { return SMLoc::getFromPointer(TokStart); }
lltok::Kind getKind() const { return CurKind; }
const std::string &getStrVal() const { return StrVal; }
Type *getTyVal() const { return TyVal; }
unsigned getUIntVal() const { return UIntVal; }
const APSInt &getAPSIntVal() const { return APSIntVal; }
const APFloat &getAPFloatVal() const { return APFloatVal; }
bool Error(LocTy L, const Twine &Msg) const;
bool Error(const Twine &Msg) const { return Error(getLoc(), Msg); }
void Warning(LocTy WarningLoc, const Twine &Msg) const;
void Warning(const Twine &Msg) const { return Warning(getLoc(), Msg); }
private:
lltok::Kind LexToken();
int getNextChar();
void SkipLineComment();
lltok::Kind ReadString(lltok::Kind kind);
bool ReadVarName();
lltok::Kind LexIdentifier();
lltok::Kind LexDigitOrNegative();
lltok::Kind LexPositive();
lltok::Kind LexAt();
lltok::Kind LexDollar();
lltok::Kind LexExclaim();
lltok::Kind LexPercent();
lltok::Kind LexVar(lltok::Kind Var, lltok::Kind VarID);
lltok::Kind LexQuote();
lltok::Kind Lex0x();
lltok::Kind LexHash();
uint64_t atoull(const char *Buffer, const char *End);
uint64_t HexIntToVal(const char *Buffer, const char *End);
void HexToIntPair(const char *Buffer, const char *End, uint64_t Pair[2]);
void FP80HexToIntPair(const char *Buff, const char *End, uint64_t Pair[2]);
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/Transforms/CMakeLists.txt | add_subdirectory(Utils)
# add_subdirectory(Instrumentation) # HLSL Change
add_subdirectory(InstCombine)
add_subdirectory(Scalar)
add_subdirectory(IPO)
add_subdirectory(Vectorize)
# add_subdirectory(Hello) # HLSL Change
# add_subdirectory(ObjCARC) # HLSL Change
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/Transforms/LLVMBuild.txt | ;===- ./lib/Transforms/LLVMBuild.txt ---------------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[common]
subdirectories = IPO InstCombine Instrumentation Scalar Utils Vectorize ObjCARC
[component_0]
type = Group
name = Transforms
parent = Libraries
|
0 | repos/DirectXShaderCompiler/lib/Transforms | repos/DirectXShaderCompiler/lib/Transforms/ObjCARC/ObjCARC.h | //===- ObjCARC.h - ObjC ARC Optimization --------------*- C++ -*-----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file defines common definitions/declarations used by the ObjC ARC
/// Optimizer. ARC stands for Automatic Reference Counting and is a system for
/// managing reference counts for objects in Objective C.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TRANSFORMS_OBJCARC_OBJCARC_H
#define LLVM_LIB_TRANSFORMS_OBJCARC_OBJCARC_H
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Optional.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/ObjCARC.h"
#include "llvm/Transforms/Utils/Local.h"
#include "ARCInstKind.h"
namespace llvm {
class raw_ostream;
}
namespace llvm {
namespace objcarc {
/// \brief A handy option to enable/disable all ARC Optimizations.
extern bool EnableARCOpts;
/// \brief Test if the given module looks interesting to run ARC optimization
/// on.
static inline bool ModuleHasARC(const Module &M) {
return
M.getNamedValue("objc_retain") ||
M.getNamedValue("objc_release") ||
M.getNamedValue("objc_autorelease") ||
M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
M.getNamedValue("objc_retainBlock") ||
M.getNamedValue("objc_autoreleaseReturnValue") ||
M.getNamedValue("objc_autoreleasePoolPush") ||
M.getNamedValue("objc_loadWeakRetained") ||
M.getNamedValue("objc_loadWeak") ||
M.getNamedValue("objc_destroyWeak") ||
M.getNamedValue("objc_storeWeak") ||
M.getNamedValue("objc_initWeak") ||
M.getNamedValue("objc_moveWeak") ||
M.getNamedValue("objc_copyWeak") ||
M.getNamedValue("objc_retainedObject") ||
M.getNamedValue("objc_unretainedObject") ||
M.getNamedValue("objc_unretainedPointer") ||
M.getNamedValue("clang.arc.use");
}
/// \brief This is a wrapper around getUnderlyingObject which also knows how to
/// look through objc_retain and objc_autorelease calls, which we know to return
/// their argument verbatim.
static inline const Value *GetUnderlyingObjCPtr(const Value *V,
const DataLayout &DL) {
for (;;) {
V = GetUnderlyingObject(V, DL);
if (!IsForwarding(GetBasicARCInstKind(V)))
break;
V = cast<CallInst>(V)->getArgOperand(0);
}
return V;
}
/// The RCIdentity root of a value \p V is a dominating value U for which
/// retaining or releasing U is equivalent to retaining or releasing V. In other
/// words, ARC operations on \p V are equivalent to ARC operations on \p U.
///
/// We use this in the ARC optimizer to make it easier to match up ARC
/// operations by always mapping ARC operations to RCIdentityRoots instead of
/// pointers themselves.
///
/// The two ways that we see RCIdentical values in ObjC are via:
///
/// 1. PointerCasts
/// 2. Forwarding Calls that return their argument verbatim.
///
/// Thus this function strips off pointer casts and forwarding calls. *NOTE*
/// This implies that two RCIdentical values must alias.
static inline const Value *GetRCIdentityRoot(const Value *V) {
for (;;) {
V = V->stripPointerCasts();
if (!IsForwarding(GetBasicARCInstKind(V)))
break;
V = cast<CallInst>(V)->getArgOperand(0);
}
return V;
}
/// Helper which calls const Value *GetRCIdentityRoot(const Value *V) and just
/// casts away the const of the result. For documentation about what an
/// RCIdentityRoot (and by extension GetRCIdentityRoot is) look at that
/// function.
static inline Value *GetRCIdentityRoot(Value *V) {
return const_cast<Value *>(GetRCIdentityRoot((const Value *)V));
}
/// \brief Assuming the given instruction is one of the special calls such as
/// objc_retain or objc_release, return the RCIdentity root of the argument of
/// the call.
static inline Value *GetArgRCIdentityRoot(Value *Inst) {
return GetRCIdentityRoot(cast<CallInst>(Inst)->getArgOperand(0));
}
static inline bool IsNullOrUndef(const Value *V) {
return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
}
static inline bool IsNoopInstruction(const Instruction *I) {
return isa<BitCastInst>(I) ||
(isa<GetElementPtrInst>(I) &&
cast<GetElementPtrInst>(I)->hasAllZeroIndices());
}
/// \brief Erase the given instruction.
///
/// Many ObjC calls return their argument verbatim,
/// so if it's such a call and the return value has users, replace them with the
/// argument value.
///
static inline void EraseInstruction(Instruction *CI) {
Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
bool Unused = CI->use_empty();
if (!Unused) {
// Replace the return value with the argument.
assert((IsForwarding(GetBasicARCInstKind(CI)) ||
(IsNoopOnNull(GetBasicARCInstKind(CI)) &&
isa<ConstantPointerNull>(OldArg))) &&
"Can't delete non-forwarding instruction with users!");
CI->replaceAllUsesWith(OldArg);
}
CI->eraseFromParent();
if (Unused)
RecursivelyDeleteTriviallyDeadInstructions(OldArg);
}
/// \brief Test whether the given value is possible a retainable object pointer.
static inline bool IsPotentialRetainableObjPtr(const Value *Op) {
// Pointers to static or stack storage are not valid retainable object
// pointers.
if (isa<Constant>(Op) || isa<AllocaInst>(Op))
return false;
// Special arguments can not be a valid retainable object pointer.
if (const Argument *Arg = dyn_cast<Argument>(Op))
if (Arg->hasByValAttr() ||
Arg->hasInAllocaAttr() ||
Arg->hasNestAttr() ||
Arg->hasStructRetAttr())
return false;
// Only consider values with pointer types.
//
// It seemes intuitive to exclude function pointer types as well, since
// functions are never retainable object pointers, however clang occasionally
// bitcasts retainable object pointers to function-pointer type temporarily.
PointerType *Ty = dyn_cast<PointerType>(Op->getType());
if (!Ty)
return false;
// Conservatively assume anything else is a potential retainable object
// pointer.
return true;
}
static inline bool IsPotentialRetainableObjPtr(const Value *Op,
AliasAnalysis &AA) {
// First make the rudimentary check.
if (!IsPotentialRetainableObjPtr(Op))
return false;
// Objects in constant memory are not reference-counted.
if (AA.pointsToConstantMemory(Op))
return false;
// Pointers in constant memory are not pointing to reference-counted objects.
if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
if (AA.pointsToConstantMemory(LI->getPointerOperand()))
return false;
// Otherwise assume the worst.
return true;
}
/// \brief Helper for GetARCInstKind. Determines what kind of construct CS
/// is.
static inline ARCInstKind GetCallSiteClass(ImmutableCallSite CS) {
for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
I != E; ++I)
if (IsPotentialRetainableObjPtr(*I))
return CS.onlyReadsMemory() ? ARCInstKind::User : ARCInstKind::CallOrUser;
return CS.onlyReadsMemory() ? ARCInstKind::None : ARCInstKind::Call;
}
/// \brief Return true if this value refers to a distinct and identifiable
/// object.
///
/// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
/// special knowledge of ObjC conventions.
static inline bool IsObjCIdentifiedObject(const Value *V) {
// Assume that call results and arguments have their own "provenance".
// Constants (including GlobalVariables) and Allocas are never
// reference-counted.
if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
isa<Argument>(V) || isa<Constant>(V) ||
isa<AllocaInst>(V))
return true;
if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
const Value *Pointer =
GetRCIdentityRoot(LI->getPointerOperand());
if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
// A constant pointer can't be pointing to an object on the heap. It may
// be reference-counted, but it won't be deleted.
if (GV->isConstant())
return true;
StringRef Name = GV->getName();
// These special variables are known to hold values which are not
// reference-counted pointers.
if (Name.startswith("\01l_objc_msgSend_fixup_"))
return true;
StringRef Section = GV->getSection();
if (Section.find("__message_refs") != StringRef::npos ||
Section.find("__objc_classrefs") != StringRef::npos ||
Section.find("__objc_superrefs") != StringRef::npos ||
Section.find("__objc_methname") != StringRef::npos ||
Section.find("__cstring") != StringRef::npos)
return true;
}
}
return false;
}
enum class ARCMDKindID {
ImpreciseRelease,
CopyOnEscape,
NoObjCARCExceptions,
};
/// A cache of MDKinds used by various ARC optimizations.
class ARCMDKindCache {
Module *M;
/// The Metadata Kind for clang.imprecise_release metadata.
llvm::Optional<unsigned> ImpreciseReleaseMDKind;
/// The Metadata Kind for clang.arc.copy_on_escape metadata.
llvm::Optional<unsigned> CopyOnEscapeMDKind;
/// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
llvm::Optional<unsigned> NoObjCARCExceptionsMDKind;
public:
void init(Module *Mod) {
M = Mod;
ImpreciseReleaseMDKind = NoneType::None;
CopyOnEscapeMDKind = NoneType::None;
NoObjCARCExceptionsMDKind = NoneType::None;
}
unsigned get(ARCMDKindID ID) {
switch (ID) {
case ARCMDKindID::ImpreciseRelease:
if (!ImpreciseReleaseMDKind)
ImpreciseReleaseMDKind =
M->getContext().getMDKindID("clang.imprecise_release");
return *ImpreciseReleaseMDKind;
case ARCMDKindID::CopyOnEscape:
if (!CopyOnEscapeMDKind)
CopyOnEscapeMDKind =
M->getContext().getMDKindID("clang.arc.copy_on_escape");
return *CopyOnEscapeMDKind;
case ARCMDKindID::NoObjCARCExceptions:
if (!NoObjCARCExceptionsMDKind)
NoObjCARCExceptionsMDKind =
M->getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
return *NoObjCARCExceptionsMDKind;
}
llvm_unreachable("Covered switch isn't covered?!");
}
};
} // end namespace objcarc
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/lib/Transforms | repos/DirectXShaderCompiler/lib/Transforms/ObjCARC/ProvenanceAnalysisEvaluator.cpp | //===- ProvenanceAnalysisEvaluator.cpp - ObjC ARC Optimization ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ProvenanceAnalysis.h"
#include "llvm/Pass.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::objcarc;
namespace {
class PAEval : public FunctionPass {
public:
static char ID;
PAEval();
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnFunction(Function &F) override;
};
}
char PAEval::ID = 0;
PAEval::PAEval() : FunctionPass(ID) {}
void PAEval::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<AliasAnalysis>();
}
static StringRef getName(Value *V) {
StringRef Name = V->getName();
if (Name.startswith("\1"))
return Name.substr(1);
return Name;
}
static void insertIfNamed(SetVector<Value *> &Values, Value *V) {
if (!V->hasName())
return;
Values.insert(V);
}
bool PAEval::runOnFunction(Function &F) {
SetVector<Value *> Values;
for (auto &Arg : F.args())
insertIfNamed(Values, &Arg);
for (auto I = inst_begin(F), E = inst_end(F); I != E; ++I) {
insertIfNamed(Values, &*I);
for (auto &Op : I->operands())
insertIfNamed(Values, Op);
}
ProvenanceAnalysis PA;
PA.setAA(&getAnalysis<AliasAnalysis>());
const DataLayout &DL = F.getParent()->getDataLayout();
for (Value *V1 : Values) {
StringRef NameV1 = getName(V1);
for (Value *V2 : Values) {
StringRef NameV2 = getName(V2);
if (NameV1 >= NameV2)
continue;
errs() << NameV1 << " and " << NameV2;
if (PA.related(V1, V2, DL))
errs() << " are related.\n";
else
errs() << " are not related.\n";
}
}
return false;
}
FunctionPass *llvm::createPAEvalPass() { return new PAEval(); }
INITIALIZE_PASS_BEGIN(PAEval, "pa-eval",
"Evaluate ProvenanceAnalysis on all pairs", false, true)
INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
INITIALIZE_PASS_END(PAEval, "pa-eval",
"Evaluate ProvenanceAnalysis on all pairs", false, true)
|
0 | repos/DirectXShaderCompiler/lib/Transforms | repos/DirectXShaderCompiler/lib/Transforms/ObjCARC/ObjCARCOpts.cpp | //===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file defines ObjC ARC optimizations. ARC stands for Automatic
/// Reference Counting and is a system for managing reference counts for objects
/// in Objective C.
///
/// The optimizations performed include elimination of redundant, partially
/// redundant, and inconsequential reference count operations, elimination of
/// redundant weak pointer operations, and numerous minor simplifications.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
#include "ObjCARC.h"
#include "ARCRuntimeEntryPoints.h"
#include "BlotMapVector.h"
#include "DependencyAnalysis.h"
#include "ObjCARCAliasAnalysis.h"
#include "ProvenanceAnalysis.h"
#include "PtrState.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::objcarc;
#define DEBUG_TYPE "objc-arc-opts"
/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
/// @{
/// \brief This is similar to GetRCIdentityRoot but it stops as soon
/// as it finds a value with multiple uses.
static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
if (Arg->hasOneUse()) {
if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
return FindSingleUseIdentifiedObject(BC->getOperand(0));
if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
if (GEP->hasAllZeroIndices())
return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
if (IsForwarding(GetBasicARCInstKind(Arg)))
return FindSingleUseIdentifiedObject(
cast<CallInst>(Arg)->getArgOperand(0));
if (!IsObjCIdentifiedObject(Arg))
return nullptr;
return Arg;
}
// If we found an identifiable object but it has multiple uses, but they are
// trivial uses, we can still consider this to be a single-use value.
if (IsObjCIdentifiedObject(Arg)) {
for (const User *U : Arg->users())
if (!U->use_empty() || GetRCIdentityRoot(U) != Arg)
return nullptr;
return Arg;
}
return nullptr;
}
/// This is a wrapper around getUnderlyingObjCPtr along the lines of
/// GetUnderlyingObjects except that it returns early when it sees the first
/// alloca.
static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V,
const DataLayout &DL) {
SmallPtrSet<const Value *, 4> Visited;
SmallVector<const Value *, 4> Worklist;
Worklist.push_back(V);
do {
const Value *P = Worklist.pop_back_val();
P = GetUnderlyingObjCPtr(P, DL);
if (isa<AllocaInst>(P))
return true;
if (!Visited.insert(P).second)
continue;
if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
Worklist.push_back(SI->getTrueValue());
Worklist.push_back(SI->getFalseValue());
continue;
}
if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
for (Value *IncValue : PN->incoming_values())
Worklist.push_back(IncValue);
continue;
}
} while (!Worklist.empty());
return false;
}
/// @}
///
/// \defgroup ARCOpt ARC Optimization.
/// @{
// TODO: On code like this:
//
// objc_retain(%x)
// stuff_that_cannot_release()
// objc_autorelease(%x)
// stuff_that_cannot_release()
// objc_retain(%x)
// stuff_that_cannot_release()
// objc_autorelease(%x)
//
// The second retain and autorelease can be deleted.
// TODO: It should be possible to delete
// objc_autoreleasePoolPush and objc_autoreleasePoolPop
// pairs if nothing is actually autoreleased between them. Also, autorelease
// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
// after inlining) can be turned into plain release calls.
// TODO: Critical-edge splitting. If the optimial insertion point is
// a critical edge, the current algorithm has to fail, because it doesn't
// know how to split edges. It should be possible to make the optimizer
// think in terms of edges, rather than blocks, and then split critical
// edges on demand.
// TODO: OptimizeSequences could generalized to be Interprocedural.
// TODO: Recognize that a bunch of other objc runtime calls have
// non-escaping arguments and non-releasing arguments, and may be
// non-autoreleasing.
// TODO: Sink autorelease calls as far as possible. Unfortunately we
// usually can't sink them past other calls, which would be the main
// case where it would be useful.
// TODO: The pointer returned from objc_loadWeakRetained is retained.
// TODO: Delete release+retain pairs (rare).
STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
STATISTIC(NumRets, "Number of return value forwarding "
"retain+autoreleases eliminated");
STATISTIC(NumRRs, "Number of retain+release paths eliminated");
STATISTIC(NumPeeps, "Number of calls peephole-optimized");
#ifndef NDEBUG
STATISTIC(NumRetainsBeforeOpt,
"Number of retains before optimization");
STATISTIC(NumReleasesBeforeOpt,
"Number of releases before optimization");
STATISTIC(NumRetainsAfterOpt,
"Number of retains after optimization");
STATISTIC(NumReleasesAfterOpt,
"Number of releases after optimization");
#endif
namespace {
/// \brief Per-BasicBlock state.
class BBState {
/// The number of unique control paths from the entry which can reach this
/// block.
unsigned TopDownPathCount;
/// The number of unique control paths to exits from this block.
unsigned BottomUpPathCount;
/// The top-down traversal uses this to record information known about a
/// pointer at the bottom of each block.
BlotMapVector<const Value *, TopDownPtrState> PerPtrTopDown;
/// The bottom-up traversal uses this to record information known about a
/// pointer at the top of each block.
BlotMapVector<const Value *, BottomUpPtrState> PerPtrBottomUp;
/// Effective predecessors of the current block ignoring ignorable edges and
/// ignored backedges.
SmallVector<BasicBlock *, 2> Preds;
/// Effective successors of the current block ignoring ignorable edges and
/// ignored backedges.
SmallVector<BasicBlock *, 2> Succs;
public:
static const unsigned OverflowOccurredValue;
BBState() : TopDownPathCount(0), BottomUpPathCount(0) { }
typedef decltype(PerPtrTopDown)::iterator top_down_ptr_iterator;
typedef decltype(PerPtrTopDown)::const_iterator const_top_down_ptr_iterator;
top_down_ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
top_down_ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
const_top_down_ptr_iterator top_down_ptr_begin() const {
return PerPtrTopDown.begin();
}
const_top_down_ptr_iterator top_down_ptr_end() const {
return PerPtrTopDown.end();
}
bool hasTopDownPtrs() const {
return !PerPtrTopDown.empty();
}
typedef decltype(PerPtrBottomUp)::iterator bottom_up_ptr_iterator;
typedef decltype(
PerPtrBottomUp)::const_iterator const_bottom_up_ptr_iterator;
bottom_up_ptr_iterator bottom_up_ptr_begin() {
return PerPtrBottomUp.begin();
}
bottom_up_ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
const_bottom_up_ptr_iterator bottom_up_ptr_begin() const {
return PerPtrBottomUp.begin();
}
const_bottom_up_ptr_iterator bottom_up_ptr_end() const {
return PerPtrBottomUp.end();
}
bool hasBottomUpPtrs() const {
return !PerPtrBottomUp.empty();
}
/// Mark this block as being an entry block, which has one path from the
/// entry by definition.
void SetAsEntry() { TopDownPathCount = 1; }
/// Mark this block as being an exit block, which has one path to an exit by
/// definition.
void SetAsExit() { BottomUpPathCount = 1; }
/// Attempt to find the PtrState object describing the top down state for
/// pointer Arg. Return a new initialized PtrState describing the top down
/// state for Arg if we do not find one.
TopDownPtrState &getPtrTopDownState(const Value *Arg) {
return PerPtrTopDown[Arg];
}
/// Attempt to find the PtrState object describing the bottom up state for
/// pointer Arg. Return a new initialized PtrState describing the bottom up
/// state for Arg if we do not find one.
BottomUpPtrState &getPtrBottomUpState(const Value *Arg) {
return PerPtrBottomUp[Arg];
}
/// Attempt to find the PtrState object describing the bottom up state for
/// pointer Arg.
bottom_up_ptr_iterator findPtrBottomUpState(const Value *Arg) {
return PerPtrBottomUp.find(Arg);
}
void clearBottomUpPointers() {
PerPtrBottomUp.clear();
}
void clearTopDownPointers() {
PerPtrTopDown.clear();
}
void InitFromPred(const BBState &Other);
void InitFromSucc(const BBState &Other);
void MergePred(const BBState &Other);
void MergeSucc(const BBState &Other);
/// Compute the number of possible unique paths from an entry to an exit
/// which pass through this block. This is only valid after both the
/// top-down and bottom-up traversals are complete.
///
/// Returns true if overflow occurred. Returns false if overflow did not
/// occur.
bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
if (TopDownPathCount == OverflowOccurredValue ||
BottomUpPathCount == OverflowOccurredValue)
return true;
unsigned long long Product =
(unsigned long long)TopDownPathCount*BottomUpPathCount;
// Overflow occurred if any of the upper bits of Product are set or if all
// the lower bits of Product are all set.
return (Product >> 32) ||
((PathCount = Product) == OverflowOccurredValue);
}
// Specialized CFG utilities.
typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
edge_iterator pred_begin() const { return Preds.begin(); }
edge_iterator pred_end() const { return Preds.end(); }
edge_iterator succ_begin() const { return Succs.begin(); }
edge_iterator succ_end() const { return Succs.end(); }
void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
bool isExit() const { return Succs.empty(); }
};
const unsigned BBState::OverflowOccurredValue = 0xffffffff;
}
namespace llvm {
raw_ostream &operator<<(raw_ostream &OS,
BBState &BBState) LLVM_ATTRIBUTE_UNUSED;
}
void BBState::InitFromPred(const BBState &Other) {
PerPtrTopDown = Other.PerPtrTopDown;
TopDownPathCount = Other.TopDownPathCount;
}
void BBState::InitFromSucc(const BBState &Other) {
PerPtrBottomUp = Other.PerPtrBottomUp;
BottomUpPathCount = Other.BottomUpPathCount;
}
/// The top-down traversal uses this to merge information about predecessors to
/// form the initial state for a new block.
void BBState::MergePred(const BBState &Other) {
if (TopDownPathCount == OverflowOccurredValue)
return;
// Other.TopDownPathCount can be 0, in which case it is either dead or a
// loop backedge. Loop backedges are special.
TopDownPathCount += Other.TopDownPathCount;
// In order to be consistent, we clear the top down pointers when by adding
// TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
// has not occurred.
if (TopDownPathCount == OverflowOccurredValue) {
clearTopDownPointers();
return;
}
// Check for overflow. If we have overflow, fall back to conservative
// behavior.
if (TopDownPathCount < Other.TopDownPathCount) {
TopDownPathCount = OverflowOccurredValue;
clearTopDownPointers();
return;
}
// For each entry in the other set, if our set has an entry with the same key,
// merge the entries. Otherwise, copy the entry and merge it with an empty
// entry.
for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
MI != ME; ++MI) {
auto Pair = PerPtrTopDown.insert(*MI);
Pair.first->second.Merge(Pair.second ? TopDownPtrState() : MI->second,
/*TopDown=*/true);
}
// For each entry in our set, if the other set doesn't have an entry with the
// same key, force it to merge with an empty entry.
for (auto MI = top_down_ptr_begin(), ME = top_down_ptr_end(); MI != ME; ++MI)
if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
MI->second.Merge(TopDownPtrState(), /*TopDown=*/true);
}
/// The bottom-up traversal uses this to merge information about successors to
/// form the initial state for a new block.
void BBState::MergeSucc(const BBState &Other) {
if (BottomUpPathCount == OverflowOccurredValue)
return;
// Other.BottomUpPathCount can be 0, in which case it is either dead or a
// loop backedge. Loop backedges are special.
BottomUpPathCount += Other.BottomUpPathCount;
// In order to be consistent, we clear the top down pointers when by adding
// BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
// has not occurred.
if (BottomUpPathCount == OverflowOccurredValue) {
clearBottomUpPointers();
return;
}
// Check for overflow. If we have overflow, fall back to conservative
// behavior.
if (BottomUpPathCount < Other.BottomUpPathCount) {
BottomUpPathCount = OverflowOccurredValue;
clearBottomUpPointers();
return;
}
// For each entry in the other set, if our set has an entry with the
// same key, merge the entries. Otherwise, copy the entry and merge
// it with an empty entry.
for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
MI != ME; ++MI) {
auto Pair = PerPtrBottomUp.insert(*MI);
Pair.first->second.Merge(Pair.second ? BottomUpPtrState() : MI->second,
/*TopDown=*/false);
}
// For each entry in our set, if the other set doesn't have an entry
// with the same key, force it to merge with an empty entry.
for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME;
++MI)
if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
MI->second.Merge(BottomUpPtrState(), /*TopDown=*/false);
}
raw_ostream &llvm::operator<<(raw_ostream &OS, BBState &BBInfo) {
// Dump the pointers we are tracking.
OS << " TopDown State:\n";
if (!BBInfo.hasTopDownPtrs()) {
DEBUG(llvm::dbgs() << " NONE!\n");
} else {
for (auto I = BBInfo.top_down_ptr_begin(), E = BBInfo.top_down_ptr_end();
I != E; ++I) {
const PtrState &P = I->second;
OS << " Ptr: " << *I->first
<< "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false")
<< "\n ImpreciseRelease: "
<< (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
<< " HasCFGHazards: "
<< (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
<< " KnownPositive: "
<< (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
<< " Seq: "
<< P.GetSeq() << "\n";
}
}
OS << " BottomUp State:\n";
if (!BBInfo.hasBottomUpPtrs()) {
DEBUG(llvm::dbgs() << " NONE!\n");
} else {
for (auto I = BBInfo.bottom_up_ptr_begin(), E = BBInfo.bottom_up_ptr_end();
I != E; ++I) {
const PtrState &P = I->second;
OS << " Ptr: " << *I->first
<< "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false")
<< "\n ImpreciseRelease: "
<< (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
<< " HasCFGHazards: "
<< (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
<< " KnownPositive: "
<< (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
<< " Seq: "
<< P.GetSeq() << "\n";
}
}
return OS;
}
namespace {
/// \brief The main ARC optimization pass.
class ObjCARCOpt : public FunctionPass {
bool Changed;
ProvenanceAnalysis PA;
/// A cache of references to runtime entry point constants.
ARCRuntimeEntryPoints EP;
/// A cache of MDKinds that can be passed into other functions to propagate
/// MDKind identifiers.
ARCMDKindCache MDKindCache;
// This is used to track if a pointer is stored into an alloca.
DenseSet<const Value *> MultiOwnersSet;
/// A flag indicating whether this optimization pass should run.
bool Run;
/// Flags which determine whether each of the interesting runtine functions
/// is in fact used in the current function.
unsigned UsedInThisFunction;
bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
ARCInstKind &Class);
void OptimizeIndividualCalls(Function &F);
void CheckForCFGHazards(const BasicBlock *BB,
DenseMap<const BasicBlock *, BBState> &BBStates,
BBState &MyStates) const;
bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
BlotMapVector<Value *, RRInfo> &Retains,
BBState &MyStates);
bool VisitBottomUp(BasicBlock *BB,
DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains);
bool VisitInstructionTopDown(Instruction *Inst,
DenseMap<Value *, RRInfo> &Releases,
BBState &MyStates);
bool VisitTopDown(BasicBlock *BB,
DenseMap<const BasicBlock *, BBState> &BBStates,
DenseMap<Value *, RRInfo> &Releases);
bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases);
void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases,
SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
bool
PairUpRetainsAndReleases(DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases, Module *M,
SmallVectorImpl<Instruction *> &NewRetains,
SmallVectorImpl<Instruction *> &NewReleases,
SmallVectorImpl<Instruction *> &DeadInsts,
RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
Value *Arg, bool KnownSafe,
bool &AnyPairsCompletelyEliminated);
bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases, Module *M);
void OptimizeWeakCalls(Function &F);
bool OptimizeSequences(Function &F);
void OptimizeReturns(Function &F);
#ifndef NDEBUG
void GatherStatistics(Function &F, bool AfterOptimization = false);
#endif
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool doInitialization(Module &M) override;
bool runOnFunction(Function &F) override;
void releaseMemory() override;
public:
static char ID;
ObjCARCOpt() : FunctionPass(ID) {
initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
}
};
}
char ObjCARCOpt::ID = 0;
INITIALIZE_PASS_BEGIN(ObjCARCOpt,
"objc-arc", "ObjC ARC optimization", false, false)
INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
INITIALIZE_PASS_END(ObjCARCOpt,
"objc-arc", "ObjC ARC optimization", false, false)
Pass *llvm::createObjCARCOptPass() {
return new ObjCARCOpt();
}
void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<ObjCARCAliasAnalysis>();
AU.addRequired<AliasAnalysis>();
// ARC optimization doesn't currently split critical edges.
AU.setPreservesCFG();
}
/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
/// not a return value. Or, if it can be paired with an
/// objc_autoreleaseReturnValue, delete the pair and return true.
bool
ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
// Check for the argument being from an immediately preceding call or invoke.
const Value *Arg = GetArgRCIdentityRoot(RetainRV);
ImmutableCallSite CS(Arg);
if (const Instruction *Call = CS.getInstruction()) {
if (Call->getParent() == RetainRV->getParent()) {
BasicBlock::const_iterator I = Call;
++I;
while (IsNoopInstruction(I)) ++I;
if (&*I == RetainRV)
return false;
} else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
BasicBlock *RetainRVParent = RetainRV->getParent();
if (II->getNormalDest() == RetainRVParent) {
BasicBlock::const_iterator I = RetainRVParent->begin();
while (IsNoopInstruction(I)) ++I;
if (&*I == RetainRV)
return false;
}
}
}
// Check for being preceded by an objc_autoreleaseReturnValue on the same
// pointer. In this case, we can delete the pair.
BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
if (I != Begin) {
do --I; while (I != Begin && IsNoopInstruction(I));
if (GetBasicARCInstKind(I) == ARCInstKind::AutoreleaseRV &&
GetArgRCIdentityRoot(I) == Arg) {
Changed = true;
++NumPeeps;
DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
<< "Erasing " << *RetainRV << "\n");
EraseInstruction(I);
EraseInstruction(RetainRV);
return true;
}
}
// Turn it to a plain objc_retain.
Changed = true;
++NumPeeps;
DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
"objc_retain since the operand is not a return value.\n"
"Old = " << *RetainRV << "\n");
Constant *NewDecl = EP.get(ARCRuntimeEntryPointKind::Retain);
cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
DEBUG(dbgs() << "New = " << *RetainRV << "\n");
return false;
}
/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
/// used as a return value.
void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
Instruction *AutoreleaseRV,
ARCInstKind &Class) {
// Check for a return of the pointer value.
const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
SmallVector<const Value *, 2> Users;
Users.push_back(Ptr);
do {
Ptr = Users.pop_back_val();
for (const User *U : Ptr->users()) {
if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
return;
if (isa<BitCastInst>(U))
Users.push_back(U);
}
} while (!Users.empty());
Changed = true;
++NumPeeps;
DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
"objc_autorelease since its operand is not used as a return "
"value.\n"
"Old = " << *AutoreleaseRV << "\n");
CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
Constant *NewDecl = EP.get(ARCRuntimeEntryPointKind::Autorelease);
AutoreleaseRVCI->setCalledFunction(NewDecl);
AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Class = ARCInstKind::Autorelease;
DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
}
/// Visit each call, one at a time, and make simplifications without doing any
/// additional analysis.
void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
// Reset all the flags in preparation for recomputing them.
UsedInThisFunction = 0;
// Visit all objc_* calls in F.
for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
Instruction *Inst = &*I++;
ARCInstKind Class = GetBasicARCInstKind(Inst);
DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
switch (Class) {
default: break;
// Delete no-op casts. These function calls have special semantics, but
// the semantics are entirely implemented via lowering in the front-end,
// so by the time they reach the optimizer, they are just no-op calls
// which return their argument.
//
// There are gray areas here, as the ability to cast reference-counted
// pointers to raw void* and back allows code to break ARC assumptions,
// however these are currently considered to be unimportant.
case ARCInstKind::NoopCast:
Changed = true;
++NumNoops;
DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
EraseInstruction(Inst);
continue;
// If the pointer-to-weak-pointer is null, it's undefined behavior.
case ARCInstKind::StoreWeak:
case ARCInstKind::LoadWeak:
case ARCInstKind::LoadWeakRetained:
case ARCInstKind::InitWeak:
case ARCInstKind::DestroyWeak: {
CallInst *CI = cast<CallInst>(Inst);
if (IsNullOrUndef(CI->getArgOperand(0))) {
Changed = true;
Type *Ty = CI->getArgOperand(0)->getType();
new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
Constant::getNullValue(Ty),
CI);
llvm::Value *NewValue = UndefValue::get(CI->getType());
DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
"\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
CI->replaceAllUsesWith(NewValue);
CI->eraseFromParent();
continue;
}
break;
}
case ARCInstKind::CopyWeak:
case ARCInstKind::MoveWeak: {
CallInst *CI = cast<CallInst>(Inst);
if (IsNullOrUndef(CI->getArgOperand(0)) ||
IsNullOrUndef(CI->getArgOperand(1))) {
Changed = true;
Type *Ty = CI->getArgOperand(0)->getType();
new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
Constant::getNullValue(Ty),
CI);
llvm::Value *NewValue = UndefValue::get(CI->getType());
DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
"\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
CI->replaceAllUsesWith(NewValue);
CI->eraseFromParent();
continue;
}
break;
}
case ARCInstKind::RetainRV:
if (OptimizeRetainRVCall(F, Inst))
continue;
break;
case ARCInstKind::AutoreleaseRV:
OptimizeAutoreleaseRVCall(F, Inst, Class);
break;
}
// objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
if (IsAutorelease(Class) && Inst->use_empty()) {
CallInst *Call = cast<CallInst>(Inst);
const Value *Arg = Call->getArgOperand(0);
Arg = FindSingleUseIdentifiedObject(Arg);
if (Arg) {
Changed = true;
++NumAutoreleases;
// Create the declaration lazily.
LLVMContext &C = Inst->getContext();
Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
Call);
NewCall->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease),
MDNode::get(C, None));
DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
"since x is otherwise unused.\nOld: " << *Call << "\nNew: "
<< *NewCall << "\n");
EraseInstruction(Call);
Inst = NewCall;
Class = ARCInstKind::Release;
}
}
// For functions which can never be passed stack arguments, add
// a tail keyword.
if (IsAlwaysTail(Class)) {
Changed = true;
DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
"passed stack args: " << *Inst << "\n");
cast<CallInst>(Inst)->setTailCall();
}
// Ensure that functions that can never have a "tail" keyword due to the
// semantics of ARC truly do not do so.
if (IsNeverTail(Class)) {
Changed = true;
DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
"\n");
cast<CallInst>(Inst)->setTailCall(false);
}
// Set nounwind as needed.
if (IsNoThrow(Class)) {
Changed = true;
DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
<< "\n");
cast<CallInst>(Inst)->setDoesNotThrow();
}
if (!IsNoopOnNull(Class)) {
UsedInThisFunction |= 1 << unsigned(Class);
continue;
}
const Value *Arg = GetArgRCIdentityRoot(Inst);
// ARC calls with null are no-ops. Delete them.
if (IsNullOrUndef(Arg)) {
Changed = true;
++NumNoops;
DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
<< "\n");
EraseInstruction(Inst);
continue;
}
// Keep track of which of retain, release, autorelease, and retain_block
// are actually present in this function.
UsedInThisFunction |= 1 << unsigned(Class);
// If Arg is a PHI, and one or more incoming values to the
// PHI are null, and the call is control-equivalent to the PHI, and there
// are no relevant side effects between the PHI and the call, the call
// could be pushed up to just those paths with non-null incoming values.
// For now, don't bother splitting critical edges for this.
SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
Worklist.push_back(std::make_pair(Inst, Arg));
do {
std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
Inst = Pair.first;
Arg = Pair.second;
const PHINode *PN = dyn_cast<PHINode>(Arg);
if (!PN) continue;
// Determine if the PHI has any null operands, or any incoming
// critical edges.
bool HasNull = false;
bool HasCriticalEdges = false;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *Incoming =
GetRCIdentityRoot(PN->getIncomingValue(i));
if (IsNullOrUndef(Incoming))
HasNull = true;
else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
.getNumSuccessors() != 1) {
HasCriticalEdges = true;
break;
}
}
// If we have null operands and no critical edges, optimize.
if (!HasCriticalEdges && HasNull) {
SmallPtrSet<Instruction *, 4> DependingInstructions;
SmallPtrSet<const BasicBlock *, 4> Visited;
// Check that there is nothing that cares about the reference
// count between the call and the phi.
switch (Class) {
case ARCInstKind::Retain:
case ARCInstKind::RetainBlock:
// These can always be moved up.
break;
case ARCInstKind::Release:
// These can't be moved across things that care about the retain
// count.
FindDependencies(NeedsPositiveRetainCount, Arg,
Inst->getParent(), Inst,
DependingInstructions, Visited, PA);
break;
case ARCInstKind::Autorelease:
// These can't be moved across autorelease pool scope boundaries.
FindDependencies(AutoreleasePoolBoundary, Arg,
Inst->getParent(), Inst,
DependingInstructions, Visited, PA);
break;
case ARCInstKind::RetainRV:
case ARCInstKind::AutoreleaseRV:
// Don't move these; the RV optimization depends on the autoreleaseRV
// being tail called, and the retainRV being immediately after a call
// (which might still happen if we get lucky with codegen layout, but
// it's not worth taking the chance).
continue;
default:
llvm_unreachable("Invalid dependence flavor");
}
if (DependingInstructions.size() == 1 &&
*DependingInstructions.begin() == PN) {
Changed = true;
++NumPartialNoops;
// Clone the call into each predecessor that has a non-null value.
CallInst *CInst = cast<CallInst>(Inst);
Type *ParamTy = CInst->getArgOperand(0)->getType();
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *Incoming =
GetRCIdentityRoot(PN->getIncomingValue(i));
if (!IsNullOrUndef(Incoming)) {
CallInst *Clone = cast<CallInst>(CInst->clone());
Value *Op = PN->getIncomingValue(i);
Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
if (Op->getType() != ParamTy)
Op = new BitCastInst(Op, ParamTy, "", InsertPos);
Clone->setArgOperand(0, Op);
Clone->insertBefore(InsertPos);
DEBUG(dbgs() << "Cloning "
<< *CInst << "\n"
"And inserting clone at " << *InsertPos << "\n");
Worklist.push_back(std::make_pair(Clone, Incoming));
}
}
// Erase the original call.
DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
EraseInstruction(CInst);
continue;
}
}
} while (!Worklist.empty());
}
}
/// If we have a top down pointer in the S_Use state, make sure that there are
/// no CFG hazards by checking the states of various bottom up pointers.
static void CheckForUseCFGHazard(const Sequence SuccSSeq,
const bool SuccSRRIKnownSafe,
TopDownPtrState &S,
bool &SomeSuccHasSame,
bool &AllSuccsHaveSame,
bool &NotAllSeqEqualButKnownSafe,
bool &ShouldContinue) {
switch (SuccSSeq) {
case S_CanRelease: {
if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
S.ClearSequenceProgress();
break;
}
S.SetCFGHazardAfflicted(true);
ShouldContinue = true;
break;
}
case S_Use:
SomeSuccHasSame = true;
break;
case S_Stop:
case S_Release:
case S_MovableRelease:
if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
AllSuccsHaveSame = false;
else
NotAllSeqEqualButKnownSafe = true;
break;
case S_Retain:
llvm_unreachable("bottom-up pointer in retain state!");
case S_None:
llvm_unreachable("This should have been handled earlier.");
}
}
/// If we have a Top Down pointer in the S_CanRelease state, make sure that
/// there are no CFG hazards by checking the states of various bottom up
/// pointers.
static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
const bool SuccSRRIKnownSafe,
TopDownPtrState &S,
bool &SomeSuccHasSame,
bool &AllSuccsHaveSame,
bool &NotAllSeqEqualButKnownSafe) {
switch (SuccSSeq) {
case S_CanRelease:
SomeSuccHasSame = true;
break;
case S_Stop:
case S_Release:
case S_MovableRelease:
case S_Use:
if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
AllSuccsHaveSame = false;
else
NotAllSeqEqualButKnownSafe = true;
break;
case S_Retain:
llvm_unreachable("bottom-up pointer in retain state!");
case S_None:
llvm_unreachable("This should have been handled earlier.");
}
}
/// Check for critical edges, loop boundaries, irreducible control flow, or
/// other CFG structures where moving code across the edge would result in it
/// being executed more.
void
ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
DenseMap<const BasicBlock *, BBState> &BBStates,
BBState &MyStates) const {
// If any top-down local-use or possible-dec has a succ which is earlier in
// the sequence, forget it.
for (auto I = MyStates.top_down_ptr_begin(), E = MyStates.top_down_ptr_end();
I != E; ++I) {
TopDownPtrState &S = I->second;
const Sequence Seq = I->second.GetSeq();
// We only care about S_Retain, S_CanRelease, and S_Use.
if (Seq == S_None)
continue;
// Make sure that if extra top down states are added in the future that this
// code is updated to handle it.
assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
"Unknown top down sequence state.");
const Value *Arg = I->first;
const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
bool SomeSuccHasSame = false;
bool AllSuccsHaveSame = true;
bool NotAllSeqEqualButKnownSafe = false;
succ_const_iterator SI(TI), SE(TI, false);
for (; SI != SE; ++SI) {
// If VisitBottomUp has pointer information for this successor, take
// what we know about it.
const DenseMap<const BasicBlock *, BBState>::iterator BBI =
BBStates.find(*SI);
assert(BBI != BBStates.end());
const BottomUpPtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
const Sequence SuccSSeq = SuccS.GetSeq();
// If bottom up, the pointer is in an S_None state, clear the sequence
// progress since the sequence in the bottom up state finished
// suggesting a mismatch in between retains/releases. This is true for
// all three cases that we are handling here: S_Retain, S_Use, and
// S_CanRelease.
if (SuccSSeq == S_None) {
S.ClearSequenceProgress();
continue;
}
// If we have S_Use or S_CanRelease, perform our check for cfg hazard
// checks.
const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
// *NOTE* We do not use Seq from above here since we are allowing for
// S.GetSeq() to change while we are visiting basic blocks.
switch(S.GetSeq()) {
case S_Use: {
bool ShouldContinue = false;
CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
ShouldContinue);
if (ShouldContinue)
continue;
break;
}
case S_CanRelease: {
CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
SomeSuccHasSame, AllSuccsHaveSame,
NotAllSeqEqualButKnownSafe);
break;
}
case S_Retain:
case S_None:
case S_Stop:
case S_Release:
case S_MovableRelease:
break;
}
}
// If the state at the other end of any of the successor edges
// matches the current state, require all edges to match. This
// guards against loops in the middle of a sequence.
if (SomeSuccHasSame && !AllSuccsHaveSame) {
S.ClearSequenceProgress();
} else if (NotAllSeqEqualButKnownSafe) {
// If we would have cleared the state foregoing the fact that we are known
// safe, stop code motion. This is because whether or not it is safe to
// remove RR pairs via KnownSafe is an orthogonal concept to whether we
// are allowed to perform code motion.
S.SetCFGHazardAfflicted(true);
}
}
}
bool ObjCARCOpt::VisitInstructionBottomUp(
Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
BBState &MyStates) {
bool NestingDetected = false;
ARCInstKind Class = GetARCInstKind(Inst);
const Value *Arg = nullptr;
DEBUG(dbgs() << " Class: " << Class << "\n");
switch (Class) {
case ARCInstKind::Release: {
Arg = GetArgRCIdentityRoot(Inst);
BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
NestingDetected |= S.InitBottomUp(MDKindCache, Inst);
break;
}
case ARCInstKind::RetainBlock:
// In OptimizeIndividualCalls, we have strength reduced all optimizable
// objc_retainBlocks to objc_retains. Thus at this point any
// objc_retainBlocks that we see are not optimizable.
break;
case ARCInstKind::Retain:
case ARCInstKind::RetainRV: {
Arg = GetArgRCIdentityRoot(Inst);
BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
if (S.MatchWithRetain()) {
// Don't do retain+release tracking for ARCInstKind::RetainRV, because
// it's better to let it remain as the first instruction after a call.
if (Class != ARCInstKind::RetainRV) {
DEBUG(llvm::dbgs() << " Matching with: " << *Inst << "\n");
Retains[Inst] = S.GetRRInfo();
}
S.ClearSequenceProgress();
}
// A retain moving bottom up can be a use.
break;
}
case ARCInstKind::AutoreleasepoolPop:
// Conservatively, clear MyStates for all known pointers.
MyStates.clearBottomUpPointers();
return NestingDetected;
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::None:
// These are irrelevant.
return NestingDetected;
case ARCInstKind::User:
// If we have a store into an alloca of a pointer we are tracking, the
// pointer has multiple owners implying that we must be more conservative.
//
// This comes up in the context of a pointer being ``KnownSafe''. In the
// presence of a block being initialized, the frontend will emit the
// objc_retain on the original pointer and the release on the pointer loaded
// from the alloca. The optimizer will through the provenance analysis
// realize that the two are related, but since we only require KnownSafe in
// one direction, will match the inner retain on the original pointer with
// the guard release on the original pointer. This is fixed by ensuring that
// in the presence of allocas we only unconditionally remove pointers if
// both our retain and our release are KnownSafe.
if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
const DataLayout &DL = BB->getModule()->getDataLayout();
if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand(), DL)) {
auto I = MyStates.findPtrBottomUpState(
GetRCIdentityRoot(SI->getValueOperand()));
if (I != MyStates.bottom_up_ptr_end())
MultiOwnersSet.insert(I->first);
}
}
break;
default:
break;
}
// Consider any other possible effects of this instruction on each
// pointer being tracked.
for (auto MI = MyStates.bottom_up_ptr_begin(),
ME = MyStates.bottom_up_ptr_end();
MI != ME; ++MI) {
const Value *Ptr = MI->first;
if (Ptr == Arg)
continue; // Handled above.
BottomUpPtrState &S = MI->second;
if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
continue;
S.HandlePotentialUse(BB, Inst, Ptr, PA, Class);
}
return NestingDetected;
}
bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains) {
DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
bool NestingDetected = false;
BBState &MyStates = BBStates[BB];
// Merge the states from each successor to compute the initial state
// for the current block.
BBState::edge_iterator SI(MyStates.succ_begin()),
SE(MyStates.succ_end());
if (SI != SE) {
const BasicBlock *Succ = *SI;
DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
assert(I != BBStates.end());
MyStates.InitFromSucc(I->second);
++SI;
for (; SI != SE; ++SI) {
Succ = *SI;
I = BBStates.find(Succ);
assert(I != BBStates.end());
MyStates.MergeSucc(I->second);
}
}
DEBUG(llvm::dbgs() << "Before:\n" << BBStates[BB] << "\n"
<< "Performing Dataflow:\n");
// Visit all the instructions, bottom-up.
for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
Instruction *Inst = std::prev(I);
// Invoke instructions are visited as part of their successors (below).
if (isa<InvokeInst>(Inst))
continue;
DEBUG(dbgs() << " Visiting " << *Inst << "\n");
NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
}
// If there's a predecessor with an invoke, visit the invoke as if it were
// part of this block, since we can't insert code after an invoke in its own
// block, and we don't want to split critical edges.
for (BBState::edge_iterator PI(MyStates.pred_begin()),
PE(MyStates.pred_end()); PI != PE; ++PI) {
BasicBlock *Pred = *PI;
if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
}
DEBUG(llvm::dbgs() << "\nFinal State:\n" << BBStates[BB] << "\n");
return NestingDetected;
}
bool
ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
DenseMap<Value *, RRInfo> &Releases,
BBState &MyStates) {
bool NestingDetected = false;
ARCInstKind Class = GetARCInstKind(Inst);
const Value *Arg = nullptr;
DEBUG(llvm::dbgs() << " Class: " << Class << "\n");
switch (Class) {
case ARCInstKind::RetainBlock:
// In OptimizeIndividualCalls, we have strength reduced all optimizable
// objc_retainBlocks to objc_retains. Thus at this point any
// objc_retainBlocks that we see are not optimizable. We need to break since
// a retain can be a potential use.
break;
case ARCInstKind::Retain:
case ARCInstKind::RetainRV: {
Arg = GetArgRCIdentityRoot(Inst);
TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
NestingDetected |= S.InitTopDown(Class, Inst);
// A retain can be a potential use; procede to the generic checking
// code below.
break;
}
case ARCInstKind::Release: {
Arg = GetArgRCIdentityRoot(Inst);
TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
// Try to form a tentative pair in between this release instruction and the
// top down pointers that we are tracking.
if (S.MatchWithRelease(MDKindCache, Inst)) {
// If we succeed, copy S's RRInfo into the Release -> {Retain Set
// Map}. Then we clear S.
DEBUG(llvm::dbgs() << " Matching with: " << *Inst << "\n");
Releases[Inst] = S.GetRRInfo();
S.ClearSequenceProgress();
}
break;
}
case ARCInstKind::AutoreleasepoolPop:
// Conservatively, clear MyStates for all known pointers.
MyStates.clearTopDownPointers();
return false;
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::None:
// These can not be uses of
return false;
default:
break;
}
// Consider any other possible effects of this instruction on each
// pointer being tracked.
for (auto MI = MyStates.top_down_ptr_begin(),
ME = MyStates.top_down_ptr_end();
MI != ME; ++MI) {
const Value *Ptr = MI->first;
if (Ptr == Arg)
continue; // Handled above.
TopDownPtrState &S = MI->second;
if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
continue;
S.HandlePotentialUse(Inst, Ptr, PA, Class);
}
return NestingDetected;
}
bool
ObjCARCOpt::VisitTopDown(BasicBlock *BB,
DenseMap<const BasicBlock *, BBState> &BBStates,
DenseMap<Value *, RRInfo> &Releases) {
DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
bool NestingDetected = false;
BBState &MyStates = BBStates[BB];
// Merge the states from each predecessor to compute the initial state
// for the current block.
BBState::edge_iterator PI(MyStates.pred_begin()),
PE(MyStates.pred_end());
if (PI != PE) {
const BasicBlock *Pred = *PI;
DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
assert(I != BBStates.end());
MyStates.InitFromPred(I->second);
++PI;
for (; PI != PE; ++PI) {
Pred = *PI;
I = BBStates.find(Pred);
assert(I != BBStates.end());
MyStates.MergePred(I->second);
}
}
DEBUG(llvm::dbgs() << "Before:\n" << BBStates[BB] << "\n"
<< "Performing Dataflow:\n");
// Visit all the instructions, top-down.
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Instruction *Inst = I;
DEBUG(dbgs() << " Visiting " << *Inst << "\n");
NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
}
DEBUG(llvm::dbgs() << "\nState Before Checking for CFG Hazards:\n"
<< BBStates[BB] << "\n\n");
CheckForCFGHazards(BB, BBStates, MyStates);
DEBUG(llvm::dbgs() << "Final State:\n" << BBStates[BB] << "\n");
return NestingDetected;
}
static void
ComputePostOrders(Function &F,
SmallVectorImpl<BasicBlock *> &PostOrder,
SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
unsigned NoObjCARCExceptionsMDKind,
DenseMap<const BasicBlock *, BBState> &BBStates) {
/// The visited set, for doing DFS walks.
SmallPtrSet<BasicBlock *, 16> Visited;
// Do DFS, computing the PostOrder.
SmallPtrSet<BasicBlock *, 16> OnStack;
SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
// Functions always have exactly one entry block, and we don't have
// any other block that we treat like an entry block.
BasicBlock *EntryBB = &F.getEntryBlock();
BBState &MyStates = BBStates[EntryBB];
MyStates.SetAsEntry();
TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Visited.insert(EntryBB);
OnStack.insert(EntryBB);
do {
dfs_next_succ:
BasicBlock *CurrBB = SuccStack.back().first;
TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
succ_iterator SE(TI, false);
while (SuccStack.back().second != SE) {
BasicBlock *SuccBB = *SuccStack.back().second++;
if (Visited.insert(SuccBB).second) {
TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
BBStates[CurrBB].addSucc(SuccBB);
BBState &SuccStates = BBStates[SuccBB];
SuccStates.addPred(CurrBB);
OnStack.insert(SuccBB);
goto dfs_next_succ;
}
if (!OnStack.count(SuccBB)) {
BBStates[CurrBB].addSucc(SuccBB);
BBStates[SuccBB].addPred(CurrBB);
}
}
OnStack.erase(CurrBB);
PostOrder.push_back(CurrBB);
SuccStack.pop_back();
} while (!SuccStack.empty());
Visited.clear();
// Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
// Functions may have many exits, and there also blocks which we treat
// as exits due to ignored edges.
SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
BasicBlock *ExitBB = I;
BBState &MyStates = BBStates[ExitBB];
if (!MyStates.isExit())
continue;
MyStates.SetAsExit();
PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Visited.insert(ExitBB);
while (!PredStack.empty()) {
reverse_dfs_next_succ:
BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
while (PredStack.back().second != PE) {
BasicBlock *BB = *PredStack.back().second++;
if (Visited.insert(BB).second) {
PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
goto reverse_dfs_next_succ;
}
}
ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
}
}
}
// Visit the function both top-down and bottom-up.
bool ObjCARCOpt::Visit(Function &F,
DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases) {
// Use reverse-postorder traversals, because we magically know that loops
// will be well behaved, i.e. they won't repeatedly call retain on a single
// pointer without doing a release. We can't use the ReversePostOrderTraversal
// class here because we want the reverse-CFG postorder to consider each
// function exit point, and we want to ignore selected cycle edges.
SmallVector<BasicBlock *, 16> PostOrder;
SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
MDKindCache.get(ARCMDKindID::NoObjCARCExceptions),
BBStates);
// Use reverse-postorder on the reverse CFG for bottom-up.
bool BottomUpNestingDetected = false;
for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
I != E; ++I)
BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
// Use reverse-postorder for top-down.
bool TopDownNestingDetected = false;
for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
PostOrder.rbegin(), E = PostOrder.rend();
I != E; ++I)
TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
return TopDownNestingDetected && BottomUpNestingDetected;
}
/// Move the calls in RetainsToMove and ReleasesToMove.
void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
RRInfo &ReleasesToMove,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases,
SmallVectorImpl<Instruction *> &DeadInsts,
Module *M) {
Type *ArgTy = Arg->getType();
Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
// Insert the new retain and release calls.
for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
Value *MyArg = ArgTy == ParamTy ? Arg :
new BitCastInst(Arg, ParamTy, "", InsertPt);
Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
Call->setDoesNotThrow();
Call->setTailCall();
DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
"At insertion point: " << *InsertPt << "\n");
}
for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
Value *MyArg = ArgTy == ParamTy ? Arg :
new BitCastInst(Arg, ParamTy, "", InsertPt);
Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
// Attach a clang.imprecise_release metadata tag, if appropriate.
if (MDNode *M = ReleasesToMove.ReleaseMetadata)
Call->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease), M);
Call->setDoesNotThrow();
if (ReleasesToMove.IsTailCallRelease)
Call->setTailCall();
DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
"At insertion point: " << *InsertPt << "\n");
}
// Delete the original retain and release calls.
for (Instruction *OrigRetain : RetainsToMove.Calls) {
Retains.blot(OrigRetain);
DeadInsts.push_back(OrigRetain);
DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
}
for (Instruction *OrigRelease : ReleasesToMove.Calls) {
Releases.erase(OrigRelease);
DeadInsts.push_back(OrigRelease);
DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
}
}
bool ObjCARCOpt::PairUpRetainsAndReleases(
DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases, Module *M,
SmallVectorImpl<Instruction *> &NewRetains,
SmallVectorImpl<Instruction *> &NewReleases,
SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
bool &AnyPairsCompletelyEliminated) {
// If a pair happens in a region where it is known that the reference count
// is already incremented, we can similarly ignore possible decrements unless
// we are dealing with a retainable object with multiple provenance sources.
bool KnownSafeTD = true, KnownSafeBU = true;
bool MultipleOwners = false;
bool CFGHazardAfflicted = false;
// Connect the dots between the top-down-collected RetainsToMove and
// bottom-up-collected ReleasesToMove to form sets of related calls.
// This is an iterative process so that we connect multiple releases
// to multiple retains if needed.
unsigned OldDelta = 0;
unsigned NewDelta = 0;
unsigned OldCount = 0;
unsigned NewCount = 0;
bool FirstRelease = true;
for (;;) {
for (SmallVectorImpl<Instruction *>::const_iterator
NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
Instruction *NewRetain = *NI;
auto It = Retains.find(NewRetain);
assert(It != Retains.end());
const RRInfo &NewRetainRRI = It->second;
KnownSafeTD &= NewRetainRRI.KnownSafe;
MultipleOwners =
MultipleOwners || MultiOwnersSet.count(GetArgRCIdentityRoot(NewRetain));
for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
auto Jt = Releases.find(NewRetainRelease);
if (Jt == Releases.end())
return false;
const RRInfo &NewRetainReleaseRRI = Jt->second;
// If the release does not have a reference to the retain as well,
// something happened which is unaccounted for. Do not do anything.
//
// This can happen if we catch an additive overflow during path count
// merging.
if (!NewRetainReleaseRRI.Calls.count(NewRetain))
return false;
if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
// If we overflow when we compute the path count, don't remove/move
// anything.
const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
unsigned PathCount = BBState::OverflowOccurredValue;
if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
return false;
assert(PathCount != BBState::OverflowOccurredValue &&
"PathCount at this point can not be "
"OverflowOccurredValue.");
OldDelta -= PathCount;
// Merge the ReleaseMetadata and IsTailCallRelease values.
if (FirstRelease) {
ReleasesToMove.ReleaseMetadata =
NewRetainReleaseRRI.ReleaseMetadata;
ReleasesToMove.IsTailCallRelease =
NewRetainReleaseRRI.IsTailCallRelease;
FirstRelease = false;
} else {
if (ReleasesToMove.ReleaseMetadata !=
NewRetainReleaseRRI.ReleaseMetadata)
ReleasesToMove.ReleaseMetadata = nullptr;
if (ReleasesToMove.IsTailCallRelease !=
NewRetainReleaseRRI.IsTailCallRelease)
ReleasesToMove.IsTailCallRelease = false;
}
// Collect the optimal insertion points.
if (!KnownSafe)
for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
// If we overflow when we compute the path count, don't
// remove/move anything.
const BBState &RIPBBState = BBStates[RIP->getParent()];
PathCount = BBState::OverflowOccurredValue;
if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
return false;
assert(PathCount != BBState::OverflowOccurredValue &&
"PathCount at this point can not be "
"OverflowOccurredValue.");
NewDelta -= PathCount;
}
}
NewReleases.push_back(NewRetainRelease);
}
}
}
NewRetains.clear();
if (NewReleases.empty()) break;
// Back the other way.
for (SmallVectorImpl<Instruction *>::const_iterator
NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
Instruction *NewRelease = *NI;
auto It = Releases.find(NewRelease);
assert(It != Releases.end());
const RRInfo &NewReleaseRRI = It->second;
KnownSafeBU &= NewReleaseRRI.KnownSafe;
CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
auto Jt = Retains.find(NewReleaseRetain);
if (Jt == Retains.end())
return false;
const RRInfo &NewReleaseRetainRRI = Jt->second;
// If the retain does not have a reference to the release as well,
// something happened which is unaccounted for. Do not do anything.
//
// This can happen if we catch an additive overflow during path count
// merging.
if (!NewReleaseRetainRRI.Calls.count(NewRelease))
return false;
if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
// If we overflow when we compute the path count, don't remove/move
// anything.
const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
unsigned PathCount = BBState::OverflowOccurredValue;
if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
return false;
assert(PathCount != BBState::OverflowOccurredValue &&
"PathCount at this point can not be "
"OverflowOccurredValue.");
OldDelta += PathCount;
OldCount += PathCount;
// Collect the optimal insertion points.
if (!KnownSafe)
for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
// If we overflow when we compute the path count, don't
// remove/move anything.
const BBState &RIPBBState = BBStates[RIP->getParent()];
PathCount = BBState::OverflowOccurredValue;
if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
return false;
assert(PathCount != BBState::OverflowOccurredValue &&
"PathCount at this point can not be "
"OverflowOccurredValue.");
NewDelta += PathCount;
NewCount += PathCount;
}
}
NewRetains.push_back(NewReleaseRetain);
}
}
}
NewReleases.clear();
if (NewRetains.empty()) break;
}
// We can only remove pointers if we are known safe in both directions.
bool UnconditionallySafe = KnownSafeTD && KnownSafeBU;
if (UnconditionallySafe) {
RetainsToMove.ReverseInsertPts.clear();
ReleasesToMove.ReverseInsertPts.clear();
NewCount = 0;
} else {
// Determine whether the new insertion points we computed preserve the
// balance of retain and release calls through the program.
// TODO: If the fully aggressive solution isn't valid, try to find a
// less aggressive solution which is.
if (NewDelta != 0)
return false;
// At this point, we are not going to remove any RR pairs, but we still are
// able to move RR pairs. If one of our pointers is afflicted with
// CFGHazards, we cannot perform such code motion so exit early.
const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
ReleasesToMove.ReverseInsertPts.size();
if (CFGHazardAfflicted && WillPerformCodeMotion)
return false;
}
// Determine whether the original call points are balanced in the retain and
// release calls through the program. If not, conservatively don't touch
// them.
// TODO: It's theoretically possible to do code motion in this case, as
// long as the existing imbalances are maintained.
if (OldDelta != 0)
return false;
Changed = true;
assert(OldCount != 0 && "Unreachable code?");
NumRRs += OldCount - NewCount;
// Set to true if we completely removed any RR pairs.
AnyPairsCompletelyEliminated = NewCount == 0;
// We can move calls!
return true;
}
/// Identify pairings between the retains and releases, and delete and/or move
/// them.
bool ObjCARCOpt::PerformCodePlacement(
DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases, Module *M) {
DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
bool AnyPairsCompletelyEliminated = false;
RRInfo RetainsToMove;
RRInfo ReleasesToMove;
SmallVector<Instruction *, 4> NewRetains;
SmallVector<Instruction *, 4> NewReleases;
SmallVector<Instruction *, 8> DeadInsts;
// Visit each retain.
for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
E = Retains.end();
I != E; ++I) {
Value *V = I->first;
if (!V) continue; // blotted
Instruction *Retain = cast<Instruction>(V);
DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Value *Arg = GetArgRCIdentityRoot(Retain);
// If the object being released is in static or stack storage, we know it's
// not being managed by ObjC reference counting, so we can delete pairs
// regardless of what possible decrements or uses lie between them.
bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
// A constant pointer can't be pointing to an object on the heap. It may
// be reference-counted, but it won't be deleted.
if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
if (const GlobalVariable *GV =
dyn_cast<GlobalVariable>(
GetRCIdentityRoot(LI->getPointerOperand())))
if (GV->isConstant())
KnownSafe = true;
// Connect the dots between the top-down-collected RetainsToMove and
// bottom-up-collected ReleasesToMove to form sets of related calls.
NewRetains.push_back(Retain);
bool PerformMoveCalls = PairUpRetainsAndReleases(
BBStates, Retains, Releases, M, NewRetains, NewReleases, DeadInsts,
RetainsToMove, ReleasesToMove, Arg, KnownSafe,
AnyPairsCompletelyEliminated);
if (PerformMoveCalls) {
// Ok, everything checks out and we're all set. Let's move/delete some
// code!
MoveCalls(Arg, RetainsToMove, ReleasesToMove,
Retains, Releases, DeadInsts, M);
}
// Clean up state for next retain.
NewReleases.clear();
NewRetains.clear();
RetainsToMove.clear();
ReleasesToMove.clear();
}
// Now that we're done moving everything, we can delete the newly dead
// instructions, as we no longer need them as insert points.
while (!DeadInsts.empty())
EraseInstruction(DeadInsts.pop_back_val());
return AnyPairsCompletelyEliminated;
}
/// Weak pointer optimizations.
void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
// First, do memdep-style RLE and S2L optimizations. We can't use memdep
// itself because it uses AliasAnalysis and we need to do provenance
// queries instead.
for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
Instruction *Inst = &*I++;
DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
ARCInstKind Class = GetBasicARCInstKind(Inst);
if (Class != ARCInstKind::LoadWeak &&
Class != ARCInstKind::LoadWeakRetained)
continue;
// Delete objc_loadWeak calls with no users.
if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
Inst->eraseFromParent();
continue;
}
// TODO: For now, just look for an earlier available version of this value
// within the same block. Theoretically, we could do memdep-style non-local
// analysis too, but that would want caching. A better approach would be to
// use the technique that EarlyCSE uses.
inst_iterator Current = std::prev(I);
BasicBlock *CurrentBB = Current.getBasicBlockIterator();
for (BasicBlock::iterator B = CurrentBB->begin(),
J = Current.getInstructionIterator();
J != B; --J) {
Instruction *EarlierInst = &*std::prev(J);
ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
switch (EarlierClass) {
case ARCInstKind::LoadWeak:
case ARCInstKind::LoadWeakRetained: {
// If this is loading from the same pointer, replace this load's value
// with that one.
CallInst *Call = cast<CallInst>(Inst);
CallInst *EarlierCall = cast<CallInst>(EarlierInst);
Value *Arg = Call->getArgOperand(0);
Value *EarlierArg = EarlierCall->getArgOperand(0);
switch (PA.getAA()->alias(Arg, EarlierArg)) {
case MustAlias:
Changed = true;
// If the load has a builtin retain, insert a plain retain for it.
if (Class == ARCInstKind::LoadWeakRetained) {
Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
CI->setTailCall();
}
// Zap the fully redundant load.
Call->replaceAllUsesWith(EarlierCall);
Call->eraseFromParent();
goto clobbered;
case MayAlias:
case PartialAlias:
goto clobbered;
case NoAlias:
break;
}
break;
}
case ARCInstKind::StoreWeak:
case ARCInstKind::InitWeak: {
// If this is storing to the same pointer and has the same size etc.
// replace this load's value with the stored value.
CallInst *Call = cast<CallInst>(Inst);
CallInst *EarlierCall = cast<CallInst>(EarlierInst);
Value *Arg = Call->getArgOperand(0);
Value *EarlierArg = EarlierCall->getArgOperand(0);
switch (PA.getAA()->alias(Arg, EarlierArg)) {
case MustAlias:
Changed = true;
// If the load has a builtin retain, insert a plain retain for it.
if (Class == ARCInstKind::LoadWeakRetained) {
Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
CI->setTailCall();
}
// Zap the fully redundant load.
Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
Call->eraseFromParent();
goto clobbered;
case MayAlias:
case PartialAlias:
goto clobbered;
case NoAlias:
break;
}
break;
}
case ARCInstKind::MoveWeak:
case ARCInstKind::CopyWeak:
// TOOD: Grab the copied value.
goto clobbered;
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::None:
case ARCInstKind::IntrinsicUser:
case ARCInstKind::User:
// Weak pointers are only modified through the weak entry points
// (and arbitrary calls, which could call the weak entry points).
break;
default:
// Anything else could modify the weak pointer.
goto clobbered;
}
}
clobbered:;
}
// Then, for each destroyWeak with an alloca operand, check to see if
// the alloca and all its users can be zapped.
for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
Instruction *Inst = &*I++;
ARCInstKind Class = GetBasicARCInstKind(Inst);
if (Class != ARCInstKind::DestroyWeak)
continue;
CallInst *Call = cast<CallInst>(Inst);
Value *Arg = Call->getArgOperand(0);
if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
for (User *U : Alloca->users()) {
const Instruction *UserInst = cast<Instruction>(U);
switch (GetBasicARCInstKind(UserInst)) {
case ARCInstKind::InitWeak:
case ARCInstKind::StoreWeak:
case ARCInstKind::DestroyWeak:
continue;
default:
goto done;
}
}
Changed = true;
for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
CallInst *UserInst = cast<CallInst>(*UI++);
switch (GetBasicARCInstKind(UserInst)) {
case ARCInstKind::InitWeak:
case ARCInstKind::StoreWeak:
// These functions return their second argument.
UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
break;
case ARCInstKind::DestroyWeak:
// No return value.
break;
default:
llvm_unreachable("alloca really is used!");
}
UserInst->eraseFromParent();
}
Alloca->eraseFromParent();
done:;
}
}
}
/// Identify program paths which execute sequences of retains and releases which
/// can be eliminated.
bool ObjCARCOpt::OptimizeSequences(Function &F) {
// Releases, Retains - These are used to store the results of the main flow
// analysis. These use Value* as the key instead of Instruction* so that the
// map stays valid when we get around to rewriting code and calls get
// replaced by arguments.
DenseMap<Value *, RRInfo> Releases;
BlotMapVector<Value *, RRInfo> Retains;
// This is used during the traversal of the function to track the
// states for each identified object at each block.
DenseMap<const BasicBlock *, BBState> BBStates;
// Analyze the CFG of the function, and all instructions.
bool NestingDetected = Visit(F, BBStates, Retains, Releases);
// Transform.
bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
Releases,
F.getParent());
// Cleanup.
MultiOwnersSet.clear();
return AnyPairsCompletelyEliminated && NestingDetected;
}
/// Check if there is a dependent call earlier that does not have anything in
/// between the Retain and the call that can affect the reference count of their
/// shared pointer argument. Note that Retain need not be in BB.
static bool
HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
SmallPtrSetImpl<Instruction *> &DepInsts,
SmallPtrSetImpl<const BasicBlock *> &Visited,
ProvenanceAnalysis &PA) {
FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
DepInsts, Visited, PA);
if (DepInsts.size() != 1)
return false;
auto *Call = dyn_cast_or_null<CallInst>(*DepInsts.begin());
// Check that the pointer is the return value of the call.
if (!Call || Arg != Call)
return false;
// Check that the call is a regular call.
ARCInstKind Class = GetBasicARCInstKind(Call);
if (Class != ARCInstKind::CallOrUser && Class != ARCInstKind::Call)
return false;
return true;
}
/// Find a dependent retain that precedes the given autorelease for which there
/// is nothing in between the two instructions that can affect the ref count of
/// Arg.
static CallInst *
FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
Instruction *Autorelease,
SmallPtrSetImpl<Instruction *> &DepInsts,
SmallPtrSetImpl<const BasicBlock *> &Visited,
ProvenanceAnalysis &PA) {
FindDependencies(CanChangeRetainCount, Arg,
BB, Autorelease, DepInsts, Visited, PA);
if (DepInsts.size() != 1)
return nullptr;
auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.begin());
// Check that we found a retain with the same argument.
if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
GetArgRCIdentityRoot(Retain) != Arg) {
return nullptr;
}
return Retain;
}
/// Look for an ``autorelease'' instruction dependent on Arg such that there are
/// no instructions dependent on Arg that need a positive ref count in between
/// the autorelease and the ret.
static CallInst *
FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
ReturnInst *Ret,
SmallPtrSetImpl<Instruction *> &DepInsts,
SmallPtrSetImpl<const BasicBlock *> &V,
ProvenanceAnalysis &PA) {
FindDependencies(NeedsPositiveRetainCount, Arg,
BB, Ret, DepInsts, V, PA);
if (DepInsts.size() != 1)
return nullptr;
auto *Autorelease = dyn_cast_or_null<CallInst>(*DepInsts.begin());
if (!Autorelease)
return nullptr;
ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
if (!IsAutorelease(AutoreleaseClass))
return nullptr;
if (GetArgRCIdentityRoot(Autorelease) != Arg)
return nullptr;
return Autorelease;
}
/// Look for this pattern:
/// \code
/// %call = call i8* @something(...)
/// %2 = call i8* @objc_retain(i8* %call)
/// %3 = call i8* @objc_autorelease(i8* %2)
/// ret i8* %3
/// \endcode
/// And delete the retain and autorelease.
void ObjCARCOpt::OptimizeReturns(Function &F) {
if (!F.getReturnType()->isPointerTy())
return;
DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
SmallPtrSet<Instruction *, 4> DependingInstructions;
SmallPtrSet<const BasicBlock *, 4> Visited;
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
BasicBlock *BB = FI;
ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
if (!Ret)
continue;
const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
// Look for an ``autorelease'' instruction that is a predecessor of Ret and
// dependent on Arg such that there are no instructions dependent on Arg
// that need a positive ref count in between the autorelease and Ret.
CallInst *Autorelease =
FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
DependingInstructions, Visited,
PA);
DependingInstructions.clear();
Visited.clear();
if (!Autorelease)
continue;
CallInst *Retain =
FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
DependingInstructions, Visited, PA);
DependingInstructions.clear();
Visited.clear();
if (!Retain)
continue;
// Check that there is nothing that can affect the reference count
// between the retain and the call. Note that Retain need not be in BB.
bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
DependingInstructions,
Visited, PA);
DependingInstructions.clear();
Visited.clear();
if (!HasSafePathToCall)
continue;
// If so, we can zap the retain and autorelease.
Changed = true;
++NumRets;
DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
<< *Autorelease << "\n");
EraseInstruction(Retain);
EraseInstruction(Autorelease);
}
}
#ifndef NDEBUG
void
ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
llvm::Statistic &NumRetains =
AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
llvm::Statistic &NumReleases =
AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
Instruction *Inst = &*I++;
switch (GetBasicARCInstKind(Inst)) {
default:
break;
case ARCInstKind::Retain:
++NumRetains;
break;
case ARCInstKind::Release:
++NumReleases;
break;
}
}
}
#endif
bool ObjCARCOpt::doInitialization(Module &M) {
if (!EnableARCOpts)
return false;
// If nothing in the Module uses ARC, don't do anything.
Run = ModuleHasARC(M);
if (!Run)
return false;
// Intuitively, objc_retain and others are nocapture, however in practice
// they are not, because they return their argument value. And objc_release
// calls finalizers which can have arbitrary side effects.
MDKindCache.init(&M);
// Initialize our runtime entry point cache.
EP.init(&M);
return false;
}
bool ObjCARCOpt::runOnFunction(Function &F) {
if (!EnableARCOpts)
return false;
// If nothing in the Module uses ARC, don't do anything.
if (!Run)
return false;
Changed = false;
DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
"\n");
PA.setAA(&getAnalysis<AliasAnalysis>());
#ifndef NDEBUG
if (AreStatisticsEnabled()) {
GatherStatistics(F, false);
}
#endif
// This pass performs several distinct transformations. As a compile-time aid
// when compiling code that isn't ObjC, skip these if the relevant ObjC
// library functions aren't declared.
// Preliminary optimizations. This also computes UsedInThisFunction.
OptimizeIndividualCalls(F);
// Optimizations for weak pointers.
if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
(1 << unsigned(ARCInstKind::LoadWeakRetained)) |
(1 << unsigned(ARCInstKind::StoreWeak)) |
(1 << unsigned(ARCInstKind::InitWeak)) |
(1 << unsigned(ARCInstKind::CopyWeak)) |
(1 << unsigned(ARCInstKind::MoveWeak)) |
(1 << unsigned(ARCInstKind::DestroyWeak))))
OptimizeWeakCalls(F);
// Optimizations for retain+release pairs.
if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
(1 << unsigned(ARCInstKind::RetainRV)) |
(1 << unsigned(ARCInstKind::RetainBlock))))
if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
// Run OptimizeSequences until it either stops making changes or
// no retain+release pair nesting is detected.
while (OptimizeSequences(F)) {}
// Optimizations if objc_autorelease is used.
if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
(1 << unsigned(ARCInstKind::AutoreleaseRV))))
OptimizeReturns(F);
// Gather statistics after optimization.
#ifndef NDEBUG
if (AreStatisticsEnabled()) {
GatherStatistics(F, true);
}
#endif
DEBUG(dbgs() << "\n");
return Changed;
}
void ObjCARCOpt::releaseMemory() {
PA.clear();
}
/// @}
///
|
0 | repos/DirectXShaderCompiler/lib/Transforms | repos/DirectXShaderCompiler/lib/Transforms/ObjCARC/ObjCARC.cpp | //===-- ObjCARC.cpp -------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements common infrastructure for libLLVMObjCARCOpts.a, which
// implements several scalar transformations over the LLVM intermediate
// representation, including the C bindings for that library.
//
//===----------------------------------------------------------------------===//
#include "ObjCARC.h"
#include "llvm-c/Core.h"
#include "llvm-c/Initialization.h"
#include "llvm/InitializePasses.h"
#include "llvm/Support/CommandLine.h"
namespace llvm {
class PassRegistry;
}
using namespace llvm;
using namespace llvm::objcarc;
/// \brief A handy option to enable/disable all ARC Optimizations.
bool llvm::objcarc::EnableARCOpts;
static cl::opt<bool, true>
EnableARCOptimizations("enable-objc-arc-opts",
cl::desc("enable/disable all ARC Optimizations"),
cl::location(EnableARCOpts),
cl::init(true));
/// initializeObjCARCOptsPasses - Initialize all passes linked into the
/// ObjCARCOpts library.
void llvm::initializeObjCARCOpts(PassRegistry &Registry) {
initializeObjCARCAliasAnalysisPass(Registry);
initializeObjCARCAPElimPass(Registry);
initializeObjCARCExpandPass(Registry);
initializeObjCARCContractPass(Registry);
initializeObjCARCOptPass(Registry);
initializePAEvalPass(Registry);
}
void LLVMInitializeObjCARCOpts(LLVMPassRegistryRef R) {
initializeObjCARCOpts(*unwrap(R));
}
|
0 | repos/DirectXShaderCompiler/lib/Transforms | repos/DirectXShaderCompiler/lib/Transforms/ObjCARC/ProvenanceAnalysis.h | //===- ProvenanceAnalysis.h - ObjC ARC Optimization ---*- C++ -*-----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This file declares a special form of Alias Analysis called ``Provenance
/// Analysis''. The word ``provenance'' refers to the history of the ownership
/// of an object. Thus ``Provenance Analysis'' is an analysis which attempts to
/// use various techniques to determine if locally
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TRANSFORMS_OBJCARC_PROVENANCEANALYSIS_H
#define LLVM_LIB_TRANSFORMS_OBJCARC_PROVENANCEANALYSIS_H
#include "llvm/ADT/DenseMap.h"
namespace llvm {
class Value;
class AliasAnalysis;
class DataLayout;
class PHINode;
class SelectInst;
}
namespace llvm {
namespace objcarc {
/// \brief This is similar to BasicAliasAnalysis, and it uses many of the same
/// techniques, except it uses special ObjC-specific reasoning about pointer
/// relationships.
///
/// In this context ``Provenance'' is defined as the history of an object's
/// ownership. Thus ``Provenance Analysis'' is defined by using the notion of
/// an ``independent provenance source'' of a pointer to determine whether or
/// not two pointers have the same provenance source and thus could
/// potentially be related.
class ProvenanceAnalysis {
AliasAnalysis *AA;
typedef std::pair<const Value *, const Value *> ValuePairTy;
typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
CachedResultsTy CachedResults;
bool relatedCheck(const Value *A, const Value *B, const DataLayout &DL);
bool relatedSelect(const SelectInst *A, const Value *B);
bool relatedPHI(const PHINode *A, const Value *B);
void operator=(const ProvenanceAnalysis &) = delete;
ProvenanceAnalysis(const ProvenanceAnalysis &) = delete;
public:
ProvenanceAnalysis() {}
void setAA(AliasAnalysis *aa) { AA = aa; }
AliasAnalysis *getAA() const { return AA; }
bool related(const Value *A, const Value *B, const DataLayout &DL);
void clear() {
CachedResults.clear();
}
};
} // end namespace objcarc
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/lib/Transforms | repos/DirectXShaderCompiler/lib/Transforms/ObjCARC/PtrState.cpp | //===--- PtrState.cpp -----------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "PtrState.h"
#include "DependencyAnalysis.h"
#include "ObjCARC.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::objcarc;
#define DEBUG_TYPE "objc-arc-ptr-state"
//===----------------------------------------------------------------------===//
// Utility
//===----------------------------------------------------------------------===//
raw_ostream &llvm::objcarc::operator<<(raw_ostream &OS, const Sequence S) {
switch (S) {
case S_None:
return OS << "S_None";
case S_Retain:
return OS << "S_Retain";
case S_CanRelease:
return OS << "S_CanRelease";
case S_Use:
return OS << "S_Use";
case S_Release:
return OS << "S_Release";
case S_MovableRelease:
return OS << "S_MovableRelease";
case S_Stop:
return OS << "S_Stop";
}
llvm_unreachable("Unknown sequence type.");
}
//===----------------------------------------------------------------------===//
// Sequence
//===----------------------------------------------------------------------===//
static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
// The easy cases.
if (A == B)
return A;
if (A == S_None || B == S_None)
return S_None;
if (A > B)
std::swap(A, B);
if (TopDown) {
// Choose the side which is further along in the sequence.
if ((A == S_Retain || A == S_CanRelease) &&
(B == S_CanRelease || B == S_Use))
return B;
} else {
// Choose the side which is further along in the sequence.
if ((A == S_Use || A == S_CanRelease) &&
(B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
return A;
// If both sides are releases, choose the more conservative one.
if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
return A;
if (A == S_Release && B == S_MovableRelease)
return A;
}
return S_None;
}
//===----------------------------------------------------------------------===//
// RRInfo
//===----------------------------------------------------------------------===//
void RRInfo::clear() {
KnownSafe = false;
IsTailCallRelease = false;
ReleaseMetadata = nullptr;
Calls.clear();
ReverseInsertPts.clear();
CFGHazardAfflicted = false;
}
bool RRInfo::Merge(const RRInfo &Other) {
// Conservatively merge the ReleaseMetadata information.
if (ReleaseMetadata != Other.ReleaseMetadata)
ReleaseMetadata = nullptr;
// Conservatively merge the boolean state.
KnownSafe &= Other.KnownSafe;
IsTailCallRelease &= Other.IsTailCallRelease;
CFGHazardAfflicted |= Other.CFGHazardAfflicted;
// Merge the call sets.
Calls.insert(Other.Calls.begin(), Other.Calls.end());
// Merge the insert point sets. If there are any differences,
// that makes this a partial merge.
bool Partial = ReverseInsertPts.size() != Other.ReverseInsertPts.size();
for (Instruction *Inst : Other.ReverseInsertPts)
Partial |= ReverseInsertPts.insert(Inst).second;
return Partial;
}
//===----------------------------------------------------------------------===//
// PtrState
//===----------------------------------------------------------------------===//
void PtrState::SetKnownPositiveRefCount() {
DEBUG(dbgs() << " Setting Known Positive.\n");
KnownPositiveRefCount = true;
}
void PtrState::ClearKnownPositiveRefCount() {
DEBUG(dbgs() << " Clearing Known Positive.\n");
KnownPositiveRefCount = false;
}
void PtrState::SetSeq(Sequence NewSeq) {
DEBUG(dbgs() << " Old: " << GetSeq() << "; New: " << NewSeq << "\n");
Seq = NewSeq;
}
void PtrState::ResetSequenceProgress(Sequence NewSeq) {
DEBUG(dbgs() << " Resetting sequence progress.\n");
SetSeq(NewSeq);
Partial = false;
RRI.clear();
}
void PtrState::Merge(const PtrState &Other, bool TopDown) {
Seq = MergeSeqs(GetSeq(), Other.GetSeq(), TopDown);
KnownPositiveRefCount &= Other.KnownPositiveRefCount;
// If we're not in a sequence (anymore), drop all associated state.
if (Seq == S_None) {
Partial = false;
RRI.clear();
} else if (Partial || Other.Partial) {
// If we're doing a merge on a path that's previously seen a partial
// merge, conservatively drop the sequence, to avoid doing partial
// RR elimination. If the branch predicates for the two merge differ,
// mixing them is unsafe.
ClearSequenceProgress();
} else {
// Otherwise merge the other PtrState's RRInfo into our RRInfo. At this
// point, we know that currently we are not partial. Stash whether or not
// the merge operation caused us to undergo a partial merging of reverse
// insertion points.
Partial = RRI.Merge(Other.RRI);
}
}
//===----------------------------------------------------------------------===//
// BottomUpPtrState
//===----------------------------------------------------------------------===//
bool BottomUpPtrState::InitBottomUp(ARCMDKindCache &Cache, Instruction *I) {
// If we see two releases in a row on the same pointer. If so, make
// a note, and we'll cicle back to revisit it after we've
// hopefully eliminated the second release, which may allow us to
// eliminate the first release too.
// Theoretically we could implement removal of nested retain+release
// pairs by making PtrState hold a stack of states, but this is
// simple and avoids adding overhead for the non-nested case.
bool NestingDetected = false;
if (GetSeq() == S_Release || GetSeq() == S_MovableRelease) {
DEBUG(dbgs() << " Found nested releases (i.e. a release pair)\n");
NestingDetected = true;
}
MDNode *ReleaseMetadata =
I->getMetadata(Cache.get(ARCMDKindID::ImpreciseRelease));
Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
ResetSequenceProgress(NewSeq);
SetReleaseMetadata(ReleaseMetadata);
SetKnownSafe(HasKnownPositiveRefCount());
SetTailCallRelease(cast<CallInst>(I)->isTailCall());
InsertCall(I);
SetKnownPositiveRefCount();
return NestingDetected;
}
bool BottomUpPtrState::MatchWithRetain() {
SetKnownPositiveRefCount();
Sequence OldSeq = GetSeq();
switch (OldSeq) {
case S_Stop:
case S_Release:
case S_MovableRelease:
case S_Use:
// If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
// imprecise release, clear our reverse insertion points.
if (OldSeq != S_Use || IsTrackingImpreciseReleases())
ClearReverseInsertPts();
// FALL THROUGH
case S_CanRelease:
return true;
case S_None:
return false;
case S_Retain:
llvm_unreachable("bottom-up pointer in retain state!");
}
llvm_unreachable("Sequence unknown enum value");
}
bool BottomUpPtrState::HandlePotentialAlterRefCount(Instruction *Inst,
const Value *Ptr,
ProvenanceAnalysis &PA,
ARCInstKind Class) {
Sequence S = GetSeq();
// Check for possible releases.
if (!CanAlterRefCount(Inst, Ptr, PA, Class))
return false;
DEBUG(dbgs() << " CanAlterRefCount: Seq: " << S << "; " << *Ptr
<< "\n");
switch (S) {
case S_Use:
SetSeq(S_CanRelease);
return true;
case S_CanRelease:
case S_Release:
case S_MovableRelease:
case S_Stop:
case S_None:
return false;
case S_Retain:
llvm_unreachable("bottom-up pointer in retain state!");
}
llvm_unreachable("Sequence unknown enum value");
}
void BottomUpPtrState::HandlePotentialUse(BasicBlock *BB, Instruction *Inst,
const Value *Ptr,
ProvenanceAnalysis &PA,
ARCInstKind Class) {
// Check for possible direct uses.
switch (GetSeq()) {
case S_Release:
case S_MovableRelease:
if (CanUse(Inst, Ptr, PA, Class)) {
DEBUG(dbgs() << " CanUse: Seq: " << GetSeq() << "; " << *Ptr
<< "\n");
assert(!HasReverseInsertPts());
// If this is an invoke instruction, we're scanning it as part of
// one of its successor blocks, since we can't insert code after it
// in its own block, and we don't want to split critical edges.
if (isa<InvokeInst>(Inst))
InsertReverseInsertPt(BB->getFirstInsertionPt());
else
InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
SetSeq(S_Use);
} else if (Seq == S_Release && IsUser(Class)) {
DEBUG(dbgs() << " PreciseReleaseUse: Seq: " << GetSeq() << "; "
<< *Ptr << "\n");
// Non-movable releases depend on any possible objc pointer use.
SetSeq(S_Stop);
assert(!HasReverseInsertPts());
// As above; handle invoke specially.
if (isa<InvokeInst>(Inst))
InsertReverseInsertPt(BB->getFirstInsertionPt());
else
InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
}
break;
case S_Stop:
if (CanUse(Inst, Ptr, PA, Class)) {
DEBUG(dbgs() << " PreciseStopUse: Seq: " << GetSeq() << "; "
<< *Ptr << "\n");
SetSeq(S_Use);
}
break;
case S_CanRelease:
case S_Use:
case S_None:
break;
case S_Retain:
llvm_unreachable("bottom-up pointer in retain state!");
}
}
//===----------------------------------------------------------------------===//
// TopDownPtrState
//===----------------------------------------------------------------------===//
bool TopDownPtrState::InitTopDown(ARCInstKind Kind, Instruction *I) {
bool NestingDetected = false;
// Don't do retain+release tracking for ARCInstKind::RetainRV, because
// it's
// better to let it remain as the first instruction after a call.
if (Kind != ARCInstKind::RetainRV) {
// If we see two retains in a row on the same pointer. If so, make
// a note, and we'll cicle back to revisit it after we've
// hopefully eliminated the second retain, which may allow us to
// eliminate the first retain too.
// Theoretically we could implement removal of nested retain+release
// pairs by making PtrState hold a stack of states, but this is
// simple and avoids adding overhead for the non-nested case.
if (GetSeq() == S_Retain)
NestingDetected = true;
ResetSequenceProgress(S_Retain);
SetKnownSafe(HasKnownPositiveRefCount());
InsertCall(I);
}
SetKnownPositiveRefCount();
return NestingDetected;
}
bool TopDownPtrState::MatchWithRelease(ARCMDKindCache &Cache,
Instruction *Release) {
ClearKnownPositiveRefCount();
Sequence OldSeq = GetSeq();
MDNode *ReleaseMetadata =
Release->getMetadata(Cache.get(ARCMDKindID::ImpreciseRelease));
switch (OldSeq) {
case S_Retain:
case S_CanRelease:
if (OldSeq == S_Retain || ReleaseMetadata != nullptr)
ClearReverseInsertPts();
// FALL THROUGH
case S_Use:
SetReleaseMetadata(ReleaseMetadata);
SetTailCallRelease(cast<CallInst>(Release)->isTailCall());
return true;
case S_None:
return false;
case S_Stop:
case S_Release:
case S_MovableRelease:
llvm_unreachable("top-down pointer in bottom up state!");
}
llvm_unreachable("Sequence unknown enum value");
}
bool TopDownPtrState::HandlePotentialAlterRefCount(Instruction *Inst,
const Value *Ptr,
ProvenanceAnalysis &PA,
ARCInstKind Class) {
// Check for possible releases.
if (!CanAlterRefCount(Inst, Ptr, PA, Class))
return false;
DEBUG(dbgs() << " CanAlterRefCount: Seq: " << GetSeq() << "; " << *Ptr
<< "\n");
ClearKnownPositiveRefCount();
switch (GetSeq()) {
case S_Retain:
SetSeq(S_CanRelease);
assert(!HasReverseInsertPts());
InsertReverseInsertPt(Inst);
// One call can't cause a transition from S_Retain to S_CanRelease
// and S_CanRelease to S_Use. If we've made the first transition,
// we're done.
return true;
case S_Use:
case S_CanRelease:
case S_None:
return false;
case S_Stop:
case S_Release:
case S_MovableRelease:
llvm_unreachable("top-down pointer in release state!");
}
llvm_unreachable("covered switch is not covered!?");
}
void TopDownPtrState::HandlePotentialUse(Instruction *Inst, const Value *Ptr,
ProvenanceAnalysis &PA,
ARCInstKind Class) {
// Check for possible direct uses.
switch (GetSeq()) {
case S_CanRelease:
if (!CanUse(Inst, Ptr, PA, Class))
return;
DEBUG(dbgs() << " CanUse: Seq: " << GetSeq() << "; " << *Ptr
<< "\n");
SetSeq(S_Use);
return;
case S_Retain:
case S_Use:
case S_None:
return;
case S_Stop:
case S_Release:
case S_MovableRelease:
llvm_unreachable("top-down pointer in release state!");
}
}
|
0 | repos/DirectXShaderCompiler/lib/Transforms | repos/DirectXShaderCompiler/lib/Transforms/ObjCARC/ObjCARCContract.cpp | //===- ObjCARCContract.cpp - ObjC ARC Optimization ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file defines late ObjC ARC optimizations. ARC stands for Automatic
/// Reference Counting and is a system for managing reference counts for objects
/// in Objective C.
///
/// This specific file mainly deals with ``contracting'' multiple lower level
/// operations into singular higher level operations through pattern matching.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
// TODO: ObjCARCContract could insert PHI nodes when uses aren't
// dominated by single calls.
#include "ObjCARC.h"
#include "ARCRuntimeEntryPoints.h"
#include "DependencyAnalysis.h"
#include "ProvenanceAnalysis.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::objcarc;
#define DEBUG_TYPE "objc-arc-contract"
STATISTIC(NumPeeps, "Number of calls peephole-optimized");
STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
//===----------------------------------------------------------------------===//
// Declarations
//===----------------------------------------------------------------------===//
namespace {
/// \brief Late ARC optimizations
///
/// These change the IR in a way that makes it difficult to be analyzed by
/// ObjCARCOpt, so it's run late.
class ObjCARCContract : public FunctionPass {
bool Changed;
AliasAnalysis *AA;
DominatorTree *DT;
ProvenanceAnalysis PA;
ARCRuntimeEntryPoints EP;
/// A flag indicating whether this optimization pass should run.
bool Run;
/// The inline asm string to insert between calls and RetainRV calls to make
/// the optimization work on targets which need it.
const MDString *RetainRVMarker;
/// The set of inserted objc_storeStrong calls. If at the end of walking the
/// function we have found no alloca instructions, these calls can be marked
/// "tail".
SmallPtrSet<CallInst *, 8> StoreStrongCalls;
/// Returns true if we eliminated Inst.
bool tryToPeepholeInstruction(Function &F, Instruction *Inst,
inst_iterator &Iter,
SmallPtrSetImpl<Instruction *> &DepInsts,
SmallPtrSetImpl<const BasicBlock *> &Visited,
bool &TailOkForStoreStrong);
bool optimizeRetainCall(Function &F, Instruction *Retain);
bool
contractAutorelease(Function &F, Instruction *Autorelease,
ARCInstKind Class,
SmallPtrSetImpl<Instruction *> &DependingInstructions,
SmallPtrSetImpl<const BasicBlock *> &Visited);
void tryToContractReleaseIntoStoreStrong(Instruction *Release,
inst_iterator &Iter);
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool doInitialization(Module &M) override;
bool runOnFunction(Function &F) override;
public:
static char ID;
ObjCARCContract() : FunctionPass(ID) {
initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
}
};
}
//===----------------------------------------------------------------------===//
// Implementation
//===----------------------------------------------------------------------===//
/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
/// return value. We do this late so we do not disrupt the dataflow analysis in
/// ObjCARCOpt.
bool ObjCARCContract::optimizeRetainCall(Function &F, Instruction *Retain) {
ImmutableCallSite CS(GetArgRCIdentityRoot(Retain));
const Instruction *Call = CS.getInstruction();
if (!Call)
return false;
if (Call->getParent() != Retain->getParent())
return false;
// Check that the call is next to the retain.
BasicBlock::const_iterator I = Call;
++I;
while (IsNoopInstruction(I)) ++I;
if (&*I != Retain)
return false;
// Turn it to an objc_retainAutoreleasedReturnValue.
Changed = true;
++NumPeeps;
DEBUG(dbgs() << "Transforming objc_retain => "
"objc_retainAutoreleasedReturnValue since the operand is a "
"return value.\nOld: "<< *Retain << "\n");
// We do not have to worry about tail calls/does not throw since
// retain/retainRV have the same properties.
Constant *Decl = EP.get(ARCRuntimeEntryPointKind::RetainRV);
cast<CallInst>(Retain)->setCalledFunction(Decl);
DEBUG(dbgs() << "New: " << *Retain << "\n");
return true;
}
/// Merge an autorelease with a retain into a fused call.
bool ObjCARCContract::contractAutorelease(
Function &F, Instruction *Autorelease, ARCInstKind Class,
SmallPtrSetImpl<Instruction *> &DependingInstructions,
SmallPtrSetImpl<const BasicBlock *> &Visited) {
const Value *Arg = GetArgRCIdentityRoot(Autorelease);
// Check that there are no instructions between the retain and the autorelease
// (such as an autorelease_pop) which may change the count.
CallInst *Retain = nullptr;
if (Class == ARCInstKind::AutoreleaseRV)
FindDependencies(RetainAutoreleaseRVDep, Arg,
Autorelease->getParent(), Autorelease,
DependingInstructions, Visited, PA);
else
FindDependencies(RetainAutoreleaseDep, Arg,
Autorelease->getParent(), Autorelease,
DependingInstructions, Visited, PA);
Visited.clear();
if (DependingInstructions.size() != 1) {
DependingInstructions.clear();
return false;
}
Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
DependingInstructions.clear();
if (!Retain || GetBasicARCInstKind(Retain) != ARCInstKind::Retain ||
GetArgRCIdentityRoot(Retain) != Arg)
return false;
Changed = true;
++NumPeeps;
DEBUG(dbgs() << " Fusing retain/autorelease!\n"
" Autorelease:" << *Autorelease << "\n"
" Retain: " << *Retain << "\n");
Constant *Decl = EP.get(Class == ARCInstKind::AutoreleaseRV
? ARCRuntimeEntryPointKind::RetainAutoreleaseRV
: ARCRuntimeEntryPointKind::RetainAutorelease);
Retain->setCalledFunction(Decl);
DEBUG(dbgs() << " New RetainAutorelease: " << *Retain << "\n");
EraseInstruction(Autorelease);
return true;
}
static StoreInst *findSafeStoreForStoreStrongContraction(LoadInst *Load,
Instruction *Release,
ProvenanceAnalysis &PA,
AliasAnalysis *AA) {
StoreInst *Store = nullptr;
bool SawRelease = false;
// Get the location associated with Load.
MemoryLocation Loc = MemoryLocation::get(Load);
// Walk down to find the store and the release, which may be in either order.
for (auto I = std::next(BasicBlock::iterator(Load)),
E = Load->getParent()->end();
I != E; ++I) {
// If we found the store we were looking for and saw the release,
// break. There is no more work to be done.
if (Store && SawRelease)
break;
// Now we know that we have not seen either the store or the release. If I
// is the release, mark that we saw the release and continue.
Instruction *Inst = &*I;
if (Inst == Release) {
SawRelease = true;
continue;
}
// Otherwise, we check if Inst is a "good" store. Grab the instruction class
// of Inst.
ARCInstKind Class = GetBasicARCInstKind(Inst);
// If Inst is an unrelated retain, we don't care about it.
//
// TODO: This is one area where the optimization could be made more
// aggressive.
if (IsRetain(Class))
continue;
// If we have seen the store, but not the release...
if (Store) {
// We need to make sure that it is safe to move the release from its
// current position to the store. This implies proving that any
// instruction in between Store and the Release conservatively can not use
// the RCIdentityRoot of Release. If we can prove we can ignore Inst, so
// continue...
if (!CanUse(Inst, Load, PA, Class)) {
continue;
}
// Otherwise, be conservative and return nullptr.
return nullptr;
}
// Ok, now we know we have not seen a store yet. See if Inst can write to
// our load location, if it can not, just ignore the instruction.
if (!(AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod))
continue;
Store = dyn_cast<StoreInst>(Inst);
// If Inst can, then check if Inst is a simple store. If Inst is not a
// store or a store that is not simple, then we have some we do not
// understand writing to this memory implying we can not move the load
// over the write to any subsequent store that we may find.
if (!Store || !Store->isSimple())
return nullptr;
// Then make sure that the pointer we are storing to is Ptr. If so, we
// found our Store!
if (Store->getPointerOperand() == Loc.Ptr)
continue;
// Otherwise, we have an unknown store to some other ptr that clobbers
// Loc.Ptr. Bail!
return nullptr;
}
// If we did not find the store or did not see the release, fail.
if (!Store || !SawRelease)
return nullptr;
// We succeeded!
return Store;
}
static Instruction *
findRetainForStoreStrongContraction(Value *New, StoreInst *Store,
Instruction *Release,
ProvenanceAnalysis &PA) {
// Walk up from the Store to find the retain.
BasicBlock::iterator I = Store;
BasicBlock::iterator Begin = Store->getParent()->begin();
while (I != Begin && GetBasicARCInstKind(I) != ARCInstKind::Retain) {
Instruction *Inst = &*I;
// It is only safe to move the retain to the store if we can prove
// conservatively that nothing besides the release can decrement reference
// counts in between the retain and the store.
if (CanDecrementRefCount(Inst, New, PA) && Inst != Release)
return nullptr;
--I;
}
Instruction *Retain = I;
if (GetBasicARCInstKind(Retain) != ARCInstKind::Retain)
return nullptr;
if (GetArgRCIdentityRoot(Retain) != New)
return nullptr;
return Retain;
}
/// Attempt to merge an objc_release with a store, load, and objc_retain to form
/// an objc_storeStrong. An objc_storeStrong:
///
/// objc_storeStrong(i8** %old_ptr, i8* new_value)
///
/// is equivalent to the following IR sequence:
///
/// ; Load old value.
/// %old_value = load i8** %old_ptr (1)
///
/// ; Increment the new value and then release the old value. This must occur
/// ; in order in case old_value releases new_value in its destructor causing
/// ; us to potentially have a dangling ptr.
/// tail call i8* @objc_retain(i8* %new_value) (2)
/// tail call void @objc_release(i8* %old_value) (3)
///
/// ; Store the new_value into old_ptr
/// store i8* %new_value, i8** %old_ptr (4)
///
/// The safety of this optimization is based around the following
/// considerations:
///
/// 1. We are forming the store strong at the store. Thus to perform this
/// optimization it must be safe to move the retain, load, and release to
/// (4).
/// 2. We need to make sure that any re-orderings of (1), (2), (3), (4) are
/// safe.
void ObjCARCContract::tryToContractReleaseIntoStoreStrong(Instruction *Release,
inst_iterator &Iter) {
// See if we are releasing something that we just loaded.
auto *Load = dyn_cast<LoadInst>(GetArgRCIdentityRoot(Release));
if (!Load || !Load->isSimple())
return;
// For now, require everything to be in one basic block.
BasicBlock *BB = Release->getParent();
if (Load->getParent() != BB)
return;
// First scan down the BB from Load, looking for a store of the RCIdentityRoot
// of Load's
StoreInst *Store =
findSafeStoreForStoreStrongContraction(Load, Release, PA, AA);
// If we fail, bail.
if (!Store)
return;
// Then find what new_value's RCIdentity Root is.
Value *New = GetRCIdentityRoot(Store->getValueOperand());
// Then walk up the BB and look for a retain on New without any intervening
// instructions which conservatively might decrement ref counts.
Instruction *Retain =
findRetainForStoreStrongContraction(New, Store, Release, PA);
// If we fail, bail.
if (!Retain)
return;
Changed = true;
++NumStoreStrongs;
DEBUG(
llvm::dbgs() << " Contracting retain, release into objc_storeStrong.\n"
<< " Old:\n"
<< " Store: " << *Store << "\n"
<< " Release: " << *Release << "\n"
<< " Retain: " << *Retain << "\n"
<< " Load: " << *Load << "\n");
LLVMContext &C = Release->getContext();
Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Type *I8XX = PointerType::getUnqual(I8X);
Value *Args[] = { Load->getPointerOperand(), New };
if (Args[0]->getType() != I8XX)
Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
if (Args[1]->getType() != I8X)
Args[1] = new BitCastInst(Args[1], I8X, "", Store);
Constant *Decl = EP.get(ARCRuntimeEntryPointKind::StoreStrong);
CallInst *StoreStrong = CallInst::Create(Decl, Args, "", Store);
StoreStrong->setDoesNotThrow();
StoreStrong->setDebugLoc(Store->getDebugLoc());
// We can't set the tail flag yet, because we haven't yet determined
// whether there are any escaping allocas. Remember this call, so that
// we can set the tail flag once we know it's safe.
StoreStrongCalls.insert(StoreStrong);
DEBUG(llvm::dbgs() << " New Store Strong: " << *StoreStrong << "\n");
if (&*Iter == Store) ++Iter;
Store->eraseFromParent();
Release->eraseFromParent();
EraseInstruction(Retain);
if (Load->use_empty())
Load->eraseFromParent();
}
bool ObjCARCContract::tryToPeepholeInstruction(
Function &F, Instruction *Inst, inst_iterator &Iter,
SmallPtrSetImpl<Instruction *> &DependingInsts,
SmallPtrSetImpl<const BasicBlock *> &Visited,
bool &TailOkForStoreStrongs) {
// Only these library routines return their argument. In particular,
// objc_retainBlock does not necessarily return its argument.
ARCInstKind Class = GetBasicARCInstKind(Inst);
switch (Class) {
case ARCInstKind::FusedRetainAutorelease:
case ARCInstKind::FusedRetainAutoreleaseRV:
return false;
case ARCInstKind::Autorelease:
case ARCInstKind::AutoreleaseRV:
return contractAutorelease(F, Inst, Class, DependingInsts, Visited);
case ARCInstKind::Retain:
// Attempt to convert retains to retainrvs if they are next to function
// calls.
if (!optimizeRetainCall(F, Inst))
return false;
// If we succeed in our optimization, fall through.
// FALLTHROUGH
case ARCInstKind::RetainRV: {
// If we're compiling for a target which needs a special inline-asm
// marker to do the retainAutoreleasedReturnValue optimization,
// insert it now.
if (!RetainRVMarker)
return false;
BasicBlock::iterator BBI = Inst;
BasicBlock *InstParent = Inst->getParent();
// Step up to see if the call immediately precedes the RetainRV call.
// If it's an invoke, we have to cross a block boundary. And we have
// to carefully dodge no-op instructions.
do {
if (&*BBI == InstParent->begin()) {
BasicBlock *Pred = InstParent->getSinglePredecessor();
if (!Pred)
goto decline_rv_optimization;
BBI = Pred->getTerminator();
break;
}
--BBI;
} while (IsNoopInstruction(BBI));
if (&*BBI == GetArgRCIdentityRoot(Inst)) {
DEBUG(dbgs() << "Adding inline asm marker for "
"retainAutoreleasedReturnValue optimization.\n");
Changed = true;
InlineAsm *IA =
InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
/*isVarArg=*/false),
RetainRVMarker->getString(),
/*Constraints=*/"", /*hasSideEffects=*/true);
CallInst::Create(IA, "", Inst);
}
decline_rv_optimization:
return false;
}
case ARCInstKind::InitWeak: {
// objc_initWeak(p, null) => *p = null
CallInst *CI = cast<CallInst>(Inst);
if (IsNullOrUndef(CI->getArgOperand(1))) {
Value *Null =
ConstantPointerNull::get(cast<PointerType>(CI->getType()));
Changed = true;
new StoreInst(Null, CI->getArgOperand(0), CI);
DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
<< " New = " << *Null << "\n");
CI->replaceAllUsesWith(Null);
CI->eraseFromParent();
}
return true;
}
case ARCInstKind::Release:
// Try to form an objc store strong from our release. If we fail, there is
// nothing further to do below, so continue.
tryToContractReleaseIntoStoreStrong(Inst, Iter);
return true;
case ARCInstKind::User:
// Be conservative if the function has any alloca instructions.
// Technically we only care about escaping alloca instructions,
// but this is sufficient to handle some interesting cases.
if (isa<AllocaInst>(Inst))
TailOkForStoreStrongs = false;
return true;
case ARCInstKind::IntrinsicUser:
// Remove calls to @clang.arc.use(...).
Inst->eraseFromParent();
return true;
default:
return true;
}
}
//===----------------------------------------------------------------------===//
// Top Level Driver
//===----------------------------------------------------------------------===//
bool ObjCARCContract::runOnFunction(Function &F) {
if (!EnableARCOpts)
return false;
// If nothing in the Module uses ARC, don't do anything.
if (!Run)
return false;
Changed = false;
AA = &getAnalysis<AliasAnalysis>();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
PA.setAA(&getAnalysis<AliasAnalysis>());
DEBUG(llvm::dbgs() << "**** ObjCARC Contract ****\n");
// Track whether it's ok to mark objc_storeStrong calls with the "tail"
// keyword. Be conservative if the function has variadic arguments.
// It seems that functions which "return twice" are also unsafe for the
// "tail" argument, because they are setjmp, which could need to
// return to an earlier stack state.
bool TailOkForStoreStrongs =
!F.isVarArg() && !F.callsFunctionThatReturnsTwice();
// For ObjC library calls which return their argument, replace uses of the
// argument with uses of the call return value, if it dominates the use. This
// reduces register pressure.
SmallPtrSet<Instruction *, 4> DependingInstructions;
SmallPtrSet<const BasicBlock *, 4> Visited;
for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E;) {
Instruction *Inst = &*I++;
DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
// First try to peephole Inst. If there is nothing further we can do in
// terms of undoing objc-arc-expand, process the next inst.
if (tryToPeepholeInstruction(F, Inst, I, DependingInstructions, Visited,
TailOkForStoreStrongs))
continue;
// Otherwise, try to undo objc-arc-expand.
// Don't use GetArgRCIdentityRoot because we don't want to look through bitcasts
// and such; to do the replacement, the argument must have type i8*.
Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
// TODO: Change this to a do-while.
for (;;) {
// If we're compiling bugpointed code, don't get in trouble.
if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
break;
// Look through the uses of the pointer.
for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
UI != UE; ) {
// Increment UI now, because we may unlink its element.
Use &U = *UI++;
unsigned OperandNo = U.getOperandNo();
// If the call's return value dominates a use of the call's argument
// value, rewrite the use to use the return value. We check for
// reachability here because an unreachable call is considered to
// trivially dominate itself, which would lead us to rewriting its
// argument in terms of its return value, which would lead to
// infinite loops in GetArgRCIdentityRoot.
if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Changed = true;
Instruction *Replacement = Inst;
Type *UseTy = U.get()->getType();
if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
// For PHI nodes, insert the bitcast in the predecessor block.
unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
BasicBlock *BB = PHI->getIncomingBlock(ValNo);
if (Replacement->getType() != UseTy)
Replacement = new BitCastInst(Replacement, UseTy, "",
&BB->back());
// While we're here, rewrite all edges for this PHI, rather
// than just one use at a time, to minimize the number of
// bitcasts we emit.
for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
if (PHI->getIncomingBlock(i) == BB) {
// Keep the UI iterator valid.
if (UI != UE &&
&PHI->getOperandUse(
PHINode::getOperandNumForIncomingValue(i)) == &*UI)
++UI;
PHI->setIncomingValue(i, Replacement);
}
} else {
if (Replacement->getType() != UseTy)
Replacement = new BitCastInst(Replacement, UseTy, "",
cast<Instruction>(U.getUser()));
U.set(Replacement);
}
}
}
// If Arg is a no-op casted pointer, strip one level of casts and iterate.
if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
Arg = BI->getOperand(0);
else if (isa<GEPOperator>(Arg) &&
cast<GEPOperator>(Arg)->hasAllZeroIndices())
Arg = cast<GEPOperator>(Arg)->getPointerOperand();
else if (isa<GlobalAlias>(Arg) &&
!cast<GlobalAlias>(Arg)->mayBeOverridden())
Arg = cast<GlobalAlias>(Arg)->getAliasee();
else
break;
}
}
// If this function has no escaping allocas or suspicious vararg usage,
// objc_storeStrong calls can be marked with the "tail" keyword.
if (TailOkForStoreStrongs)
for (CallInst *CI : StoreStrongCalls)
CI->setTailCall();
StoreStrongCalls.clear();
return Changed;
}
//===----------------------------------------------------------------------===//
// Misc Pass Manager
//===----------------------------------------------------------------------===//
char ObjCARCContract::ID = 0;
INITIALIZE_PASS_BEGIN(ObjCARCContract, "objc-arc-contract",
"ObjC ARC contraction", false, false)
INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_END(ObjCARCContract, "objc-arc-contract",
"ObjC ARC contraction", false, false)
void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<AliasAnalysis>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.setPreservesCFG();
}
Pass *llvm::createObjCARCContractPass() { return new ObjCARCContract(); }
bool ObjCARCContract::doInitialization(Module &M) {
// If nothing in the Module uses ARC, don't do anything.
Run = ModuleHasARC(M);
if (!Run)
return false;
EP.init(&M);
// Initialize RetainRVMarker.
RetainRVMarker = nullptr;
if (NamedMDNode *NMD =
M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
if (NMD->getNumOperands() == 1) {
const MDNode *N = NMD->getOperand(0);
if (N->getNumOperands() == 1)
if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
RetainRVMarker = S;
}
return false;
}
|
0 | repos/DirectXShaderCompiler/lib/Transforms | repos/DirectXShaderCompiler/lib/Transforms/ObjCARC/ARCRuntimeEntryPoints.h | //===- ARCRuntimeEntryPoints.h - ObjC ARC Optimization --*- C++ -*---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file contains a class ARCRuntimeEntryPoints for use in
/// creating/managing references to entry points to the arc objective c runtime.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TRANSFORMS_OBJCARC_ARCRUNTIMEENTRYPOINTS_H
#define LLVM_LIB_TRANSFORMS_OBJCARC_ARCRUNTIMEENTRYPOINTS_H
#include "ObjCARC.h"
namespace llvm {
namespace objcarc {
enum class ARCRuntimeEntryPointKind {
AutoreleaseRV,
Release,
Retain,
RetainBlock,
Autorelease,
StoreStrong,
RetainRV,
RetainAutorelease,
RetainAutoreleaseRV,
};
/// Declarations for ObjC runtime functions and constants. These are initialized
/// lazily to avoid cluttering up the Module with unused declarations.
class ARCRuntimeEntryPoints {
public:
ARCRuntimeEntryPoints() : TheModule(nullptr),
AutoreleaseRV(nullptr),
Release(nullptr),
Retain(nullptr),
RetainBlock(nullptr),
Autorelease(nullptr),
StoreStrong(nullptr),
RetainRV(nullptr),
RetainAutorelease(nullptr),
RetainAutoreleaseRV(nullptr) { }
void init(Module *M) {
TheModule = M;
AutoreleaseRV = nullptr;
Release = nullptr;
Retain = nullptr;
RetainBlock = nullptr;
Autorelease = nullptr;
StoreStrong = nullptr;
RetainRV = nullptr;
RetainAutorelease = nullptr;
RetainAutoreleaseRV = nullptr;
}
Constant *get(ARCRuntimeEntryPointKind kind) {
assert(TheModule != nullptr && "Not initialized.");
switch (kind) {
case ARCRuntimeEntryPointKind::AutoreleaseRV:
return getI8XRetI8XEntryPoint(AutoreleaseRV,
"objc_autoreleaseReturnValue", true);
case ARCRuntimeEntryPointKind::Release:
return getVoidRetI8XEntryPoint(Release, "objc_release");
case ARCRuntimeEntryPointKind::Retain:
return getI8XRetI8XEntryPoint(Retain, "objc_retain", true);
case ARCRuntimeEntryPointKind::RetainBlock:
return getI8XRetI8XEntryPoint(RetainBlock, "objc_retainBlock", false);
case ARCRuntimeEntryPointKind::Autorelease:
return getI8XRetI8XEntryPoint(Autorelease, "objc_autorelease", true);
case ARCRuntimeEntryPointKind::StoreStrong:
return getI8XRetI8XXI8XEntryPoint(StoreStrong, "objc_storeStrong");
case ARCRuntimeEntryPointKind::RetainRV:
return getI8XRetI8XEntryPoint(RetainRV,
"objc_retainAutoreleasedReturnValue", true);
case ARCRuntimeEntryPointKind::RetainAutorelease:
return getI8XRetI8XEntryPoint(RetainAutorelease, "objc_retainAutorelease",
true);
case ARCRuntimeEntryPointKind::RetainAutoreleaseRV:
return getI8XRetI8XEntryPoint(RetainAutoreleaseRV,
"objc_retainAutoreleaseReturnValue", true);
}
llvm_unreachable("Switch should be a covered switch.");
}
private:
/// Cached reference to the module which we will insert declarations into.
Module *TheModule;
/// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
Constant *AutoreleaseRV;
/// Declaration for ObjC runtime function objc_release.
Constant *Release;
/// Declaration for ObjC runtime function objc_retain.
Constant *Retain;
/// Declaration for ObjC runtime function objc_retainBlock.
Constant *RetainBlock;
/// Declaration for ObjC runtime function objc_autorelease.
Constant *Autorelease;
/// Declaration for objc_storeStrong().
Constant *StoreStrong;
/// Declaration for objc_retainAutoreleasedReturnValue().
Constant *RetainRV;
/// Declaration for objc_retainAutorelease().
Constant *RetainAutorelease;
/// Declaration for objc_retainAutoreleaseReturnValue().
Constant *RetainAutoreleaseRV;
Constant *getVoidRetI8XEntryPoint(Constant *&Decl,
const char *Name) {
if (Decl)
return Decl;
LLVMContext &C = TheModule->getContext();
Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
AttributeSet Attr =
AttributeSet().addAttribute(C, AttributeSet::FunctionIndex,
Attribute::NoUnwind);
FunctionType *Fty = FunctionType::get(Type::getVoidTy(C), Params,
/*isVarArg=*/false);
return Decl = TheModule->getOrInsertFunction(Name, Fty, Attr);
}
Constant *getI8XRetI8XEntryPoint(Constant *& Decl,
const char *Name,
bool NoUnwind = false) {
if (Decl)
return Decl;
LLVMContext &C = TheModule->getContext();
Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Type *Params[] = { I8X };
FunctionType *Fty = FunctionType::get(I8X, Params, /*isVarArg=*/false);
AttributeSet Attr = AttributeSet();
if (NoUnwind)
Attr = Attr.addAttribute(C, AttributeSet::FunctionIndex,
Attribute::NoUnwind);
return Decl = TheModule->getOrInsertFunction(Name, Fty, Attr);
}
Constant *getI8XRetI8XXI8XEntryPoint(Constant *&Decl,
const char *Name) {
if (Decl)
return Decl;
LLVMContext &C = TheModule->getContext();
Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Type *I8XX = PointerType::getUnqual(I8X);
Type *Params[] = { I8XX, I8X };
AttributeSet Attr =
AttributeSet().addAttribute(C, AttributeSet::FunctionIndex,
Attribute::NoUnwind);
Attr = Attr.addAttribute(C, 1, Attribute::NoCapture);
FunctionType *Fty = FunctionType::get(Type::getVoidTy(C), Params,
/*isVarArg=*/false);
return Decl = TheModule->getOrInsertFunction(Name, Fty, Attr);
}
}; // class ARCRuntimeEntryPoints
} // namespace objcarc
} // namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/lib/Transforms | repos/DirectXShaderCompiler/lib/Transforms/ObjCARC/BlotMapVector.h | //===- BlotMapVector.h - A MapVector with the blot operation -*- C++ -*----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/DenseMap.h"
#include <vector>
#include <algorithm>
namespace llvm {
/// \brief An associative container with fast insertion-order (deterministic)
/// iteration over its elements. Plus the special blot operation.
template <class KeyT, class ValueT> class BlotMapVector {
/// Map keys to indices in Vector.
typedef DenseMap<KeyT, size_t> MapTy;
MapTy Map;
typedef std::vector<std::pair<KeyT, ValueT>> VectorTy;
/// Keys and values.
VectorTy Vector;
public:
typedef typename VectorTy::iterator iterator;
typedef typename VectorTy::const_iterator const_iterator;
iterator begin() { return Vector.begin(); }
iterator end() { return Vector.end(); }
const_iterator begin() const { return Vector.begin(); }
const_iterator end() const { return Vector.end(); }
#ifdef XDEBUG
~BlotMapVector() {
assert(Vector.size() >= Map.size()); // May differ due to blotting.
for (typename MapTy::const_iterator I = Map.begin(), E = Map.end(); I != E;
++I) {
assert(I->second < Vector.size());
assert(Vector[I->second].first == I->first);
}
for (typename VectorTy::const_iterator I = Vector.begin(), E = Vector.end();
I != E; ++I)
assert(!I->first || (Map.count(I->first) &&
Map[I->first] == size_t(I - Vector.begin())));
}
#endif
ValueT &operator[](const KeyT &Arg) {
std::pair<typename MapTy::iterator, bool> Pair =
Map.insert(std::make_pair(Arg, size_t(0)));
if (Pair.second) {
size_t Num = Vector.size();
Pair.first->second = Num;
Vector.push_back(std::make_pair(Arg, ValueT()));
return Vector[Num].second;
}
return Vector[Pair.first->second].second;
}
std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &InsertPair) {
std::pair<typename MapTy::iterator, bool> Pair =
Map.insert(std::make_pair(InsertPair.first, size_t(0)));
if (Pair.second) {
size_t Num = Vector.size();
Pair.first->second = Num;
Vector.push_back(InsertPair);
return std::make_pair(Vector.begin() + Num, true);
}
return std::make_pair(Vector.begin() + Pair.first->second, false);
}
iterator find(const KeyT &Key) {
typename MapTy::iterator It = Map.find(Key);
if (It == Map.end())
return Vector.end();
return Vector.begin() + It->second;
}
const_iterator find(const KeyT &Key) const {
typename MapTy::const_iterator It = Map.find(Key);
if (It == Map.end())
return Vector.end();
return Vector.begin() + It->second;
}
/// This is similar to erase, but instead of removing the element from the
/// vector, it just zeros out the key in the vector. This leaves iterators
/// intact, but clients must be prepared for zeroed-out keys when iterating.
void blot(const KeyT &Key) {
typename MapTy::iterator It = Map.find(Key);
if (It == Map.end())
return;
Vector[It->second].first = KeyT();
Map.erase(It);
}
void clear() {
Map.clear();
Vector.clear();
}
bool empty() const {
assert(Map.empty() == Vector.empty());
return Map.empty();
}
};
} //
|
0 | repos/DirectXShaderCompiler/lib/Transforms | repos/DirectXShaderCompiler/lib/Transforms/ObjCARC/PtrState.h | //===--- PtrState.h - ARC State for a Ptr -------------------*- C++ -*-----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains declarations for the ARC state associated with a ptr. It
// is only used by the ARC Sequence Dataflow computation. By separating this
// from the actual dataflow, it is easier to consider the mechanics of the ARC
// optimization separate from the actual predicates being used.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TRANSFORMS_OBJCARC_PTRSTATE_H
#define LLVM_LIB_TRANSFORMS_OBJCARC_PTRSTATE_H
#include "ARCInstKind.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Debug.h"
namespace llvm {
namespace objcarc {
class ARCMDKindCache;
class ProvenanceAnalysis;
/// \enum Sequence
///
/// \brief A sequence of states that a pointer may go through in which an
/// objc_retain and objc_release are actually needed.
enum Sequence {
S_None,
S_Retain, ///< objc_retain(x).
S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
S_Use, ///< any use of x.
S_Stop, ///< like S_Release, but code motion is stopped.
S_Release, ///< objc_release(x).
S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
};
raw_ostream &operator<<(raw_ostream &OS,
const Sequence S) LLVM_ATTRIBUTE_UNUSED;
/// \brief Unidirectional information about either a
/// retain-decrement-use-release sequence or release-use-decrement-retain
/// reverse sequence.
struct RRInfo {
/// After an objc_retain, the reference count of the referenced
/// object is known to be positive. Similarly, before an objc_release, the
/// reference count of the referenced object is known to be positive. If
/// there are retain-release pairs in code regions where the retain count
/// is known to be positive, they can be eliminated, regardless of any side
/// effects between them.
///
/// Also, a retain+release pair nested within another retain+release
/// pair all on the known same pointer value can be eliminated, regardless
/// of any intervening side effects.
///
/// KnownSafe is true when either of these conditions is satisfied.
bool KnownSafe;
/// True of the objc_release calls are all marked with the "tail" keyword.
bool IsTailCallRelease;
/// If the Calls are objc_release calls and they all have a
/// clang.imprecise_release tag, this is the metadata tag.
MDNode *ReleaseMetadata;
/// For a top-down sequence, the set of objc_retains or
/// objc_retainBlocks. For bottom-up, the set of objc_releases.
SmallPtrSet<Instruction *, 2> Calls;
/// The set of optimal insert positions for moving calls in the opposite
/// sequence.
SmallPtrSet<Instruction *, 2> ReverseInsertPts;
/// If this is true, we cannot perform code motion but can still remove
/// retain/release pairs.
bool CFGHazardAfflicted;
RRInfo()
: KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(nullptr),
CFGHazardAfflicted(false) {}
void clear();
/// Conservatively merge the two RRInfo. Returns true if a partial merge has
/// occurred, false otherwise.
bool Merge(const RRInfo &Other);
};
/// \brief This class summarizes several per-pointer runtime properties which
/// are propogated through the flow graph.
class PtrState {
protected:
/// True if the reference count is known to be incremented.
bool KnownPositiveRefCount;
/// True if we've seen an opportunity for partial RR elimination, such as
/// pushing calls into a CFG triangle or into one side of a CFG diamond.
bool Partial;
/// The current position in the sequence.
unsigned char Seq : 8;
/// Unidirectional information about the current sequence.
RRInfo RRI;
PtrState() : KnownPositiveRefCount(false), Partial(false), Seq(S_None) {}
public:
bool IsKnownSafe() const { return RRI.KnownSafe; }
void SetKnownSafe(const bool NewValue) { RRI.KnownSafe = NewValue; }
bool IsTailCallRelease() const { return RRI.IsTailCallRelease; }
void SetTailCallRelease(const bool NewValue) {
RRI.IsTailCallRelease = NewValue;
}
bool IsTrackingImpreciseReleases() const {
return RRI.ReleaseMetadata != nullptr;
}
const MDNode *GetReleaseMetadata() const { return RRI.ReleaseMetadata; }
void SetReleaseMetadata(MDNode *NewValue) { RRI.ReleaseMetadata = NewValue; }
bool IsCFGHazardAfflicted() const { return RRI.CFGHazardAfflicted; }
void SetCFGHazardAfflicted(const bool NewValue) {
RRI.CFGHazardAfflicted = NewValue;
}
void SetKnownPositiveRefCount();
void ClearKnownPositiveRefCount();
bool HasKnownPositiveRefCount() const { return KnownPositiveRefCount; }
void SetSeq(Sequence NewSeq);
Sequence GetSeq() const { return static_cast<Sequence>(Seq); }
void ClearSequenceProgress() { ResetSequenceProgress(S_None); }
void ResetSequenceProgress(Sequence NewSeq);
void Merge(const PtrState &Other, bool TopDown);
void InsertCall(Instruction *I) { RRI.Calls.insert(I); }
void InsertReverseInsertPt(Instruction *I) { RRI.ReverseInsertPts.insert(I); }
void ClearReverseInsertPts() { RRI.ReverseInsertPts.clear(); }
bool HasReverseInsertPts() const { return !RRI.ReverseInsertPts.empty(); }
const RRInfo &GetRRInfo() const { return RRI; }
};
struct BottomUpPtrState : PtrState {
BottomUpPtrState() : PtrState() {}
/// (Re-)Initialize this bottom up pointer returning true if we detected a
/// pointer with nested releases.
bool InitBottomUp(ARCMDKindCache &Cache, Instruction *I);
/// Return true if this set of releases can be paired with a release. Modifies
/// state appropriately to reflect that the matching occured if it is
/// successful.
///
/// It is assumed that one has already checked that the RCIdentity of the
/// retain and the RCIdentity of this ptr state are the same.
bool MatchWithRetain();
void HandlePotentialUse(BasicBlock *BB, Instruction *Inst, const Value *Ptr,
ProvenanceAnalysis &PA, ARCInstKind Class);
bool HandlePotentialAlterRefCount(Instruction *Inst, const Value *Ptr,
ProvenanceAnalysis &PA, ARCInstKind Class);
};
struct TopDownPtrState : PtrState {
TopDownPtrState() : PtrState() {}
/// (Re-)Initialize this bottom up pointer returning true if we detected a
/// pointer with nested releases.
bool InitTopDown(ARCInstKind Kind, Instruction *I);
/// Return true if this set of retains can be paired with the given
/// release. Modifies state appropriately to reflect that the matching
/// occured.
bool MatchWithRelease(ARCMDKindCache &Cache, Instruction *Release);
void HandlePotentialUse(Instruction *Inst, const Value *Ptr,
ProvenanceAnalysis &PA, ARCInstKind Class);
bool HandlePotentialAlterRefCount(Instruction *Inst, const Value *Ptr,
ProvenanceAnalysis &PA, ARCInstKind Class);
};
} // end namespace objcarc
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/lib/Transforms | repos/DirectXShaderCompiler/lib/Transforms/ObjCARC/ARCInstKind.cpp | //===- ARCInstKind.cpp - ObjC ARC Optimization ----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file defines several utility functions used by various ARC
/// optimizations which are IMHO too big to be in a header file.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
#include "ObjCARC.h"
#include "llvm/IR/Intrinsics.h"
using namespace llvm;
using namespace llvm::objcarc;
raw_ostream &llvm::objcarc::operator<<(raw_ostream &OS,
const ARCInstKind Class) {
switch (Class) {
case ARCInstKind::Retain:
return OS << "ARCInstKind::Retain";
case ARCInstKind::RetainRV:
return OS << "ARCInstKind::RetainRV";
case ARCInstKind::RetainBlock:
return OS << "ARCInstKind::RetainBlock";
case ARCInstKind::Release:
return OS << "ARCInstKind::Release";
case ARCInstKind::Autorelease:
return OS << "ARCInstKind::Autorelease";
case ARCInstKind::AutoreleaseRV:
return OS << "ARCInstKind::AutoreleaseRV";
case ARCInstKind::AutoreleasepoolPush:
return OS << "ARCInstKind::AutoreleasepoolPush";
case ARCInstKind::AutoreleasepoolPop:
return OS << "ARCInstKind::AutoreleasepoolPop";
case ARCInstKind::NoopCast:
return OS << "ARCInstKind::NoopCast";
case ARCInstKind::FusedRetainAutorelease:
return OS << "ARCInstKind::FusedRetainAutorelease";
case ARCInstKind::FusedRetainAutoreleaseRV:
return OS << "ARCInstKind::FusedRetainAutoreleaseRV";
case ARCInstKind::LoadWeakRetained:
return OS << "ARCInstKind::LoadWeakRetained";
case ARCInstKind::StoreWeak:
return OS << "ARCInstKind::StoreWeak";
case ARCInstKind::InitWeak:
return OS << "ARCInstKind::InitWeak";
case ARCInstKind::LoadWeak:
return OS << "ARCInstKind::LoadWeak";
case ARCInstKind::MoveWeak:
return OS << "ARCInstKind::MoveWeak";
case ARCInstKind::CopyWeak:
return OS << "ARCInstKind::CopyWeak";
case ARCInstKind::DestroyWeak:
return OS << "ARCInstKind::DestroyWeak";
case ARCInstKind::StoreStrong:
return OS << "ARCInstKind::StoreStrong";
case ARCInstKind::CallOrUser:
return OS << "ARCInstKind::CallOrUser";
case ARCInstKind::Call:
return OS << "ARCInstKind::Call";
case ARCInstKind::User:
return OS << "ARCInstKind::User";
case ARCInstKind::IntrinsicUser:
return OS << "ARCInstKind::IntrinsicUser";
case ARCInstKind::None:
return OS << "ARCInstKind::None";
}
llvm_unreachable("Unknown instruction class!");
}
ARCInstKind llvm::objcarc::GetFunctionClass(const Function *F) {
Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
// No (mandatory) arguments.
if (AI == AE)
return StringSwitch<ARCInstKind>(F->getName())
.Case("objc_autoreleasePoolPush", ARCInstKind::AutoreleasepoolPush)
.Case("clang.arc.use", ARCInstKind::IntrinsicUser)
.Default(ARCInstKind::CallOrUser);
// One argument.
const Argument *A0 = AI++;
if (AI == AE)
// Argument is a pointer.
if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
Type *ETy = PTy->getElementType();
// Argument is i8*.
if (ETy->isIntegerTy(8))
return StringSwitch<ARCInstKind>(F->getName())
.Case("objc_retain", ARCInstKind::Retain)
.Case("objc_retainAutoreleasedReturnValue", ARCInstKind::RetainRV)
.Case("objc_retainBlock", ARCInstKind::RetainBlock)
.Case("objc_release", ARCInstKind::Release)
.Case("objc_autorelease", ARCInstKind::Autorelease)
.Case("objc_autoreleaseReturnValue", ARCInstKind::AutoreleaseRV)
.Case("objc_autoreleasePoolPop", ARCInstKind::AutoreleasepoolPop)
.Case("objc_retainedObject", ARCInstKind::NoopCast)
.Case("objc_unretainedObject", ARCInstKind::NoopCast)
.Case("objc_unretainedPointer", ARCInstKind::NoopCast)
.Case("objc_retain_autorelease",
ARCInstKind::FusedRetainAutorelease)
.Case("objc_retainAutorelease", ARCInstKind::FusedRetainAutorelease)
.Case("objc_retainAutoreleaseReturnValue",
ARCInstKind::FusedRetainAutoreleaseRV)
.Case("objc_sync_enter", ARCInstKind::User)
.Case("objc_sync_exit", ARCInstKind::User)
.Default(ARCInstKind::CallOrUser);
// Argument is i8**
if (PointerType *Pte = dyn_cast<PointerType>(ETy))
if (Pte->getElementType()->isIntegerTy(8))
return StringSwitch<ARCInstKind>(F->getName())
.Case("objc_loadWeakRetained", ARCInstKind::LoadWeakRetained)
.Case("objc_loadWeak", ARCInstKind::LoadWeak)
.Case("objc_destroyWeak", ARCInstKind::DestroyWeak)
.Default(ARCInstKind::CallOrUser);
}
// Two arguments, first is i8**.
const Argument *A1 = AI++;
if (AI == AE)
if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
if (Pte->getElementType()->isIntegerTy(8))
if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
Type *ETy1 = PTy1->getElementType();
// Second argument is i8*
if (ETy1->isIntegerTy(8))
return StringSwitch<ARCInstKind>(F->getName())
.Case("objc_storeWeak", ARCInstKind::StoreWeak)
.Case("objc_initWeak", ARCInstKind::InitWeak)
.Case("objc_storeStrong", ARCInstKind::StoreStrong)
.Default(ARCInstKind::CallOrUser);
// Second argument is i8**.
if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
if (Pte1->getElementType()->isIntegerTy(8))
return StringSwitch<ARCInstKind>(F->getName())
.Case("objc_moveWeak", ARCInstKind::MoveWeak)
.Case("objc_copyWeak", ARCInstKind::CopyWeak)
// Ignore annotation calls. This is important to stop the
// optimizer from treating annotations as uses which would
// make the state of the pointers they are attempting to
// elucidate to be incorrect.
.Case("llvm.arc.annotation.topdown.bbstart",
ARCInstKind::None)
.Case("llvm.arc.annotation.topdown.bbend",
ARCInstKind::None)
.Case("llvm.arc.annotation.bottomup.bbstart",
ARCInstKind::None)
.Case("llvm.arc.annotation.bottomup.bbend",
ARCInstKind::None)
.Default(ARCInstKind::CallOrUser);
}
// Anything else.
return ARCInstKind::CallOrUser;
}
// A whitelist of intrinsics that we know do not use objc pointers or decrement
// ref counts.
static bool isInertIntrinsic(unsigned ID) {
// TODO: Make this into a covered switch.
switch (ID) {
case Intrinsic::returnaddress:
case Intrinsic::frameaddress:
case Intrinsic::stacksave:
case Intrinsic::stackrestore:
case Intrinsic::vastart:
case Intrinsic::vacopy:
case Intrinsic::vaend:
case Intrinsic::objectsize:
case Intrinsic::prefetch:
case Intrinsic::stackprotector:
case Intrinsic::eh_return_i32:
case Intrinsic::eh_return_i64:
case Intrinsic::eh_typeid_for:
case Intrinsic::eh_dwarf_cfa:
case Intrinsic::eh_sjlj_lsda:
case Intrinsic::eh_sjlj_functioncontext:
case Intrinsic::init_trampoline:
case Intrinsic::adjust_trampoline:
case Intrinsic::lifetime_start:
case Intrinsic::lifetime_end:
case Intrinsic::invariant_start:
case Intrinsic::invariant_end:
// Don't let dbg info affect our results.
case Intrinsic::dbg_declare:
case Intrinsic::dbg_value:
// Short cut: Some intrinsics obviously don't use ObjC pointers.
return true;
default:
return false;
}
}
// A whitelist of intrinsics that we know do not use objc pointers or decrement
// ref counts.
static bool isUseOnlyIntrinsic(unsigned ID) {
// We are conservative and even though intrinsics are unlikely to touch
// reference counts, we white list them for safety.
//
// TODO: Expand this into a covered switch. There is a lot more here.
switch (ID) {
case Intrinsic::memcpy:
case Intrinsic::memmove:
case Intrinsic::memset:
return true;
default:
return false;
}
}
/// \brief Determine what kind of construct V is.
ARCInstKind llvm::objcarc::GetARCInstKind(const Value *V) {
if (const Instruction *I = dyn_cast<Instruction>(V)) {
// Any instruction other than bitcast and gep with a pointer operand have a
// use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
// to a subsequent use, rather than using it themselves, in this sense.
// As a short cut, several other opcodes are known to have no pointer
// operands of interest. And ret is never followed by a release, so it's
// not interesting to examine.
switch (I->getOpcode()) {
case Instruction::Call: {
const CallInst *CI = cast<CallInst>(I);
// See if we have a function that we know something about.
if (const Function *F = CI->getCalledFunction()) {
ARCInstKind Class = GetFunctionClass(F);
if (Class != ARCInstKind::CallOrUser)
return Class;
Intrinsic::ID ID = F->getIntrinsicID();
if (isInertIntrinsic(ID))
return ARCInstKind::None;
if (isUseOnlyIntrinsic(ID))
return ARCInstKind::User;
}
// Otherwise, be conservative.
return GetCallSiteClass(CI);
}
case Instruction::Invoke:
// Otherwise, be conservative.
return GetCallSiteClass(cast<InvokeInst>(I));
case Instruction::BitCast:
case Instruction::GetElementPtr:
case Instruction::Select:
case Instruction::PHI:
case Instruction::Ret:
case Instruction::Br:
case Instruction::Switch:
case Instruction::IndirectBr:
case Instruction::Alloca:
case Instruction::VAArg:
case Instruction::Add:
case Instruction::FAdd:
case Instruction::Sub:
case Instruction::FSub:
case Instruction::Mul:
case Instruction::FMul:
case Instruction::SDiv:
case Instruction::UDiv:
case Instruction::FDiv:
case Instruction::SRem:
case Instruction::URem:
case Instruction::FRem:
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::SExt:
case Instruction::ZExt:
case Instruction::Trunc:
case Instruction::IntToPtr:
case Instruction::FCmp:
case Instruction::FPTrunc:
case Instruction::FPExt:
case Instruction::FPToUI:
case Instruction::FPToSI:
case Instruction::UIToFP:
case Instruction::SIToFP:
case Instruction::InsertElement:
case Instruction::ExtractElement:
case Instruction::ShuffleVector:
case Instruction::ExtractValue:
break;
case Instruction::ICmp:
// Comparing a pointer with null, or any other constant, isn't an
// interesting use, because we don't care what the pointer points to, or
// about the values of any other dynamic reference-counted pointers.
if (IsPotentialRetainableObjPtr(I->getOperand(1)))
return ARCInstKind::User;
break;
default:
// For anything else, check all the operands.
// Note that this includes both operands of a Store: while the first
// operand isn't actually being dereferenced, it is being stored to
// memory where we can no longer track who might read it and dereference
// it, so we have to consider it potentially used.
for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
OI != OE; ++OI)
if (IsPotentialRetainableObjPtr(*OI))
return ARCInstKind::User;
}
}
// Otherwise, it's totally inert for ARC purposes.
return ARCInstKind::None;
}
/// \brief Test if the given class is a kind of user.
bool llvm::objcarc::IsUser(ARCInstKind Class) {
switch (Class) {
case ARCInstKind::User:
case ARCInstKind::CallOrUser:
case ARCInstKind::IntrinsicUser:
return true;
case ARCInstKind::Retain:
case ARCInstKind::RetainRV:
case ARCInstKind::RetainBlock:
case ARCInstKind::Release:
case ARCInstKind::Autorelease:
case ARCInstKind::AutoreleaseRV:
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::AutoreleasepoolPop:
case ARCInstKind::NoopCast:
case ARCInstKind::FusedRetainAutorelease:
case ARCInstKind::FusedRetainAutoreleaseRV:
case ARCInstKind::LoadWeakRetained:
case ARCInstKind::StoreWeak:
case ARCInstKind::InitWeak:
case ARCInstKind::LoadWeak:
case ARCInstKind::MoveWeak:
case ARCInstKind::CopyWeak:
case ARCInstKind::DestroyWeak:
case ARCInstKind::StoreStrong:
case ARCInstKind::Call:
case ARCInstKind::None:
return false;
}
llvm_unreachable("covered switch isn't covered?");
}
/// \brief Test if the given class is objc_retain or equivalent.
bool llvm::objcarc::IsRetain(ARCInstKind Class) {
switch (Class) {
case ARCInstKind::Retain:
case ARCInstKind::RetainRV:
return true;
// I believe we treat retain block as not a retain since it can copy its
// block.
case ARCInstKind::RetainBlock:
case ARCInstKind::Release:
case ARCInstKind::Autorelease:
case ARCInstKind::AutoreleaseRV:
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::AutoreleasepoolPop:
case ARCInstKind::NoopCast:
case ARCInstKind::FusedRetainAutorelease:
case ARCInstKind::FusedRetainAutoreleaseRV:
case ARCInstKind::LoadWeakRetained:
case ARCInstKind::StoreWeak:
case ARCInstKind::InitWeak:
case ARCInstKind::LoadWeak:
case ARCInstKind::MoveWeak:
case ARCInstKind::CopyWeak:
case ARCInstKind::DestroyWeak:
case ARCInstKind::StoreStrong:
case ARCInstKind::IntrinsicUser:
case ARCInstKind::CallOrUser:
case ARCInstKind::Call:
case ARCInstKind::User:
case ARCInstKind::None:
return false;
}
llvm_unreachable("covered switch isn't covered?");
}
/// \brief Test if the given class is objc_autorelease or equivalent.
bool llvm::objcarc::IsAutorelease(ARCInstKind Class) {
switch (Class) {
case ARCInstKind::Autorelease:
case ARCInstKind::AutoreleaseRV:
return true;
case ARCInstKind::Retain:
case ARCInstKind::RetainRV:
case ARCInstKind::RetainBlock:
case ARCInstKind::Release:
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::AutoreleasepoolPop:
case ARCInstKind::NoopCast:
case ARCInstKind::FusedRetainAutorelease:
case ARCInstKind::FusedRetainAutoreleaseRV:
case ARCInstKind::LoadWeakRetained:
case ARCInstKind::StoreWeak:
case ARCInstKind::InitWeak:
case ARCInstKind::LoadWeak:
case ARCInstKind::MoveWeak:
case ARCInstKind::CopyWeak:
case ARCInstKind::DestroyWeak:
case ARCInstKind::StoreStrong:
case ARCInstKind::IntrinsicUser:
case ARCInstKind::CallOrUser:
case ARCInstKind::Call:
case ARCInstKind::User:
case ARCInstKind::None:
return false;
}
llvm_unreachable("covered switch isn't covered?");
}
/// \brief Test if the given class represents instructions which return their
/// argument verbatim.
bool llvm::objcarc::IsForwarding(ARCInstKind Class) {
switch (Class) {
case ARCInstKind::Retain:
case ARCInstKind::RetainRV:
case ARCInstKind::Autorelease:
case ARCInstKind::AutoreleaseRV:
case ARCInstKind::NoopCast:
return true;
case ARCInstKind::RetainBlock:
case ARCInstKind::Release:
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::AutoreleasepoolPop:
case ARCInstKind::FusedRetainAutorelease:
case ARCInstKind::FusedRetainAutoreleaseRV:
case ARCInstKind::LoadWeakRetained:
case ARCInstKind::StoreWeak:
case ARCInstKind::InitWeak:
case ARCInstKind::LoadWeak:
case ARCInstKind::MoveWeak:
case ARCInstKind::CopyWeak:
case ARCInstKind::DestroyWeak:
case ARCInstKind::StoreStrong:
case ARCInstKind::IntrinsicUser:
case ARCInstKind::CallOrUser:
case ARCInstKind::Call:
case ARCInstKind::User:
case ARCInstKind::None:
return false;
}
llvm_unreachable("covered switch isn't covered?");
}
/// \brief Test if the given class represents instructions which do nothing if
/// passed a null pointer.
bool llvm::objcarc::IsNoopOnNull(ARCInstKind Class) {
switch (Class) {
case ARCInstKind::Retain:
case ARCInstKind::RetainRV:
case ARCInstKind::Release:
case ARCInstKind::Autorelease:
case ARCInstKind::AutoreleaseRV:
case ARCInstKind::RetainBlock:
return true;
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::AutoreleasepoolPop:
case ARCInstKind::FusedRetainAutorelease:
case ARCInstKind::FusedRetainAutoreleaseRV:
case ARCInstKind::LoadWeakRetained:
case ARCInstKind::StoreWeak:
case ARCInstKind::InitWeak:
case ARCInstKind::LoadWeak:
case ARCInstKind::MoveWeak:
case ARCInstKind::CopyWeak:
case ARCInstKind::DestroyWeak:
case ARCInstKind::StoreStrong:
case ARCInstKind::IntrinsicUser:
case ARCInstKind::CallOrUser:
case ARCInstKind::Call:
case ARCInstKind::User:
case ARCInstKind::None:
case ARCInstKind::NoopCast:
return false;
}
llvm_unreachable("covered switch isn't covered?");
}
/// \brief Test if the given class represents instructions which are always safe
/// to mark with the "tail" keyword.
bool llvm::objcarc::IsAlwaysTail(ARCInstKind Class) {
// ARCInstKind::RetainBlock may be given a stack argument.
switch (Class) {
case ARCInstKind::Retain:
case ARCInstKind::RetainRV:
case ARCInstKind::AutoreleaseRV:
return true;
case ARCInstKind::Release:
case ARCInstKind::Autorelease:
case ARCInstKind::RetainBlock:
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::AutoreleasepoolPop:
case ARCInstKind::FusedRetainAutorelease:
case ARCInstKind::FusedRetainAutoreleaseRV:
case ARCInstKind::LoadWeakRetained:
case ARCInstKind::StoreWeak:
case ARCInstKind::InitWeak:
case ARCInstKind::LoadWeak:
case ARCInstKind::MoveWeak:
case ARCInstKind::CopyWeak:
case ARCInstKind::DestroyWeak:
case ARCInstKind::StoreStrong:
case ARCInstKind::IntrinsicUser:
case ARCInstKind::CallOrUser:
case ARCInstKind::Call:
case ARCInstKind::User:
case ARCInstKind::None:
case ARCInstKind::NoopCast:
return false;
}
llvm_unreachable("covered switch isn't covered?");
}
/// \brief Test if the given class represents instructions which are never safe
/// to mark with the "tail" keyword.
bool llvm::objcarc::IsNeverTail(ARCInstKind Class) {
/// It is never safe to tail call objc_autorelease since by tail calling
/// objc_autorelease: fast autoreleasing causing our object to be potentially
/// reclaimed from the autorelease pool which violates the semantics of
/// __autoreleasing types in ARC.
switch (Class) {
case ARCInstKind::Autorelease:
return true;
case ARCInstKind::Retain:
case ARCInstKind::RetainRV:
case ARCInstKind::AutoreleaseRV:
case ARCInstKind::Release:
case ARCInstKind::RetainBlock:
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::AutoreleasepoolPop:
case ARCInstKind::FusedRetainAutorelease:
case ARCInstKind::FusedRetainAutoreleaseRV:
case ARCInstKind::LoadWeakRetained:
case ARCInstKind::StoreWeak:
case ARCInstKind::InitWeak:
case ARCInstKind::LoadWeak:
case ARCInstKind::MoveWeak:
case ARCInstKind::CopyWeak:
case ARCInstKind::DestroyWeak:
case ARCInstKind::StoreStrong:
case ARCInstKind::IntrinsicUser:
case ARCInstKind::CallOrUser:
case ARCInstKind::Call:
case ARCInstKind::User:
case ARCInstKind::None:
case ARCInstKind::NoopCast:
return false;
}
llvm_unreachable("covered switch isn't covered?");
}
/// \brief Test if the given class represents instructions which are always safe
/// to mark with the nounwind attribute.
bool llvm::objcarc::IsNoThrow(ARCInstKind Class) {
// objc_retainBlock is not nounwind because it calls user copy constructors
// which could theoretically throw.
switch (Class) {
case ARCInstKind::Retain:
case ARCInstKind::RetainRV:
case ARCInstKind::Release:
case ARCInstKind::Autorelease:
case ARCInstKind::AutoreleaseRV:
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::AutoreleasepoolPop:
return true;
case ARCInstKind::RetainBlock:
case ARCInstKind::FusedRetainAutorelease:
case ARCInstKind::FusedRetainAutoreleaseRV:
case ARCInstKind::LoadWeakRetained:
case ARCInstKind::StoreWeak:
case ARCInstKind::InitWeak:
case ARCInstKind::LoadWeak:
case ARCInstKind::MoveWeak:
case ARCInstKind::CopyWeak:
case ARCInstKind::DestroyWeak:
case ARCInstKind::StoreStrong:
case ARCInstKind::IntrinsicUser:
case ARCInstKind::CallOrUser:
case ARCInstKind::Call:
case ARCInstKind::User:
case ARCInstKind::None:
case ARCInstKind::NoopCast:
return false;
}
llvm_unreachable("covered switch isn't covered?");
}
/// Test whether the given instruction can autorelease any pointer or cause an
/// autoreleasepool pop.
///
/// This means that it *could* interrupt the RV optimization.
bool llvm::objcarc::CanInterruptRV(ARCInstKind Class) {
switch (Class) {
case ARCInstKind::AutoreleasepoolPop:
case ARCInstKind::CallOrUser:
case ARCInstKind::Call:
case ARCInstKind::Autorelease:
case ARCInstKind::AutoreleaseRV:
case ARCInstKind::FusedRetainAutorelease:
case ARCInstKind::FusedRetainAutoreleaseRV:
return true;
case ARCInstKind::Retain:
case ARCInstKind::RetainRV:
case ARCInstKind::Release:
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::RetainBlock:
case ARCInstKind::LoadWeakRetained:
case ARCInstKind::StoreWeak:
case ARCInstKind::InitWeak:
case ARCInstKind::LoadWeak:
case ARCInstKind::MoveWeak:
case ARCInstKind::CopyWeak:
case ARCInstKind::DestroyWeak:
case ARCInstKind::StoreStrong:
case ARCInstKind::IntrinsicUser:
case ARCInstKind::User:
case ARCInstKind::None:
case ARCInstKind::NoopCast:
return false;
}
llvm_unreachable("covered switch isn't covered?");
}
bool llvm::objcarc::CanDecrementRefCount(ARCInstKind Kind) {
switch (Kind) {
case ARCInstKind::Retain:
case ARCInstKind::RetainRV:
case ARCInstKind::Autorelease:
case ARCInstKind::AutoreleaseRV:
case ARCInstKind::NoopCast:
case ARCInstKind::FusedRetainAutorelease:
case ARCInstKind::FusedRetainAutoreleaseRV:
case ARCInstKind::IntrinsicUser:
case ARCInstKind::User:
case ARCInstKind::None:
return false;
// The cases below are conservative.
// RetainBlock can result in user defined copy constructors being called
// implying releases may occur.
case ARCInstKind::RetainBlock:
case ARCInstKind::Release:
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::AutoreleasepoolPop:
case ARCInstKind::LoadWeakRetained:
case ARCInstKind::StoreWeak:
case ARCInstKind::InitWeak:
case ARCInstKind::LoadWeak:
case ARCInstKind::MoveWeak:
case ARCInstKind::CopyWeak:
case ARCInstKind::DestroyWeak:
case ARCInstKind::StoreStrong:
case ARCInstKind::CallOrUser:
case ARCInstKind::Call:
return true;
}
llvm_unreachable("covered switch isn't covered?");
}
|
0 | repos/DirectXShaderCompiler/lib/Transforms | repos/DirectXShaderCompiler/lib/Transforms/ObjCARC/DependencyAnalysis.h | //===- DependencyAnalysis.h - ObjC ARC Optimization ---*- C++ -*-----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This file declares special dependency analysis routines used in Objective C
/// ARC Optimizations.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TRANSFORMS_OBJCARC_DEPENDENCYANALYSIS_H
#define LLVM_LIB_TRANSFORMS_OBJCARC_DEPENDENCYANALYSIS_H
#include "ARCInstKind.h"
#include "llvm/ADT/SmallPtrSet.h"
namespace llvm {
class BasicBlock;
class Instruction;
class Value;
}
namespace llvm {
namespace objcarc {
class ProvenanceAnalysis;
/// \enum DependenceKind
/// \brief Defines different dependence kinds among various ARC constructs.
///
/// There are several kinds of dependence-like concepts in use here.
///
enum DependenceKind {
NeedsPositiveRetainCount,
AutoreleasePoolBoundary,
CanChangeRetainCount,
RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
};
void FindDependencies(DependenceKind Flavor,
const Value *Arg,
BasicBlock *StartBB, Instruction *StartInst,
SmallPtrSetImpl<Instruction *> &DependingInstructions,
SmallPtrSetImpl<const BasicBlock *> &Visited,
ProvenanceAnalysis &PA);
bool
Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
ProvenanceAnalysis &PA);
/// Test whether the given instruction can "use" the given pointer's object in a
/// way that requires the reference count to be positive.
bool CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
ARCInstKind Class);
/// Test whether the given instruction can result in a reference count
/// modification (positive or negative) for the pointer's object.
bool CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
ProvenanceAnalysis &PA, ARCInstKind Class);
/// Returns true if we can not conservatively prove that Inst can not decrement
/// the reference count of Ptr. Returns false if we can.
bool CanDecrementRefCount(const Instruction *Inst, const Value *Ptr,
ProvenanceAnalysis &PA, ARCInstKind Class);
static inline bool CanDecrementRefCount(const Instruction *Inst,
const Value *Ptr,
ProvenanceAnalysis &PA) {
return CanDecrementRefCount(Inst, Ptr, PA, GetARCInstKind(Inst));
}
} // namespace objcarc
} // namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/lib/Transforms | repos/DirectXShaderCompiler/lib/Transforms/ObjCARC/ObjCARCExpand.cpp | //===- ObjCARCExpand.cpp - ObjC ARC Optimization --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file defines ObjC ARC optimizations. ARC stands for Automatic
/// Reference Counting and is a system for managing reference counts for objects
/// in Objective C.
///
/// This specific file deals with early optimizations which perform certain
/// cleanup operations.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
#include "ObjCARC.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Value.h"
#include "llvm/Pass.h"
#include "llvm/PassAnalysisSupport.h"
#include "llvm/PassRegistry.h"
#include "llvm/PassSupport.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#define DEBUG_TYPE "objc-arc-expand"
namespace llvm {
class Module;
}
using namespace llvm;
using namespace llvm::objcarc;
namespace {
/// \brief Early ARC transformations.
class ObjCARCExpand : public FunctionPass {
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool doInitialization(Module &M) override;
bool runOnFunction(Function &F) override;
/// A flag indicating whether this optimization pass should run.
bool Run;
public:
static char ID;
ObjCARCExpand() : FunctionPass(ID) {
initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
}
};
}
char ObjCARCExpand::ID = 0;
INITIALIZE_PASS(ObjCARCExpand,
"objc-arc-expand", "ObjC ARC expansion", false, false)
Pass *llvm::createObjCARCExpandPass() {
return new ObjCARCExpand();
}
void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
}
bool ObjCARCExpand::doInitialization(Module &M) {
Run = ModuleHasARC(M);
return false;
}
bool ObjCARCExpand::runOnFunction(Function &F) {
if (!EnableARCOpts)
return false;
// If nothing in the Module uses ARC, don't do anything.
if (!Run)
return false;
bool Changed = false;
DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n");
for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
Instruction *Inst = &*I;
DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
switch (GetBasicARCInstKind(Inst)) {
case ARCInstKind::Retain:
case ARCInstKind::RetainRV:
case ARCInstKind::Autorelease:
case ARCInstKind::AutoreleaseRV:
case ARCInstKind::FusedRetainAutorelease:
case ARCInstKind::FusedRetainAutoreleaseRV: {
// These calls return their argument verbatim, as a low-level
// optimization. However, this makes high-level optimizations
// harder. Undo any uses of this optimization that the front-end
// emitted here. We'll redo them in the contract pass.
Changed = true;
Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
" New = " << *Value << "\n");
Inst->replaceAllUsesWith(Value);
break;
}
default:
break;
}
}
DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
return Changed;
}
|
0 | repos/DirectXShaderCompiler/lib/Transforms | repos/DirectXShaderCompiler/lib/Transforms/ObjCARC/CMakeLists.txt | add_llvm_library(LLVMObjCARCOpts
ObjCARC.cpp
ObjCARCOpts.cpp
ObjCARCExpand.cpp
ObjCARCAPElim.cpp
ObjCARCAliasAnalysis.cpp
ARCInstKind.cpp
ObjCARCContract.cpp
DependencyAnalysis.cpp
ProvenanceAnalysis.cpp
ProvenanceAnalysisEvaluator.cpp
PtrState.cpp
ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/Transforms
)
add_dependencies(LLVMObjCARCOpts intrinsics_gen)
|
0 | repos/DirectXShaderCompiler/lib/Transforms | repos/DirectXShaderCompiler/lib/Transforms/ObjCARC/ObjCARCAliasAnalysis.cpp | //===- ObjCARCAliasAnalysis.cpp - ObjC ARC Optimization -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file defines a simple ARC-aware AliasAnalysis using special knowledge
/// of Objective C to enhance other optimization passes which rely on the Alias
/// Analysis infrastructure.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
#include "ObjCARC.h"
#include "ObjCARCAliasAnalysis.h"
#include "llvm/IR/Instruction.h"
#include "llvm/InitializePasses.h"
#include "llvm/PassAnalysisSupport.h"
#include "llvm/PassSupport.h"
#define DEBUG_TYPE "objc-arc-aa"
namespace llvm {
class Function;
class Value;
}
using namespace llvm;
using namespace llvm::objcarc;
// Register this pass...
char ObjCARCAliasAnalysis::ID = 0;
INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
"ObjC-ARC-Based Alias Analysis", false, true, false)
ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
return new ObjCARCAliasAnalysis();
}
bool ObjCARCAliasAnalysis::doInitialization(Module &M) {
InitializeAliasAnalysis(this, &M.getDataLayout());
return true;
}
void
ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
AliasAnalysis::getAnalysisUsage(AU);
}
AliasResult ObjCARCAliasAnalysis::alias(const MemoryLocation &LocA,
const MemoryLocation &LocB) {
if (!EnableARCOpts)
return AliasAnalysis::alias(LocA, LocB);
// First, strip off no-ops, including ObjC-specific no-ops, and try making a
// precise alias query.
const Value *SA = GetRCIdentityRoot(LocA.Ptr);
const Value *SB = GetRCIdentityRoot(LocB.Ptr);
AliasResult Result =
AliasAnalysis::alias(MemoryLocation(SA, LocA.Size, LocA.AATags),
MemoryLocation(SB, LocB.Size, LocB.AATags));
if (Result != MayAlias)
return Result;
// If that failed, climb to the underlying object, including climbing through
// ObjC-specific no-ops, and try making an imprecise alias query.
const Value *UA = GetUnderlyingObjCPtr(SA, *DL);
const Value *UB = GetUnderlyingObjCPtr(SB, *DL);
if (UA != SA || UB != SB) {
Result = AliasAnalysis::alias(MemoryLocation(UA), MemoryLocation(UB));
// We can't use MustAlias or PartialAlias results here because
// GetUnderlyingObjCPtr may return an offsetted pointer value.
if (Result == NoAlias)
return NoAlias;
}
// If that failed, fail. We don't need to chain here, since that's covered
// by the earlier precise query.
return MayAlias;
}
bool ObjCARCAliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
bool OrLocal) {
if (!EnableARCOpts)
return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
// First, strip off no-ops, including ObjC-specific no-ops, and try making
// a precise alias query.
const Value *S = GetRCIdentityRoot(Loc.Ptr);
if (AliasAnalysis::pointsToConstantMemory(
MemoryLocation(S, Loc.Size, Loc.AATags), OrLocal))
return true;
// If that failed, climb to the underlying object, including climbing through
// ObjC-specific no-ops, and try making an imprecise alias query.
const Value *U = GetUnderlyingObjCPtr(S, *DL);
if (U != S)
return AliasAnalysis::pointsToConstantMemory(MemoryLocation(U), OrLocal);
// If that failed, fail. We don't need to chain here, since that's covered
// by the earlier precise query.
return false;
}
AliasAnalysis::ModRefBehavior
ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
// We have nothing to do. Just chain to the next AliasAnalysis.
return AliasAnalysis::getModRefBehavior(CS);
}
AliasAnalysis::ModRefBehavior
ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
if (!EnableARCOpts)
return AliasAnalysis::getModRefBehavior(F);
switch (GetFunctionClass(F)) {
case ARCInstKind::NoopCast:
return DoesNotAccessMemory;
default:
break;
}
return AliasAnalysis::getModRefBehavior(F);
}
AliasAnalysis::ModRefResult
ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
const MemoryLocation &Loc) {
if (!EnableARCOpts)
return AliasAnalysis::getModRefInfo(CS, Loc);
switch (GetBasicARCInstKind(CS.getInstruction())) {
case ARCInstKind::Retain:
case ARCInstKind::RetainRV:
case ARCInstKind::Autorelease:
case ARCInstKind::AutoreleaseRV:
case ARCInstKind::NoopCast:
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::FusedRetainAutorelease:
case ARCInstKind::FusedRetainAutoreleaseRV:
// These functions don't access any memory visible to the compiler.
// Note that this doesn't include objc_retainBlock, because it updates
// pointers when it copies block data.
return NoModRef;
default:
break;
}
return AliasAnalysis::getModRefInfo(CS, Loc);
}
AliasAnalysis::ModRefResult
ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
ImmutableCallSite CS2) {
// TODO: Theoretically we could check for dependencies between objc_* calls
// and OnlyAccessesArgumentPointees calls or other well-behaved calls.
return AliasAnalysis::getModRefInfo(CS1, CS2);
}
|
0 | repos/DirectXShaderCompiler/lib/Transforms | repos/DirectXShaderCompiler/lib/Transforms/ObjCARC/LLVMBuild.txt | ;===- ./lib/Transforms/ObjCARC/LLVMBuild.txt -------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Library
name = ObjCARC
parent = Transforms
library_name = ObjCARCOpts
required_libraries = Analysis Core Support TransformUtils
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.