Coverage Report

Created: 2022-01-25 06:29

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptx86ABIFixups.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- RenderScriptx86ABIFixups.cpp --------------------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
9
#include <set>
10
11
#include "llvm/ADT/StringRef.h"
12
#include "llvm/IR/BasicBlock.h"
13
#include "llvm/IR/Constants.h"
14
#include "llvm/IR/Function.h"
15
#include "llvm/IR/Instruction.h"
16
#include "llvm/IR/Instructions.h"
17
#include "llvm/IR/Module.h"
18
#include "llvm/IRReader/IRReader.h"
19
#include "llvm/Pass.h"
20
21
#include "lldb/Target/Process.h"
22
#include "lldb/Utility/Log.h"
23
24
using namespace lldb_private;
25
26
0
static bool isRSAPICall(llvm::Module &module, llvm::CallInst *call_inst) {
27
  // TODO get the list of renderscript modules from lldb and check if
28
  // this llvm::Module calls into any of them.
29
0
  (void)module;
30
0
  const auto func_name = call_inst->getCalledFunction()->getName();
31
0
  if (func_name.startswith("llvm") || func_name.startswith("lldb"))
32
0
    return false;
33
34
0
  if (call_inst->getCalledFunction()->isIntrinsic())
35
0
    return false;
36
37
0
  return true;
38
0
}
39
40
static bool isRSLargeReturnCall(llvm::Module &module,
41
0
                                llvm::CallInst *call_inst) {
42
  // i686 and x86_64 returns for large vectors in the RenderScript API are not
43
  // handled as normal register pairs, but as a hidden sret type. This is not
44
  // reflected in the debug info or mangled symbol name, and the android ABI
45
  // for x86 and x86_64, (as well as the emulators) specifies there is no AVX,
46
  // so bcc generates an sret function because we cannot natively return
47
  // 256 bit vectors.
48
  // This function simply checks whether a function has a > 128bit return type.
49
  // It is perhaps an unreliable heuristic, and relies on bcc not generating
50
  // AVX code, so if the android ABI one day provides for AVX, this function
51
  // may go out of fashion.
52
0
  (void)module;
53
0
  if (!call_inst || !call_inst->getCalledFunction())
54
0
    return false;
55
56
0
  return call_inst->getCalledFunction()
57
0
             ->getReturnType()
58
0
             ->getPrimitiveSizeInBits() > 128;
59
0
}
60
61
0
static bool isRSAllocationPtrTy(const llvm::Type *type) {
62
0
  if (!type->isPointerTy())
63
0
    return false;
64
0
  auto ptr_type = type->getPointerElementType();
65
66
0
  return ptr_type->isStructTy() &&
67
0
         ptr_type->getStructName().startswith("struct.rs_allocation");
68
0
}
69
70
static bool isRSAllocationTyCallSite(llvm::Module &module,
71
0
                                     llvm::CallInst *call_inst) {
72
0
  (void)module;
73
0
  if (!call_inst->hasByValArgument())
74
0
    return false;
75
0
  for (const auto *param : call_inst->operand_values())
76
0
    if (isRSAllocationPtrTy(param->getType()))
77
0
      return true;
78
0
  return false;
79
0
}
80
81
0
static llvm::FunctionType *cloneToStructRetFnTy(llvm::CallInst *call_inst) {
82
  // on x86 StructReturn functions return a pointer to the return value, rather
83
  // than the return value itself
84
  // [ref](http://www.agner.org/optimize/calling_conventions.pdf section 6). We
85
  // create a return type by getting the pointer type of the old return type,
86
  // and inserting a new initial argument of pointer type of the original
87
  // return type.
88
0
  Log *log(
89
0
      GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_EXPRESSIONS));
90
91
0
  assert(call_inst && "no CallInst");
92
0
  llvm::Function *orig = call_inst->getCalledFunction();
93
0
  assert(orig && "CallInst has no called function");
94
0
  llvm::FunctionType *orig_type = orig->getFunctionType();
95
0
  auto name = orig->getName();
96
0
  LLDB_LOGF(log, "%s - cloning to StructRet function for '%s'", __FUNCTION__,
97
0
            name.str().c_str());
98
99
0
  unsigned num_params = orig_type->getNumParams();
100
0
  std::vector<llvm::Type *> new_params{num_params + 1, nullptr};
101
0
  std::vector<llvm::Type *> params{orig_type->param_begin(),
102
0
                                   orig_type->param_end()};
103
104
  // This may not work if the function is somehow declared void as llvm is
105
  // strongly typed and represents void* with i8*
106
0
  assert(!orig_type->getReturnType()->isVoidTy() &&
107
0
         "Cannot add StructRet attribute to void function");
108
0
  llvm::PointerType *return_type_ptr_type =
109
0
      llvm::PointerType::getUnqual(orig->getReturnType());
110
0
  assert(return_type_ptr_type &&
111
0
         "failed to get function return type PointerType");
112
0
  if (!return_type_ptr_type)
113
0
    return nullptr;
114
115
0
  LLDB_LOGF(log,
116
0
            "%s - return type pointer type for StructRet clone @ '0x%p':\n",
117
0
            __FUNCTION__, (void *)return_type_ptr_type);
118
  // put the sret pointer argument in place at the beginning of the
119
  // argument list.
120
0
  params.emplace(params.begin(), return_type_ptr_type);
121
0
  assert(params.size() == num_params + 1);
122
0
  return llvm::FunctionType::get(return_type_ptr_type, params,
123
0
                                 orig->isVarArg());
124
0
}
125
126
static bool
127
findRSCallSites(llvm::Module &module, std::set<llvm::CallInst *> &rs_callsites,
128
0
                bool (*predicate)(llvm::Module &, llvm::CallInst *)) {
129
0
  bool found = false;
130
131
0
  for (auto &func : module.getFunctionList())
132
0
    for (auto &block : func.getBasicBlockList())
133
0
      for (auto &inst : block) {
134
0
        llvm::CallInst *call_inst =
135
0
            llvm::dyn_cast_or_null<llvm::CallInst>(&inst);
136
0
        if (!call_inst || !call_inst->getCalledFunction())
137
          // This is not the call-site you are looking for...
138
0
          continue;
139
0
        if (isRSAPICall(module, call_inst) && predicate(module, call_inst)) {
140
0
          rs_callsites.insert(call_inst);
141
0
          found = true;
142
0
        }
143
0
      }
144
0
  return found;
145
0
}
146
147
0
static bool fixupX86StructRetCalls(llvm::Module &module) {
148
0
  bool changed = false;
149
  // changing a basic block while iterating over it seems to have some
150
  // undefined behaviour going on so we find all RS callsites first, then fix
151
  // them up after consuming the iterator.
152
0
  std::set<llvm::CallInst *> rs_callsites;
153
0
  if (!findRSCallSites(module, rs_callsites, isRSLargeReturnCall))
154
0
    return false;
155
156
0
  for (auto call_inst : rs_callsites) {
157
0
    llvm::FunctionType *new_func_type = cloneToStructRetFnTy(call_inst);
158
0
    assert(new_func_type &&
159
0
           "failed to clone functionType for Renderscript ABI fixup");
160
161
0
    llvm::Function *func = call_inst->getCalledFunction();
162
0
    assert(func && "cannot resolve function in RenderScriptRuntime");
163
    // Copy the original call arguments
164
0
    std::vector<llvm::Value *> new_call_args(call_inst->arg_begin(),
165
0
                                             call_inst->arg_end());
166
167
    // Allocate enough space to store the return value of the original function
168
    // we pass a pointer to this allocation as the StructRet param, and then
169
    // copy its value into the lldb return value
170
0
    const llvm::DataLayout &DL = module.getDataLayout();
171
0
    llvm::AllocaInst *return_value_alloc = new llvm::AllocaInst(
172
0
      func->getReturnType(), DL.getAllocaAddrSpace(), "var_vector_return_alloc",
173
0
      call_inst);
174
    // use the new allocation as the new first argument
175
0
    new_call_args.emplace(new_call_args.begin(),
176
0
                          llvm::cast<llvm::Value>(return_value_alloc));
177
0
    llvm::PointerType *new_func_ptr_type =
178
0
        llvm::PointerType::get(new_func_type, 0);
179
    // Create the type cast from the old function type to the new one
180
0
    llvm::Constant *new_func_cast = llvm::ConstantExpr::getCast(
181
0
        llvm::Instruction::BitCast, func, new_func_ptr_type);
182
    // create an allocation for a new function pointer
183
0
    llvm::AllocaInst *new_func_ptr =
184
0
        new llvm::AllocaInst(new_func_ptr_type, DL.getAllocaAddrSpace(),
185
0
                             "new_func_ptr", call_inst);
186
    // store the new_func_cast to the newly allocated space
187
0
    (new llvm::StoreInst(new_func_cast, new_func_ptr, call_inst))
188
0
        ->setName("new_func_ptr_load_cast");
189
    // load the new function address ready for a jump
190
0
    llvm::LoadInst *new_func_addr_load =
191
0
        new llvm::LoadInst(new_func_ptr->getType()->getPointerElementType(),
192
0
                           new_func_ptr, "load_func_pointer", call_inst);
193
    // and create a callinstruction from it
194
0
    llvm::CallInst *new_call_inst =
195
0
        llvm::CallInst::Create(new_func_type, new_func_addr_load, new_call_args,
196
0
                               "new_func_call", call_inst);
197
0
    new_call_inst->setCallingConv(call_inst->getCallingConv());
198
0
    new_call_inst->setTailCall(call_inst->isTailCall());
199
0
    llvm::LoadInst *lldb_save_result_address = new llvm::LoadInst(
200
0
        return_value_alloc->getType()->getPointerElementType(),
201
0
        return_value_alloc, "save_return_val", call_inst);
202
203
    // Now remove the old broken call
204
0
    call_inst->replaceAllUsesWith(lldb_save_result_address);
205
0
    call_inst->eraseFromParent();
206
0
    changed = true;
207
0
  }
208
0
  return changed;
209
0
}
210
211
0
static bool fixupRSAllocationStructByValCalls(llvm::Module &module) {
212
  // On x86_64, calls to functions in the RS runtime that take an
213
  // `rs_allocation` type argument are actually handled as by-ref params by
214
  // bcc, but appear to be passed by value by lldb (the callsite all use
215
  // `struct byval`). On x86_64 Linux, struct arguments are transferred in
216
  // registers if the struct size is no bigger than 128bits
217
  // [ref](http://www.agner.org/optimize/calling_conventions.pdf) section 7.1
218
  // "Passing and returning objects" otherwise passed on the stack. an object
219
  // of type `rs_allocation` is actually 256bits, so should be passed on the
220
  // stack. However, code generated by bcc actually treats formal params of
221
  // type `rs_allocation` as `rs_allocation *` so we need to convert the
222
  // calling convention to pass by reference, and remove any hint of byval from
223
  // formal parameters.
224
0
  bool changed = false;
225
0
  std::set<llvm::CallInst *> rs_callsites;
226
0
  if (!findRSCallSites(module, rs_callsites, isRSAllocationTyCallSite))
227
0
    return false;
228
229
0
  std::set<llvm::Function *> rs_functions;
230
231
  // for all call instructions
232
0
  for (auto call_inst : rs_callsites) {
233
    // add the called function to a set so that we can strip its byval
234
    // attributes in another pass
235
0
    rs_functions.insert(call_inst->getCalledFunction());
236
237
    // get the function attributes
238
0
    llvm::AttributeList call_attribs = call_inst->getAttributes();
239
240
    // iterate over the argument attributes
241
0
    for (unsigned I : call_attribs.indexes()) {
242
      // if this argument is passed by val
243
0
      if (call_attribs.hasAttributeAtIndex(I, llvm::Attribute::ByVal)) {
244
        // strip away the byval attribute
245
0
        call_inst->removeAttributeAtIndex(I, llvm::Attribute::ByVal);
246
0
        changed = true;
247
0
      }
248
0
    }
249
0
  }
250
251
  // for all called function decls
252
0
  for (auto func : rs_functions) {
253
    // inspect all of the arguments in the call
254
0
    for (auto &arg : func->args()) {
255
0
      if (arg.hasByValAttr()) {
256
0
        arg.removeAttr(llvm::Attribute::ByVal);
257
0
        changed = true;
258
0
      }
259
0
    }
260
0
  }
261
0
  return changed;
262
0
}
263
264
namespace lldb_private {
265
namespace lldb_renderscript {
266
267
0
bool fixupX86FunctionCalls(llvm::Module &module) {
268
0
  return fixupX86StructRetCalls(module);
269
0
}
270
271
0
bool fixupX86_64FunctionCalls(llvm::Module &module) {
272
0
  bool changed = false;
273
0
  changed |= fixupX86StructRetCalls(module);
274
0
  changed |= fixupRSAllocationStructByValCalls(module);
275
0
  return changed;
276
0
}
277
278
} // end namespace lldb_renderscript
279
} // end namespace lldb_private