[WebAssembly] Support bitcasted function addresses with varargs.

Generalize FixFunctionBitcasts to handle varargs functions. This in
particular fixes the case where clang bitcasts away a varargs when
calling a K&R-style function.

This avoids interacting with tricky ABI details because it operates
at the LLVM IR level before varargs ABI details are exposed.

This fixes PR35385.

llvm-svn: 319186
diff --git a/llvm/lib/MC/WasmObjectWriter.cpp b/llvm/lib/MC/WasmObjectWriter.cpp
index 2297084..6e9088b 100644
--- a/llvm/lib/MC/WasmObjectWriter.cpp
+++ b/llvm/lib/MC/WasmObjectWriter.cpp
@@ -1040,12 +1040,15 @@
   for (const MCSymbol &S : Asm.symbols()) {
     const auto &WS = static_cast<const MCSymbolWasm &>(S);
 
-    if (WS.isTemporary())
-      continue;
-
+    // Register types for all functions, including those with private linkage
+    // (making them
+    // because wasm always needs a type signature.
     if (WS.isFunction())
       registerFunctionType(WS);
 
+    if (WS.isTemporary())
+      continue;
+
     // If the symbol is not defined in this translation unit, import it.
     if (!WS.isDefined(/*SetUsed=*/false)) {
       WasmImport Import;
diff --git a/llvm/lib/Target/WebAssembly/WebAssemblyFixFunctionBitcasts.cpp b/llvm/lib/Target/WebAssembly/WebAssemblyFixFunctionBitcasts.cpp
index 19df75c..6473a2b 100644
--- a/llvm/lib/Target/WebAssembly/WebAssemblyFixFunctionBitcasts.cpp
+++ b/llvm/lib/Target/WebAssembly/WebAssemblyFixFunctionBitcasts.cpp
@@ -107,9 +107,10 @@
   // Determine what arguments to pass.
   SmallVector<Value *, 4> Args;
   Function::arg_iterator AI = Wrapper->arg_begin();
+  Function::arg_iterator AE = Wrapper->arg_end();
   FunctionType::param_iterator PI = F->getFunctionType()->param_begin();
   FunctionType::param_iterator PE = F->getFunctionType()->param_end();
-  for (; AI != Wrapper->arg_end() && PI != PE; ++AI, ++PI) {
+  for (; AI != AE && PI != PE; ++AI, ++PI) {
     if (AI->getType() != *PI) {
       Wrapper->eraseFromParent();
       return nullptr;
@@ -118,6 +119,9 @@
   }
   for (; PI != PE; ++PI)
     Args.push_back(UndefValue::get(*PI));
+  if (F->isVarArg())
+    for (; AI != AE; ++AI)
+      Args.push_back(&*AI);
 
   CallInst *Call = CallInst::Create(F, Args, "", BB);
 
@@ -158,11 +162,6 @@
     if (!Ty)
       continue;
 
-    // Wasm varargs are not ABI-compatible with non-varargs. Just ignore
-    // such casts for now.
-    if (Ty->isVarArg() || F->isVarArg())
-      continue;
-
     auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr));
     if (Pair.second)
       Pair.first->second = CreateWrapper(F, Ty);