#include "clang/Basic/Version.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Triple.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/VCSRevision.h"
#include "llvm/Support/WithColor.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"
#include <cassert>
#include <cstdint>
#define OPENMP_OFFLOAD_IMAGE_VERSION "1.0"
using namespace llvm;
using namespace llvm::object;
static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
static cl::OptionCategory
ClangOffloadWrapperCategory("clang-offload-wrapper options");
static cl::opt<std::string> Output("o", cl::Required,
cl::desc("Output filename"),
cl::value_desc("filename"),
cl::cat(ClangOffloadWrapperCategory));
static cl::list<std::string> Inputs(cl::Positional, cl::OneOrMore,
cl::desc("<input files>"),
cl::cat(ClangOffloadWrapperCategory));
static cl::opt<std::string>
Target("target", cl::Required,
cl::desc("Target triple for the output module"),
cl::value_desc("triple"), cl::cat(ClangOffloadWrapperCategory));
static cl::opt<bool> SaveTemps(
"save-temps",
cl::desc("Save temporary files that may be produced by the tool. "
"This option forces print-out of the temporary files' names."),
cl::Hidden);
static cl::opt<bool> AddOpenMPOffloadNotes(
"add-omp-offload-notes",
cl::desc("Add LLVMOMPOFFLOAD ELF notes to ELF device images."), cl::Hidden);
namespace {
class BinaryWrapper {
LLVMContext C;
Module M;
StructType *EntryTy = nullptr;
StructType *ImageTy = nullptr;
StructType *DescTy = nullptr;
std::string ToolName;
std::string ObjcopyPath;
std::vector<std::string> TempFiles;
private:
IntegerType *getSizeTTy() {
switch (M.getDataLayout().getPointerTypeSize(Type::getInt8PtrTy(C))) {
case 4u:
return Type::getInt32Ty(C);
case 8u:
return Type::getInt64Ty(C);
}
llvm_unreachable("unsupported pointer type size");
}
StructType *getEntryTy() {
if (!EntryTy)
EntryTy = StructType::create("__tgt_offload_entry", Type::getInt8PtrTy(C),
Type::getInt8PtrTy(C), getSizeTTy(),
Type::getInt32Ty(C), Type::getInt32Ty(C));
return EntryTy;
}
PointerType *getEntryPtrTy() { return PointerType::getUnqual(getEntryTy()); }
StructType *getDeviceImageTy() {
if (!ImageTy)
ImageTy = StructType::create("__tgt_device_image", Type::getInt8PtrTy(C),
Type::getInt8PtrTy(C), getEntryPtrTy(),
getEntryPtrTy());
return ImageTy;
}
PointerType *getDeviceImagePtrTy() {
return PointerType::getUnqual(getDeviceImageTy());
}
StructType *getBinDescTy() {
if (!DescTy)
DescTy = StructType::create("__tgt_bin_desc", Type::getInt32Ty(C),
getDeviceImagePtrTy(), getEntryPtrTy(),
getEntryPtrTy());
return DescTy;
}
PointerType *getBinDescPtrTy() {
return PointerType::getUnqual(getBinDescTy());
}
GlobalVariable *createBinDesc(ArrayRef<ArrayRef<char>> Bufs) {
auto *EntriesB = new GlobalVariable(
M, getEntryTy(), true, GlobalValue::ExternalLinkage,
nullptr, "__start_omp_offloading_entries");
EntriesB->setVisibility(GlobalValue::HiddenVisibility);
auto *EntriesE = new GlobalVariable(
M, getEntryTy(), true, GlobalValue::ExternalLinkage,
nullptr, "__stop_omp_offloading_entries");
EntriesE->setVisibility(GlobalValue::HiddenVisibility);
auto *DummyInit =
ConstantAggregateZero::get(ArrayType::get(getEntryTy(), 0u));
auto *DummyEntry = new GlobalVariable(
M, DummyInit->getType(), true, GlobalVariable::ExternalLinkage,
DummyInit, "__dummy.omp_offloading.entry");
DummyEntry->setSection("omp_offloading_entries");
DummyEntry->setVisibility(GlobalValue::HiddenVisibility);
auto *Zero = ConstantInt::get(getSizeTTy(), 0u);
Constant *ZeroZero[] = {Zero, Zero};
SmallVector<Constant *, 4u> ImagesInits;
ImagesInits.reserve(Bufs.size());
for (ArrayRef<char> Buf : Bufs) {
auto *Data = ConstantDataArray::get(C, Buf);
auto *Image = new GlobalVariable(M, Data->getType(), true,
GlobalVariable::InternalLinkage, Data,
".omp_offloading.device_image");
Image->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
auto *Size = ConstantInt::get(getSizeTTy(), Buf.size());
Constant *ZeroSize[] = {Zero, Size};
auto *ImageB = ConstantExpr::getGetElementPtr(Image->getValueType(),
Image, ZeroZero);
auto *ImageE = ConstantExpr::getGetElementPtr(Image->getValueType(),
Image, ZeroSize);
ImagesInits.push_back(ConstantStruct::get(getDeviceImageTy(), ImageB,
ImageE, EntriesB, EntriesE));
}
auto *ImagesData = ConstantArray::get(
ArrayType::get(getDeviceImageTy(), ImagesInits.size()), ImagesInits);
auto *Images =
new GlobalVariable(M, ImagesData->getType(), true,
GlobalValue::InternalLinkage, ImagesData,
".omp_offloading.device_images");
Images->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
auto *ImagesB = ConstantExpr::getGetElementPtr(Images->getValueType(),
Images, ZeroZero);
auto *DescInit = ConstantStruct::get(
getBinDescTy(),
ConstantInt::get(Type::getInt32Ty(C), ImagesInits.size()), ImagesB,
EntriesB, EntriesE);
return new GlobalVariable(M, DescInit->getType(), true,
GlobalValue::InternalLinkage, DescInit,
".omp_offloading.descriptor");
}
void createRegisterFunction(GlobalVariable *BinDesc) {
auto *FuncTy = FunctionType::get(Type::getVoidTy(C), false);
auto *Func = Function::Create(FuncTy, GlobalValue::InternalLinkage,
".omp_offloading.descriptor_reg", &M);
Func->setSection(".text.startup");
auto *RegFuncTy = FunctionType::get(Type::getVoidTy(C), getBinDescPtrTy(),
false);
FunctionCallee RegFuncC =
M.getOrInsertFunction("__tgt_register_lib", RegFuncTy);
IRBuilder<> Builder(BasicBlock::Create(C, "entry", Func));
Builder.CreateCall(RegFuncC, BinDesc);
Builder.CreateRetVoid();
appendToGlobalCtors(M, Func, 1);
}
void createUnregisterFunction(GlobalVariable *BinDesc) {
auto *FuncTy = FunctionType::get(Type::getVoidTy(C), false);
auto *Func = Function::Create(FuncTy, GlobalValue::InternalLinkage,
".omp_offloading.descriptor_unreg", &M);
Func->setSection(".text.startup");
auto *UnRegFuncTy = FunctionType::get(Type::getVoidTy(C), getBinDescPtrTy(),
false);
FunctionCallee UnRegFuncC =
M.getOrInsertFunction("__tgt_unregister_lib", UnRegFuncTy);
IRBuilder<> Builder(BasicBlock::Create(C, "entry", Func));
Builder.CreateCall(UnRegFuncC, BinDesc);
Builder.CreateRetVoid();
appendToGlobalDtors(M, Func, 1);
}
public:
BinaryWrapper(StringRef Target, StringRef ToolName)
: M("offload.wrapper.object", C), ToolName(ToolName) {
M.setTargetTriple(Target);
void *P = (void *)(intptr_t)&Help;
std::string COWPath = sys::fs::getMainExecutable(ToolName.str().c_str(), P);
if (!COWPath.empty()) {
auto COWDir = sys::path::parent_path(COWPath);
ErrorOr<std::string> ObjcopyPathOrErr =
sys::findProgramByName("llvm-objcopy", {COWDir});
if (ObjcopyPathOrErr) {
ObjcopyPath = *ObjcopyPathOrErr;
return;
}
}
ErrorOr<std::string> ObjcopyPathOrErr =
sys::findProgramByName("llvm-objcopy");
if (!ObjcopyPathOrErr) {
WithColor::warning(errs(), ToolName)
<< "cannot find llvm-objcopy[.exe] in PATH; ELF notes cannot be "
"added.\n";
return;
}
ObjcopyPath = *ObjcopyPathOrErr;
}
~BinaryWrapper() {
if (TempFiles.empty())
return;
StringRef ToolNameRef(ToolName);
auto warningOS = [ToolNameRef]() -> raw_ostream & {
return WithColor::warning(errs(), ToolNameRef);
};
for (auto &F : TempFiles) {
if (SaveTemps) {
warningOS() << "keeping temporary file " << F << "\n";
continue;
}
auto EC = sys::fs::remove(F, false);
if (EC)
warningOS() << "cannot remove temporary file " << F << ": "
<< EC.message().c_str() << "\n";
}
}
const Module &wrapBinaries(ArrayRef<ArrayRef<char>> Binaries) {
GlobalVariable *Desc = createBinDesc(Binaries);
assert(Desc && "no binary descriptor");
createRegisterFunction(Desc);
createUnregisterFunction(Desc);
return M;
}
std::unique_ptr<MemoryBuffer> addELFNotes(std::unique_ptr<MemoryBuffer> Buf,
StringRef OriginalFileName) {
if (ObjcopyPath.empty())
return Buf;
StringRef ToolNameRef(ToolName);
auto warningOS = [ToolNameRef]() -> raw_ostream & {
return WithColor::warning(errs(), ToolNameRef);
};
auto handleErrorAsWarning = [&warningOS](Error E) {
logAllUnhandledErrors(std::move(E), warningOS());
};
Expected<std::unique_ptr<ObjectFile>> BinOrErr =
ObjectFile::createELFObjectFile(Buf->getMemBufferRef(),
false);
if (Error E = BinOrErr.takeError()) {
consumeError(std::move(E));
warningOS() << OriginalFileName
<< " is not an ELF image, so notes cannot be added to it.\n";
return Buf;
}
support::endianness Endianness;
if (isa<ELF64LEObjectFile>(BinOrErr->get()) ||
isa<ELF32LEObjectFile>(BinOrErr->get())) {
Endianness = support::little;
} else if (isa<ELF64BEObjectFile>(BinOrErr->get()) ||
isa<ELF32BEObjectFile>(BinOrErr->get())) {
Endianness = support::big;
} else {
warningOS() << OriginalFileName
<< " is an ELF image of unrecognized format.\n";
return Buf;
}
Twine NotesFileModel = OriginalFileName + Twine(".elfnotes.%%%%%%%.tmp");
Expected<sys::fs::TempFile> NotesTemp =
sys::fs::TempFile::create(NotesFileModel);
if (Error E = NotesTemp.takeError()) {
handleErrorAsWarning(createFileError(NotesFileModel, std::move(E)));
return Buf;
}
TempFiles.push_back(NotesTemp->TmpName);
Twine ELFFileModel = OriginalFileName + Twine(".elfwithnotes.%%%%%%%.tmp");
Expected<sys::fs::TempFile> ELFTemp =
sys::fs::TempFile::create(ELFFileModel);
if (Error E = ELFTemp.takeError()) {
handleErrorAsWarning(createFileError(ELFFileModel, std::move(E)));
return Buf;
}
TempFiles.push_back(ELFTemp->TmpName);
std::string ELFTmpFileName = ELFTemp->TmpName;
if (Error E = ELFTemp->keep(ELFTmpFileName)) {
handleErrorAsWarning(createFileError(ELFTmpFileName, std::move(E)));
return Buf;
}
raw_fd_ostream NotesOS(NotesTemp->FD, false);
struct NoteTy {
std::string Name;
uint32_t Type = 0;
std::string Desc;
NoteTy(std::string &&Name, uint32_t Type, std::string &&Desc)
: Name(std::move(Name)), Type(Type), Desc(std::move(Desc)) {}
};
SmallVector<NoteTy, 3> Notes;
Notes.emplace_back("LLVMOMPOFFLOAD", ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION,
OPENMP_OFFLOAD_IMAGE_VERSION);
Notes.emplace_back("LLVMOMPOFFLOAD", ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER,
"LLVM");
Notes.emplace_back("LLVMOMPOFFLOAD",
ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION,
LLVM_VERSION_STRING
#ifdef LLVM_REVISION
" " LLVM_REVISION
#endif
);
auto getPadAmount = [](uint32_t N, uint32_t Alignment) -> uint32_t {
uint32_t Mod = (N % Alignment);
if (Mod == 0)
return 0;
return Alignment - Mod;
};
auto emitPadding = [&getPadAmount](raw_ostream &OS, uint32_t Size) {
for (uint32_t I = 0; I < getPadAmount(Size, 4); ++I)
OS << '\0';
};
for (auto &N : Notes) {
assert(!N.Name.empty() && "We should not create notes with empty names.");
if (N.Name.back() != '\0')
N.Name += '\0';
uint32_t NameSz = N.Name.size();
uint32_t DescSz = N.Desc.size();
support::endian::write<uint32_t>(NotesOS, NameSz, Endianness);
support::endian::write<uint32_t>(NotesOS, DescSz, Endianness);
support::endian::write<uint32_t>(NotesOS, N.Type, Endianness);
NotesOS << N.Name;
emitPadding(NotesOS, NameSz);
if (DescSz == 0)
continue;
NotesOS << N.Desc;
emitPadding(NotesOS, DescSz);
}
NotesOS.flush();
std::string NotesTmpFileName = NotesTemp->TmpName;
if (Error E = NotesTemp->keep(NotesTmpFileName)) {
handleErrorAsWarning(createFileError(NotesTmpFileName, std::move(E)));
return Buf;
}
std::vector<StringRef> Args;
Args.push_back(ObjcopyPath);
std::string Option("--add-section=.note.openmp=" + NotesTmpFileName);
Args.push_back(Option);
Args.push_back(OriginalFileName);
Args.push_back(ELFTmpFileName);
bool ExecutionFailed = false;
std::string ErrMsg;
(void)sys::ExecuteAndWait(ObjcopyPath, Args,
llvm::None, {},
0,
0, &ErrMsg, &ExecutionFailed);
if (ExecutionFailed) {
warningOS() << ErrMsg << "\n";
return Buf;
}
ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
MemoryBuffer::getFile(ELFTmpFileName);
if (!BufOrErr) {
handleErrorAsWarning(
createFileError(ELFTmpFileName, BufOrErr.getError()));
return Buf;
}
return std::move(*BufOrErr);
}
};
}
int main(int argc, const char **argv) {
sys::PrintStackTraceOnErrorSignal(argv[0]);
cl::HideUnrelatedOptions(ClangOffloadWrapperCategory);
cl::SetVersionPrinter([](raw_ostream &OS) {
OS << clang::getClangToolFullVersion("clang-offload-wrapper") << '\n';
});
cl::ParseCommandLineOptions(
argc, argv,
"A tool to create a wrapper bitcode for offload target binaries. Takes "
"offload\ntarget binaries as input and produces bitcode file containing "
"target binaries packaged\nas data and initialization code which "
"registers target binaries in offload runtime.\n");
if (Help) {
cl::PrintHelpMessage();
return 0;
}
auto reportError = [argv](Error E) {
logAllUnhandledErrors(std::move(E), WithColor::error(errs(), argv[0]));
};
if (Triple(Target).getArch() == Triple::UnknownArch) {
reportError(createStringError(
errc::invalid_argument, "'" + Target + "': unsupported target triple"));
return 1;
}
BinaryWrapper Wrapper(Target, argv[0]);
SmallVector<std::unique_ptr<MemoryBuffer>, 4u> Buffers;
SmallVector<ArrayRef<char>, 4u> Images;
Buffers.reserve(Inputs.size());
Images.reserve(Inputs.size());
for (const std::string &File : Inputs) {
ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
MemoryBuffer::getFileOrSTDIN(File);
if (!BufOrErr) {
reportError(createFileError(File, BufOrErr.getError()));
return 1;
}
std::unique_ptr<MemoryBuffer> Buffer(std::move(*BufOrErr));
if (File != "-" && AddOpenMPOffloadNotes) {
Buffer = Wrapper.addELFNotes(std::move(Buffer), File);
}
const std::unique_ptr<MemoryBuffer> &Buf =
Buffers.emplace_back(std::move(Buffer));
Images.emplace_back(Buf->getBufferStart(), Buf->getBufferSize());
}
std::error_code EC;
ToolOutputFile Out(Output, EC, sys::fs::OF_None);
if (EC) {
reportError(createFileError(Output, EC));
return 1;
}
WriteBitcodeToFile(
Wrapper.wrapBinaries(makeArrayRef(Images.data(), Images.size())),
Out.os());
if (Out.os().has_error()) {
reportError(createFileError(Output, Out.os().error()));
return 1;
}
Out.keep();
return 0;
}