2017-12-15 08:17:10 +08:00
|
|
|
//===-- WebAssemblyLowerGlobalDtors.cpp - Lower @llvm.global_dtors --------===//
|
|
|
|
//
|
2019-01-19 16:50:56 +08:00
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
2017-12-15 08:17:10 +08:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
///
|
|
|
|
/// \file
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Lower @llvm.global_dtors.
|
2017-12-15 08:17:10 +08:00
|
|
|
///
|
|
|
|
/// WebAssembly doesn't have a builtin way to invoke static destructors.
|
|
|
|
/// Implement @llvm.global_dtors by creating wrapper functions that are
|
|
|
|
/// registered in @llvm.global_ctors and which contain a call to
|
|
|
|
/// `__cxa_atexit` to register their destructor functions.
|
|
|
|
///
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
#include "WebAssembly.h"
|
2018-09-05 09:27:38 +08:00
|
|
|
#include "llvm/ADT/MapVector.h"
|
2017-12-15 08:17:10 +08:00
|
|
|
#include "llvm/IR/Constants.h"
|
|
|
|
#include "llvm/IR/Instructions.h"
|
|
|
|
#include "llvm/IR/Intrinsics.h"
|
|
|
|
#include "llvm/IR/Module.h"
|
|
|
|
#include "llvm/Pass.h"
|
|
|
|
#include "llvm/Support/Debug.h"
|
|
|
|
#include "llvm/Support/raw_ostream.h"
|
2018-09-05 09:27:38 +08:00
|
|
|
#include "llvm/Transforms/Utils/ModuleUtils.h"
|
2017-12-15 08:17:10 +08:00
|
|
|
using namespace llvm;
|
|
|
|
|
|
|
|
#define DEBUG_TYPE "wasm-lower-global-dtors"
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
class LowerGlobalDtors final : public ModulePass {
|
|
|
|
StringRef getPassName() const override {
|
|
|
|
return "WebAssembly Lower @llvm.global_dtors";
|
|
|
|
}
|
|
|
|
|
|
|
|
void getAnalysisUsage(AnalysisUsage &AU) const override {
|
|
|
|
AU.setPreservesCFG();
|
|
|
|
ModulePass::getAnalysisUsage(AU);
|
|
|
|
}
|
|
|
|
|
|
|
|
bool runOnModule(Module &M) override;
|
|
|
|
|
|
|
|
public:
|
|
|
|
static char ID;
|
|
|
|
LowerGlobalDtors() : ModulePass(ID) {}
|
|
|
|
};
|
|
|
|
} // End anonymous namespace
|
|
|
|
|
|
|
|
char LowerGlobalDtors::ID = 0;
|
2018-03-31 04:36:58 +08:00
|
|
|
INITIALIZE_PASS(LowerGlobalDtors, DEBUG_TYPE,
|
|
|
|
"Lower @llvm.global_dtors for WebAssembly", false, false)
|
|
|
|
|
2017-12-15 08:17:10 +08:00
|
|
|
ModulePass *llvm::createWebAssemblyLowerGlobalDtors() {
|
|
|
|
return new LowerGlobalDtors();
|
|
|
|
}
|
|
|
|
|
|
|
|
bool LowerGlobalDtors::runOnModule(Module &M) {
|
2019-01-10 07:05:21 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "********** Lower Global Destructors **********\n");
|
|
|
|
|
2017-12-15 08:17:10 +08:00
|
|
|
GlobalVariable *GV = M.getGlobalVariable("llvm.global_dtors");
|
2019-03-01 08:12:13 +08:00
|
|
|
if (!GV || !GV->hasInitializer())
|
2017-12-15 08:17:10 +08:00
|
|
|
return false;
|
|
|
|
|
|
|
|
const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
|
|
|
|
if (!InitList)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// Sanity-check @llvm.global_dtor's type.
|
[WebAssembly] clang-tidy (NFC)
Summary:
This patch fixes clang-tidy warnings on wasm-only files.
The list of checks used is:
`-*,clang-diagnostic-*,llvm-*,misc-*,-misc-unused-parameters,readability-identifier-naming,modernize-*`
(LLVM's default .clang-tidy list is the same except it does not have
`modernize-*`. But I've seen in multiple CLs in LLVM the modernize style
was recommended and code was fixed based on the style, so I added it as
well.)
The common fixes are:
- Variable names start with an uppercase letter
- Function names start with a lowercase letter
- Use `auto` when you use casts so the type is evident
- Use inline initialization for class member variables
- Use `= default` for empty constructors / destructors
- Use `using` in place of `typedef`
Reviewers: sbc100, tlively, aardappel
Subscribers: dschuff, sunfish, jgravelle-google, yurydelendik, kripken, MatzeB, mgorny, rupprecht, llvm-commits
Differential Revision: https://reviews.llvm.org/D57500
llvm-svn: 353075
2019-02-05 03:13:39 +08:00
|
|
|
auto *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
|
2017-12-15 08:17:10 +08:00
|
|
|
if (!ETy || ETy->getNumElements() != 3 ||
|
|
|
|
!ETy->getTypeAtIndex(0U)->isIntegerTy() ||
|
|
|
|
!ETy->getTypeAtIndex(1U)->isPointerTy() ||
|
|
|
|
!ETy->getTypeAtIndex(2U)->isPointerTy())
|
|
|
|
return false; // Not (int, ptr, ptr).
|
|
|
|
|
|
|
|
// Collect the contents of @llvm.global_dtors, collated by priority and
|
|
|
|
// associated symbol.
|
2018-09-05 09:27:38 +08:00
|
|
|
std::map<uint16_t, MapVector<Constant *, std::vector<Constant *>>> DtorFuncs;
|
2017-12-15 08:17:10 +08:00
|
|
|
for (Value *O : InitList->operands()) {
|
[WebAssembly] clang-tidy (NFC)
Summary:
This patch fixes clang-tidy warnings on wasm-only files.
The list of checks used is:
`-*,clang-diagnostic-*,llvm-*,misc-*,-misc-unused-parameters,readability-identifier-naming,modernize-*`
(LLVM's default .clang-tidy list is the same except it does not have
`modernize-*`. But I've seen in multiple CLs in LLVM the modernize style
was recommended and code was fixed based on the style, so I added it as
well.)
The common fixes are:
- Variable names start with an uppercase letter
- Function names start with a lowercase letter
- Use `auto` when you use casts so the type is evident
- Use inline initialization for class member variables
- Use `= default` for empty constructors / destructors
- Use `using` in place of `typedef`
Reviewers: sbc100, tlively, aardappel
Subscribers: dschuff, sunfish, jgravelle-google, yurydelendik, kripken, MatzeB, mgorny, rupprecht, llvm-commits
Differential Revision: https://reviews.llvm.org/D57500
llvm-svn: 353075
2019-02-05 03:13:39 +08:00
|
|
|
auto *CS = dyn_cast<ConstantStruct>(O);
|
2018-09-05 09:27:38 +08:00
|
|
|
if (!CS)
|
|
|
|
continue; // Malformed.
|
2017-12-15 08:17:10 +08:00
|
|
|
|
[WebAssembly] clang-tidy (NFC)
Summary:
This patch fixes clang-tidy warnings on wasm-only files.
The list of checks used is:
`-*,clang-diagnostic-*,llvm-*,misc-*,-misc-unused-parameters,readability-identifier-naming,modernize-*`
(LLVM's default .clang-tidy list is the same except it does not have
`modernize-*`. But I've seen in multiple CLs in LLVM the modernize style
was recommended and code was fixed based on the style, so I added it as
well.)
The common fixes are:
- Variable names start with an uppercase letter
- Function names start with a lowercase letter
- Use `auto` when you use casts so the type is evident
- Use inline initialization for class member variables
- Use `= default` for empty constructors / destructors
- Use `using` in place of `typedef`
Reviewers: sbc100, tlively, aardappel
Subscribers: dschuff, sunfish, jgravelle-google, yurydelendik, kripken, MatzeB, mgorny, rupprecht, llvm-commits
Differential Revision: https://reviews.llvm.org/D57500
llvm-svn: 353075
2019-02-05 03:13:39 +08:00
|
|
|
auto *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
|
2018-09-05 09:27:38 +08:00
|
|
|
if (!Priority)
|
|
|
|
continue; // Malformed.
|
2017-12-15 08:17:10 +08:00
|
|
|
uint16_t PriorityValue = Priority->getLimitedValue(UINT16_MAX);
|
|
|
|
|
|
|
|
Constant *DtorFunc = CS->getOperand(1);
|
|
|
|
if (DtorFunc->isNullValue())
|
2018-09-05 09:27:38 +08:00
|
|
|
break; // Found a null terminator, skip the rest.
|
2017-12-15 08:17:10 +08:00
|
|
|
|
|
|
|
Constant *Associated = CS->getOperand(2);
|
2019-08-23 03:56:14 +08:00
|
|
|
Associated = cast<Constant>(Associated->stripPointerCasts());
|
2017-12-15 08:17:10 +08:00
|
|
|
|
|
|
|
DtorFuncs[PriorityValue][Associated].push_back(DtorFunc);
|
|
|
|
}
|
|
|
|
if (DtorFuncs.empty())
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
|
|
|
|
LLVMContext &C = M.getContext();
|
|
|
|
PointerType *VoidStar = Type::getInt8PtrTy(C);
|
2018-09-05 09:27:38 +08:00
|
|
|
Type *AtExitFuncArgs[] = {VoidStar};
|
|
|
|
FunctionType *AtExitFuncTy =
|
|
|
|
FunctionType::get(Type::getVoidTy(C), AtExitFuncArgs,
|
|
|
|
/*isVarArg=*/false);
|
|
|
|
|
[opaque pointer types] Add a FunctionCallee wrapper type, and use it.
Recommit r352791 after tweaking DerivedTypes.h slightly, so that gcc
doesn't choke on it, hopefully.
Original Message:
The FunctionCallee type is effectively a {FunctionType*,Value*} pair,
and is a useful convenience to enable code to continue passing the
result of getOrInsertFunction() through to EmitCall, even once pointer
types lose their pointee-type.
Then:
- update the CallInst/InvokeInst instruction creation functions to
take a Callee,
- modify getOrInsertFunction to return FunctionCallee, and
- update all callers appropriately.
One area of particular note is the change to the sanitizer
code. Previously, they had been casting the result of
`getOrInsertFunction` to a `Function*` via
`checkSanitizerInterfaceFunction`, and storing that. That would report
an error if someone had already inserted a function declaraction with
a mismatching signature.
However, in general, LLVM allows for such mismatches, as
`getOrInsertFunction` will automatically insert a bitcast if
needed. As part of this cleanup, cause the sanitizer code to do the
same. (It will call its functions using the expected signature,
however they may have been declared.)
Finally, in a small number of locations, callers of
`getOrInsertFunction` actually were expecting/requiring that a brand
new function was being created. In such cases, I've switched them to
Function::Create instead.
Differential Revision: https://reviews.llvm.org/D57315
llvm-svn: 352827
2019-02-01 10:28:03 +08:00
|
|
|
FunctionCallee AtExit = M.getOrInsertFunction(
|
|
|
|
"__cxa_atexit",
|
|
|
|
FunctionType::get(Type::getInt32Ty(C),
|
|
|
|
{PointerType::get(AtExitFuncTy, 0), VoidStar, VoidStar},
|
|
|
|
/*isVarArg=*/false));
|
2017-12-15 08:17:10 +08:00
|
|
|
|
|
|
|
// Declare __dso_local.
|
|
|
|
Constant *DsoHandle = M.getNamedValue("__dso_handle");
|
|
|
|
if (!DsoHandle) {
|
|
|
|
Type *DsoHandleTy = Type::getInt8Ty(C);
|
2018-09-05 09:27:38 +08:00
|
|
|
GlobalVariable *Handle = new GlobalVariable(
|
|
|
|
M, DsoHandleTy, /*isConstant=*/true,
|
|
|
|
GlobalVariable::ExternalWeakLinkage, nullptr, "__dso_handle");
|
2017-12-15 08:17:10 +08:00
|
|
|
Handle->setVisibility(GlobalVariable::HiddenVisibility);
|
|
|
|
DsoHandle = Handle;
|
|
|
|
}
|
|
|
|
|
|
|
|
// For each unique priority level and associated symbol, generate a function
|
|
|
|
// to call all the destructors at that level, and a function to register the
|
|
|
|
// first function with __cxa_atexit.
|
|
|
|
for (auto &PriorityAndMore : DtorFuncs) {
|
|
|
|
uint16_t Priority = PriorityAndMore.first;
|
|
|
|
for (auto &AssociatedAndMore : PriorityAndMore.second) {
|
|
|
|
Constant *Associated = AssociatedAndMore.first;
|
|
|
|
|
|
|
|
Function *CallDtors = Function::Create(
|
2018-09-05 09:27:38 +08:00
|
|
|
AtExitFuncTy, Function::PrivateLinkage,
|
|
|
|
"call_dtors" +
|
|
|
|
(Priority != UINT16_MAX ? (Twine(".") + Twine(Priority))
|
|
|
|
: Twine()) +
|
|
|
|
(!Associated->isNullValue() ? (Twine(".") + Associated->getName())
|
|
|
|
: Twine()),
|
|
|
|
&M);
|
2017-12-15 08:17:10 +08:00
|
|
|
BasicBlock *BB = BasicBlock::Create(C, "body", CallDtors);
|
2019-02-02 04:43:25 +08:00
|
|
|
FunctionType *VoidVoid = FunctionType::get(Type::getVoidTy(C),
|
|
|
|
/*isVarArg=*/false);
|
2017-12-15 08:17:10 +08:00
|
|
|
|
|
|
|
for (auto Dtor : AssociatedAndMore.second)
|
2019-02-02 04:43:25 +08:00
|
|
|
CallInst::Create(VoidVoid, Dtor, "", BB);
|
2017-12-15 08:17:10 +08:00
|
|
|
ReturnInst::Create(C, BB);
|
|
|
|
|
|
|
|
Function *RegisterCallDtors = Function::Create(
|
2018-09-05 09:27:38 +08:00
|
|
|
VoidVoid, Function::PrivateLinkage,
|
|
|
|
"register_call_dtors" +
|
|
|
|
(Priority != UINT16_MAX ? (Twine(".") + Twine(Priority))
|
|
|
|
: Twine()) +
|
|
|
|
(!Associated->isNullValue() ? (Twine(".") + Associated->getName())
|
|
|
|
: Twine()),
|
|
|
|
&M);
|
2017-12-15 08:17:10 +08:00
|
|
|
BasicBlock *EntryBB = BasicBlock::Create(C, "entry", RegisterCallDtors);
|
|
|
|
BasicBlock *FailBB = BasicBlock::Create(C, "fail", RegisterCallDtors);
|
|
|
|
BasicBlock *RetBB = BasicBlock::Create(C, "return", RegisterCallDtors);
|
|
|
|
|
|
|
|
Value *Null = ConstantPointerNull::get(VoidStar);
|
2018-09-05 09:27:38 +08:00
|
|
|
Value *Args[] = {CallDtors, Null, DsoHandle};
|
2017-12-15 08:17:10 +08:00
|
|
|
Value *Res = CallInst::Create(AtExit, Args, "call", EntryBB);
|
|
|
|
Value *Cmp = new ICmpInst(*EntryBB, ICmpInst::ICMP_NE, Res,
|
|
|
|
Constant::getNullValue(Res->getType()));
|
|
|
|
BranchInst::Create(FailBB, RetBB, Cmp, EntryBB);
|
|
|
|
|
|
|
|
// If `__cxa_atexit` hits out-of-memory, trap, so that we don't misbehave.
|
2018-09-05 09:27:38 +08:00
|
|
|
// This should be very rare, because if the process is running out of
|
|
|
|
// memory before main has even started, something is wrong.
|
|
|
|
CallInst::Create(Intrinsic::getDeclaration(&M, Intrinsic::trap), "",
|
|
|
|
FailBB);
|
2017-12-15 08:17:10 +08:00
|
|
|
new UnreachableInst(C, FailBB);
|
|
|
|
|
|
|
|
ReturnInst::Create(C, RetBB);
|
|
|
|
|
|
|
|
// Now register the registration function with @llvm.global_ctors.
|
|
|
|
appendToGlobalCtors(M, RegisterCallDtors, Priority, Associated);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now that we've lowered everything, remove @llvm.global_dtors.
|
|
|
|
GV->eraseFromParent();
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|