11b637458SDan Gohman //===-- WebAssemblyFixFunctionBitcasts.cpp - Fix function bitcasts --------===//
21b637458SDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
61b637458SDan Gohman //
71b637458SDan Gohman //===----------------------------------------------------------------------===//
81b637458SDan Gohman ///
91b637458SDan Gohman /// \file
105f8f34e4SAdrian Prantl /// Fix bitcasted functions.
111b637458SDan Gohman ///
121b637458SDan Gohman /// WebAssembly requires caller and callee signatures to match, however in LLVM,
131b637458SDan Gohman /// some amount of slop is vaguely permitted. Detect mismatch by looking for
141b637458SDan Gohman /// bitcasts of functions and rewrite them to use wrapper functions instead.
151b637458SDan Gohman ///
161b637458SDan Gohman /// This doesn't catch all cases, such as when a function's address is taken in
171b637458SDan Gohman /// one place and casted in another, but it works for many common cases.
181b637458SDan Gohman ///
191b637458SDan Gohman /// Note that LLVM already optimizes away function bitcasts in common cases by
201b637458SDan Gohman /// dropping arguments as needed, so this pass only ends up getting used in less
211b637458SDan Gohman /// common cases.
221b637458SDan Gohman ///
231b637458SDan Gohman //===----------------------------------------------------------------------===//
241b637458SDan Gohman 
251b637458SDan Gohman #include "WebAssembly.h"
261b637458SDan Gohman #include "llvm/IR/Constants.h"
271b637458SDan Gohman #include "llvm/IR/Instructions.h"
281b637458SDan Gohman #include "llvm/IR/Module.h"
291b637458SDan Gohman #include "llvm/IR/Operator.h"
301b637458SDan Gohman #include "llvm/Pass.h"
311b637458SDan Gohman #include "llvm/Support/Debug.h"
321b637458SDan Gohman #include "llvm/Support/raw_ostream.h"
331b637458SDan Gohman using namespace llvm;
341b637458SDan Gohman 
351b637458SDan Gohman #define DEBUG_TYPE "wasm-fix-function-bitcasts"
361b637458SDan Gohman 
371b637458SDan Gohman namespace {
381b637458SDan Gohman class FixFunctionBitcasts final : public ModulePass {
getPassName() const391b637458SDan Gohman   StringRef getPassName() const override {
401b637458SDan Gohman     return "WebAssembly Fix Function Bitcasts";
411b637458SDan Gohman   }
421b637458SDan Gohman 
getAnalysisUsage(AnalysisUsage & AU) const431b637458SDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
441b637458SDan Gohman     AU.setPreservesCFG();
451b637458SDan Gohman     ModulePass::getAnalysisUsage(AU);
461b637458SDan Gohman   }
471b637458SDan Gohman 
481b637458SDan Gohman   bool runOnModule(Module &M) override;
491b637458SDan Gohman 
501b637458SDan Gohman public:
511b637458SDan Gohman   static char ID;
FixFunctionBitcasts()521b637458SDan Gohman   FixFunctionBitcasts() : ModulePass(ID) {}
531b637458SDan Gohman };
541b637458SDan Gohman } // End anonymous namespace
551b637458SDan Gohman 
561b637458SDan Gohman char FixFunctionBitcasts::ID = 0;
5740926451SJacob Gravelle INITIALIZE_PASS(FixFunctionBitcasts, DEBUG_TYPE,
5840926451SJacob Gravelle                 "Fix mismatching bitcasts for WebAssembly", false, false)
5940926451SJacob Gravelle 
createWebAssemblyFixFunctionBitcasts()601b637458SDan Gohman ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() {
611b637458SDan Gohman   return new FixFunctionBitcasts();
621b637458SDan Gohman }
631b637458SDan Gohman 
641b637458SDan Gohman // Recursively descend the def-use lists from V to find non-bitcast users of
651b637458SDan Gohman // bitcasts of V.
findUses(Value * V,Function & F,SmallVectorImpl<std::pair<CallBase *,Function * >> & Uses)6618c56a07SHeejin Ahn static void findUses(Value *V, Function &F,
67*7f058ce8SNikita Popov                      SmallVectorImpl<std::pair<CallBase *, Function *>> &Uses) {
68*7f058ce8SNikita Popov   for (User *U : V->users()) {
69*7f058ce8SNikita Popov     if (auto *BC = dyn_cast<BitCastOperator>(U))
70*7f058ce8SNikita Popov       findUses(BC, F, Uses);
71*7f058ce8SNikita Popov     else if (auto *A = dyn_cast<GlobalAlias>(U))
72*7f058ce8SNikita Popov       findUses(A, F, Uses);
73*7f058ce8SNikita Popov     else if (auto *CB = dyn_cast<CallBase>(U)) {
74a58b62b4SCraig Topper       Value *Callee = CB->getCalledOperand();
7537af00e7SJacob Gravelle       if (Callee != V)
7637af00e7SJacob Gravelle         // Skip calls where the function isn't the callee
7737af00e7SJacob Gravelle         continue;
78*7f058ce8SNikita Popov       if (CB->getFunctionType() == F.getValueType())
79*7f058ce8SNikita Popov         // Skip uses that are immediately called
8037af00e7SJacob Gravelle         continue;
81*7f058ce8SNikita Popov       Uses.push_back(std::make_pair(CB, &F));
821b637458SDan Gohman     }
831b637458SDan Gohman   }
847acb42a4SDerek Schuff }
851b637458SDan Gohman 
861b637458SDan Gohman // Create a wrapper function with type Ty that calls F (which may have a
871b637458SDan Gohman // different type). Attempt to support common bitcasted function idioms:
881b637458SDan Gohman //  - Call with more arguments than needed: arguments are dropped
891b637458SDan Gohman //  - Call with fewer arguments than needed: arguments are filled in with undef
901b637458SDan Gohman //  - Return value is not needed: drop it
911b637458SDan Gohman //  - Return value needed but not present: supply an undef
920e2ceb81SDan Gohman //
9341d7047dSSam Clegg // If the all the argument types of trivially castable to one another (i.e.
9441d7047dSSam Clegg // I32 vs pointer type) then we don't create a wrapper at all (return nullptr
9541d7047dSSam Clegg // instead).
9641d7047dSSam Clegg //
9788599bf6SSam Clegg // If there is a type mismatch that we know would result in an invalid wasm
9888599bf6SSam Clegg // module then generate wrapper that contains unreachable (i.e. abort at
9988599bf6SSam Clegg // runtime).  Such programs are deep into undefined behaviour territory,
10041d7047dSSam Clegg // but we choose to fail at runtime rather than generate and invalid module
10141d7047dSSam Clegg // or fail at compiler time.  The reason we delay the error is that we want
10241d7047dSSam Clegg // to support the CMake which expects to be able to compile and link programs
10341d7047dSSam Clegg // that refer to functions with entirely incorrect signatures (this is how
10441d7047dSSam Clegg // CMake detects the existence of a function in a toolchain).
10588599bf6SSam Clegg //
10688599bf6SSam Clegg // For bitcasts that involve struct types we don't know at this stage if they
10788599bf6SSam Clegg // would be equivalent at the wasm level and so we can't know if we need to
10888599bf6SSam Clegg // generate a wrapper.
createWrapper(Function * F,FunctionType * Ty)10918c56a07SHeejin Ahn static Function *createWrapper(Function *F, FunctionType *Ty) {
1101b637458SDan Gohman   Module *M = F->getParent();
1111b637458SDan Gohman 
11241d7047dSSam Clegg   Function *Wrapper = Function::Create(Ty, Function::PrivateLinkage,
11341d7047dSSam Clegg                                        F->getName() + "_bitcast", M);
1141b637458SDan Gohman   BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
11541d7047dSSam Clegg   const DataLayout &DL = BB->getModule()->getDataLayout();
1161b637458SDan Gohman 
1171b637458SDan Gohman   // Determine what arguments to pass.
1181b637458SDan Gohman   SmallVector<Value *, 4> Args;
1191b637458SDan Gohman   Function::arg_iterator AI = Wrapper->arg_begin();
1202803bfafSDan Gohman   Function::arg_iterator AE = Wrapper->arg_end();
1211b637458SDan Gohman   FunctionType::param_iterator PI = F->getFunctionType()->param_begin();
1221b637458SDan Gohman   FunctionType::param_iterator PE = F->getFunctionType()->param_end();
12341d7047dSSam Clegg   bool TypeMismatch = false;
12441d7047dSSam Clegg   bool WrapperNeeded = false;
12541d7047dSSam Clegg 
12688599bf6SSam Clegg   Type *ExpectedRtnType = F->getFunctionType()->getReturnType();
12788599bf6SSam Clegg   Type *RtnType = Ty->getReturnType();
12888599bf6SSam Clegg 
12941d7047dSSam Clegg   if ((F->getFunctionType()->getNumParams() != Ty->getNumParams()) ||
13088599bf6SSam Clegg       (F->getFunctionType()->isVarArg() != Ty->isVarArg()) ||
13188599bf6SSam Clegg       (ExpectedRtnType != RtnType))
13241d7047dSSam Clegg     WrapperNeeded = true;
13341d7047dSSam Clegg 
1342803bfafSDan Gohman   for (; AI != AE && PI != PE; ++AI, ++PI) {
13541d7047dSSam Clegg     Type *ArgType = AI->getType();
13641d7047dSSam Clegg     Type *ParamType = *PI;
13741d7047dSSam Clegg 
13841d7047dSSam Clegg     if (ArgType == ParamType) {
1391b637458SDan Gohman       Args.push_back(&*AI);
14041d7047dSSam Clegg     } else {
14141d7047dSSam Clegg       if (CastInst::isBitOrNoopPointerCastable(ArgType, ParamType, DL)) {
14241d7047dSSam Clegg         Instruction *PtrCast =
14341d7047dSSam Clegg             CastInst::CreateBitOrPointerCast(AI, ParamType, "cast");
14441d7047dSSam Clegg         BB->getInstList().push_back(PtrCast);
14541d7047dSSam Clegg         Args.push_back(PtrCast);
14688599bf6SSam Clegg       } else if (ArgType->isStructTy() || ParamType->isStructTy()) {
14718c56a07SHeejin Ahn         LLVM_DEBUG(dbgs() << "createWrapper: struct param type in bitcast: "
14888599bf6SSam Clegg                           << F->getName() << "\n");
14988599bf6SSam Clegg         WrapperNeeded = false;
15041d7047dSSam Clegg       } else {
15118c56a07SHeejin Ahn         LLVM_DEBUG(dbgs() << "createWrapper: arg type mismatch calling: "
15241d7047dSSam Clegg                           << F->getName() << "\n");
15341d7047dSSam Clegg         LLVM_DEBUG(dbgs() << "Arg[" << Args.size() << "] Expected: "
15441d7047dSSam Clegg                           << *ParamType << " Got: " << *ArgType << "\n");
15541d7047dSSam Clegg         TypeMismatch = true;
15641d7047dSSam Clegg         break;
1571b637458SDan Gohman       }
15841d7047dSSam Clegg     }
15941d7047dSSam Clegg   }
16041d7047dSSam Clegg 
16188599bf6SSam Clegg   if (WrapperNeeded && !TypeMismatch) {
1621b637458SDan Gohman     for (; PI != PE; ++PI)
1631b637458SDan Gohman       Args.push_back(UndefValue::get(*PI));
1642803bfafSDan Gohman     if (F->isVarArg())
1652803bfafSDan Gohman       for (; AI != AE; ++AI)
1662803bfafSDan Gohman         Args.push_back(&*AI);
1671b637458SDan Gohman 
1681b637458SDan Gohman     CallInst *Call = CallInst::Create(F, Args, "", BB);
1691b637458SDan Gohman 
17041d7047dSSam Clegg     Type *ExpectedRtnType = F->getFunctionType()->getReturnType();
17141d7047dSSam Clegg     Type *RtnType = Ty->getReturnType();
1721b637458SDan Gohman     // Determine what value to return.
17341d7047dSSam Clegg     if (RtnType->isVoidTy()) {
1741b637458SDan Gohman       ReturnInst::Create(M->getContext(), BB);
17541d7047dSSam Clegg     } else if (ExpectedRtnType->isVoidTy()) {
17688599bf6SSam Clegg       LLVM_DEBUG(dbgs() << "Creating dummy return: " << *RtnType << "\n");
17741d7047dSSam Clegg       ReturnInst::Create(M->getContext(), UndefValue::get(RtnType), BB);
17841d7047dSSam Clegg     } else if (RtnType == ExpectedRtnType) {
1791b637458SDan Gohman       ReturnInst::Create(M->getContext(), Call, BB);
18041d7047dSSam Clegg     } else if (CastInst::isBitOrNoopPointerCastable(ExpectedRtnType, RtnType,
18141d7047dSSam Clegg                                                     DL)) {
18241d7047dSSam Clegg       Instruction *Cast =
18341d7047dSSam Clegg           CastInst::CreateBitOrPointerCast(Call, RtnType, "cast");
18441d7047dSSam Clegg       BB->getInstList().push_back(Cast);
18541d7047dSSam Clegg       ReturnInst::Create(M->getContext(), Cast, BB);
18688599bf6SSam Clegg     } else if (RtnType->isStructTy() || ExpectedRtnType->isStructTy()) {
18718c56a07SHeejin Ahn       LLVM_DEBUG(dbgs() << "createWrapper: struct return type in bitcast: "
18888599bf6SSam Clegg                         << F->getName() << "\n");
18988599bf6SSam Clegg       WrapperNeeded = false;
19041d7047dSSam Clegg     } else {
19118c56a07SHeejin Ahn       LLVM_DEBUG(dbgs() << "createWrapper: return type mismatch calling: "
19241d7047dSSam Clegg                         << F->getName() << "\n");
19341d7047dSSam Clegg       LLVM_DEBUG(dbgs() << "Expected: " << *ExpectedRtnType
19441d7047dSSam Clegg                         << " Got: " << *RtnType << "\n");
19541d7047dSSam Clegg       TypeMismatch = true;
19641d7047dSSam Clegg     }
19741d7047dSSam Clegg   }
19841d7047dSSam Clegg 
19941d7047dSSam Clegg   if (TypeMismatch) {
20088599bf6SSam Clegg     // Create a new wrapper that simply contains `unreachable`.
20188599bf6SSam Clegg     Wrapper->eraseFromParent();
202f208f631SHeejin Ahn     Wrapper = Function::Create(Ty, Function::PrivateLinkage,
203f208f631SHeejin Ahn                                F->getName() + "_bitcast_invalid", M);
20488599bf6SSam Clegg     BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
20541d7047dSSam Clegg     new UnreachableInst(M->getContext(), BB);
20641d7047dSSam Clegg     Wrapper->setName(F->getName() + "_bitcast_invalid");
20741d7047dSSam Clegg   } else if (!WrapperNeeded) {
20818c56a07SHeejin Ahn     LLVM_DEBUG(dbgs() << "createWrapper: no wrapper needed: " << F->getName()
20941d7047dSSam Clegg                       << "\n");
2100e2ceb81SDan Gohman     Wrapper->eraseFromParent();
2110e2ceb81SDan Gohman     return nullptr;
2120e2ceb81SDan Gohman   }
21318c56a07SHeejin Ahn   LLVM_DEBUG(dbgs() << "createWrapper: " << F->getName() << "\n");
2141b637458SDan Gohman   return Wrapper;
2151b637458SDan Gohman }
2161b637458SDan Gohman 
2174684f824SDan Gohman // Test whether a main function with type FuncTy should be rewritten to have
2184684f824SDan Gohman // type MainTy.
shouldFixMainFunction(FunctionType * FuncTy,FunctionType * MainTy)219711950c1SBenjamin Kramer static bool shouldFixMainFunction(FunctionType *FuncTy, FunctionType *MainTy) {
2204684f824SDan Gohman   // Only fix the main function if it's the standard zero-arg form. That way,
2214684f824SDan Gohman   // the standard cases will work as expected, and users will see signature
2224684f824SDan Gohman   // mismatches from the linker for non-standard cases.
2234684f824SDan Gohman   return FuncTy->getReturnType() == MainTy->getReturnType() &&
2244684f824SDan Gohman          FuncTy->getNumParams() == 0 &&
2254684f824SDan Gohman          !FuncTy->isVarArg();
2264684f824SDan Gohman }
2274684f824SDan Gohman 
runOnModule(Module & M)2281b637458SDan Gohman bool FixFunctionBitcasts::runOnModule(Module &M) {
229569f0909SHeejin Ahn   LLVM_DEBUG(dbgs() << "********** Fix Function Bitcasts **********\n");
230569f0909SHeejin Ahn 
2316736f590SDan Gohman   Function *Main = nullptr;
2326736f590SDan Gohman   CallInst *CallMain = nullptr;
233*7f058ce8SNikita Popov   SmallVector<std::pair<CallBase *, Function *>, 0> Uses;
234d5eda355SDan Gohman 
2351b637458SDan Gohman   // Collect all the places that need wrappers.
2366736f590SDan Gohman   for (Function &F : M) {
23708670d43SYuta Saito     // Skip to fix when the function is swiftcc because swiftcc allows
23808670d43SYuta Saito     // bitcast type difference for swiftself and swifterror.
23908670d43SYuta Saito     if (F.getCallingConv() == CallingConv::Swift)
24008670d43SYuta Saito       continue;
241*7f058ce8SNikita Popov     findUses(&F, F, Uses);
2426736f590SDan Gohman 
2436736f590SDan Gohman     // If we have a "main" function, and its type isn't
2446736f590SDan Gohman     // "int main(int argc, char *argv[])", create an artificial call with it
2456736f590SDan Gohman     // bitcasted to that type so that we generate a wrapper for it, so that
2466736f590SDan Gohman     // the C runtime can call it.
2474684f824SDan Gohman     if (F.getName() == "main") {
2486736f590SDan Gohman       Main = &F;
2496736f590SDan Gohman       LLVMContext &C = M.getContext();
25079c054f6SSam Clegg       Type *MainArgTys[] = {Type::getInt32Ty(C),
25179c054f6SSam Clegg                             PointerType::get(Type::getInt8PtrTy(C), 0)};
2526736f590SDan Gohman       FunctionType *MainTy = FunctionType::get(Type::getInt32Ty(C), MainArgTys,
2536736f590SDan Gohman                                                /*isVarArg=*/false);
25418c56a07SHeejin Ahn       if (shouldFixMainFunction(F.getFunctionType(), MainTy)) {
25579c054f6SSam Clegg         LLVM_DEBUG(dbgs() << "Found `main` function with incorrect type: "
25679c054f6SSam Clegg                           << *F.getFunctionType() << "\n");
257f208f631SHeejin Ahn         Value *Args[] = {UndefValue::get(MainArgTys[0]),
258f208f631SHeejin Ahn                          UndefValue::get(MainArgTys[1])};
259f208f631SHeejin Ahn         Value *Casted =
260f208f631SHeejin Ahn             ConstantExpr::getBitCast(Main, PointerType::get(MainTy, 0));
2617976eb58SJames Y Knight         CallMain = CallInst::Create(MainTy, Casted, Args, "call_main");
262*7f058ce8SNikita Popov         Uses.push_back(std::make_pair(CallMain, &F));
2636736f590SDan Gohman       }
2646736f590SDan Gohman     }
2656736f590SDan Gohman   }
2661b637458SDan Gohman 
2671b637458SDan Gohman   DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers;
2681b637458SDan Gohman 
2691b637458SDan Gohman   for (auto &UseFunc : Uses) {
270*7f058ce8SNikita Popov     CallBase *CB = UseFunc.first;
2711b637458SDan Gohman     Function *F = UseFunc.second;
272*7f058ce8SNikita Popov     FunctionType *Ty = CB->getFunctionType();
2731b637458SDan Gohman 
2741b637458SDan Gohman     auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr));
2751b637458SDan Gohman     if (Pair.second)
27618c56a07SHeejin Ahn       Pair.first->second = createWrapper(F, Ty);
2771b637458SDan Gohman 
2780e2ceb81SDan Gohman     Function *Wrapper = Pair.first->second;
2790e2ceb81SDan Gohman     if (!Wrapper)
2800e2ceb81SDan Gohman       continue;
2810e2ceb81SDan Gohman 
282*7f058ce8SNikita Popov     CB->setCalledOperand(Wrapper);
2831b637458SDan Gohman   }
2841b637458SDan Gohman 
2856736f590SDan Gohman   // If we created a wrapper for main, rename the wrapper so that it's the
2866736f590SDan Gohman   // one that gets called from startup.
2876736f590SDan Gohman   if (CallMain) {
2886736f590SDan Gohman     Main->setName("__original_main");
28918c56a07SHeejin Ahn     auto *MainWrapper =
290a58b62b4SCraig Topper         cast<Function>(CallMain->getCalledOperand()->stripPointerCasts());
2914684f824SDan Gohman     delete CallMain;
2924684f824SDan Gohman     if (Main->isDeclaration()) {
2934684f824SDan Gohman       // The wrapper is not needed in this case as we don't need to export
2944684f824SDan Gohman       // it to anyone else.
2954684f824SDan Gohman       MainWrapper->eraseFromParent();
2964684f824SDan Gohman     } else {
2974684f824SDan Gohman       // Otherwise give the wrapper the same linkage as the original main
2984684f824SDan Gohman       // function, so that it can be called from the same places.
2996736f590SDan Gohman       MainWrapper->setName("main");
3006736f590SDan Gohman       MainWrapper->setLinkage(Main->getLinkage());
3016736f590SDan Gohman       MainWrapper->setVisibility(Main->getVisibility());
3024684f824SDan Gohman     }
3036736f590SDan Gohman   }
3046736f590SDan Gohman 
3051b637458SDan Gohman   return true;
3061b637458SDan Gohman }
307