slang_rs_backend.cpp revision 68fc02ca4a7235e2981be5eee4ad968a9d3928c0
1/*
2 * Copyright 2010, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "slang_rs_backend.h"
18
19#include <vector>
20#include <string>
21
22#include "llvm/Metadata.h"
23#include "llvm/Constant.h"
24#include "llvm/Constants.h"
25#include "llvm/Module.h"
26#include "llvm/Function.h"
27#include "llvm/DerivedTypes.h"
28
29#include "llvm/System/Path.h"
30
31#include "llvm/Support/IRBuilder.h"
32
33#include "llvm/ADT/Twine.h"
34#include "llvm/ADT/StringExtras.h"
35
36#include "clang/AST/DeclGroup.h"
37
38#include "slang_rs.h"
39#include "slang_rs_context.h"
40#include "slang_rs_metadata.h"
41#include "slang_rs_export_var.h"
42#include "slang_rs_export_func.h"
43#include "slang_rs_export_type.h"
44
45using namespace slang;
46
47RSBackend::RSBackend(RSContext *Context,
48                     clang::Diagnostic &Diags,
49                     const clang::CodeGenOptions &CodeGenOpts,
50                     const clang::TargetOptions &TargetOpts,
51                     const PragmaList &Pragmas,
52                     llvm::raw_ostream *OS,
53                     Slang::OutputType OT,
54                     clang::SourceManager &SourceMgr,
55                     bool AllowRSPrefix)
56    : Backend(Diags,
57              CodeGenOpts,
58              TargetOpts,
59              Pragmas,
60              OS,
61              OT),
62      mContext(Context),
63      mSourceMgr(SourceMgr),
64      mAllowRSPrefix(AllowRSPrefix),
65      mExportVarMetadata(NULL),
66      mExportFuncMetadata(NULL),
67      mExportTypeMetadata(NULL) {
68  return;
69}
70
71void RSBackend::HandleTopLevelDecl(clang::DeclGroupRef D) {
72  // Disallow user-defined functions with prefix "rs"
73  if (!mAllowRSPrefix) {
74    // Iterate all function declarations in the program.
75    for (clang::DeclGroupRef::iterator I = D.begin(), E = D.end();
76         I != E; I++) {
77      clang::FunctionDecl *FD = dyn_cast<clang::FunctionDecl>(*I);
78      if (FD == NULL)
79        continue;
80      if (FD->getName().startswith("rs")) {  // Check prefix
81        clang::FullSourceLoc FSL(FD->getLocStart(), mSourceMgr);
82        clang::PresumedLoc PLoc = mSourceMgr.getPresumedLoc(FSL);
83        llvm::sys::Path HeaderFilename(PLoc.getFilename());
84
85        // Skip if that function declared in the RS default header.
86        if (SlangRS::IsRSHeaderFile(HeaderFilename.getLast().data()))
87          continue;
88        mDiags.Report(FSL, mDiags.getCustomDiagID(clang::Diagnostic::Error,
89                      "invalid function name prefix, \"rs\" is reserved: '%0'"))
90            << FD->getName();
91      }
92    }
93  }
94
95  Backend::HandleTopLevelDecl(D);
96  return;
97}
98
99void RSBackend::HandleTranslationUnitPost(llvm::Module *M) {
100  mContext->processExport();
101
102  // Dump export variable info
103  if (mContext->hasExportVar()) {
104    if (mExportVarMetadata == NULL)
105      mExportVarMetadata = M->getOrInsertNamedMetadata(RS_EXPORT_VAR_MN);
106
107    llvm::SmallVector<llvm::Value*, 2> ExportVarInfo;
108
109    for (RSContext::const_export_var_iterator I = mContext->export_vars_begin(),
110            E = mContext->export_vars_end();
111         I != E;
112         I++) {
113      const RSExportVar *EV = *I;
114      const RSExportType *ET = EV->getType();
115
116      // Variable name
117      ExportVarInfo.push_back(
118          llvm::MDString::get(mLLVMContext, EV->getName().c_str()));
119
120      // Type name
121      if (ET->getClass() == RSExportType::ExportClassPrimitive)
122        ExportVarInfo.push_back(
123            llvm::MDString::get(
124                mLLVMContext, llvm::utostr_32(
125                    static_cast<const RSExportPrimitiveType*>(ET)->getType())));
126      else if (ET->getClass() == RSExportType::ExportClassPointer)
127        ExportVarInfo.push_back(
128            llvm::MDString::get(
129                mLLVMContext, ("*" + static_cast<const RSExportPointerType*>(ET)
130                               ->getPointeeType()->getName()).c_str()));
131      else
132        ExportVarInfo.push_back(
133            llvm::MDString::get(mLLVMContext,
134                                EV->getType()->getName().c_str()));
135
136      mExportVarMetadata->addOperand(
137          llvm::MDNode::get(mLLVMContext,
138                            ExportVarInfo.data(),
139                            ExportVarInfo.size()) );
140
141      ExportVarInfo.clear();
142    }
143  }
144
145  // Dump export function info
146  if (mContext->hasExportFunc()) {
147    if (mExportFuncMetadata == NULL)
148      mExportFuncMetadata =
149          M->getOrInsertNamedMetadata(RS_EXPORT_FUNC_MN);
150
151    llvm::SmallVector<llvm::Value*, 1> ExportFuncInfo;
152
153    for (RSContext::const_export_func_iterator
154            I = mContext->export_funcs_begin(),
155            E = mContext->export_funcs_end();
156         I != E;
157         I++) {
158      const RSExportFunc *EF = *I;
159
160      // Function name
161      if (!EF->hasParam()) {
162        ExportFuncInfo.push_back(llvm::MDString::get(mLLVMContext,
163                                                     EF->getName().c_str()));
164      } else {
165        llvm::Function *F = M->getFunction(EF->getName());
166        llvm::Function *HelperFunction;
167        const std::string HelperFunctionName(".helper_" + EF->getName());
168
169        assert(F && "Function marked as exported disappeared in Bitcode");
170
171        // Create helper function
172        {
173          llvm::StructType *HelperFunctionParameterTy = NULL;
174
175          if (!F->getArgumentList().empty()) {
176            std::vector<const llvm::Type*> HelperFunctionParameterTys;
177            for (llvm::Function::arg_iterator AI = F->arg_begin(),
178                 AE = F->arg_end(); AI != AE; AI++)
179              HelperFunctionParameterTys.push_back(AI->getType());
180
181            HelperFunctionParameterTy =
182                llvm::StructType::get(mLLVMContext, HelperFunctionParameterTys);
183          }
184
185          if (!EF->checkParameterPacketType(HelperFunctionParameterTy)) {
186            fprintf(stderr, "Failed to export function %s: parameter type "
187                            "mismatch during creation of helper function.\n",
188                    EF->getName().c_str());
189
190            const RSExportRecordType *Expected = EF->getParamPacketType();
191            if (Expected) {
192              fprintf(stderr, "Expected:\n");
193              Expected->getLLVMType()->dump();
194            }
195            if (HelperFunctionParameterTy) {
196              fprintf(stderr, "Got:\n");
197              HelperFunctionParameterTy->dump();
198            }
199          }
200
201          std::vector<const llvm::Type*> Params;
202          if (HelperFunctionParameterTy) {
203            llvm::PointerType *HelperFunctionParameterTyP =
204                llvm::PointerType::getUnqual(HelperFunctionParameterTy);
205            Params.push_back(HelperFunctionParameterTyP);
206          }
207
208          llvm::FunctionType * HelperFunctionType =
209              llvm::FunctionType::get(F->getReturnType(),
210                                      Params,
211                                      /* IsVarArgs = */false);
212
213          HelperFunction =
214              llvm::Function::Create(HelperFunctionType,
215                                     llvm::GlobalValue::ExternalLinkage,
216                                     HelperFunctionName,
217                                     M);
218
219          HelperFunction->addFnAttr(llvm::Attribute::NoInline);
220          HelperFunction->setCallingConv(F->getCallingConv());
221
222          // Create helper function body
223          {
224            llvm::Argument *HelperFunctionParameter =
225                &(*HelperFunction->arg_begin());
226            llvm::BasicBlock *BB =
227                llvm::BasicBlock::Create(mLLVMContext, "entry", HelperFunction);
228            llvm::IRBuilder<> *IB = new llvm::IRBuilder<>(BB);
229            llvm::SmallVector<llvm::Value*, 6> Params;
230            llvm::Value *Idx[2];
231
232            Idx[0] =
233                llvm::ConstantInt::get(llvm::Type::getInt32Ty(mLLVMContext), 0);
234
235            // getelementptr and load instruction for all elements in
236            // parameter .p
237            for (size_t i = 0; i < EF->getNumParameters(); i++) {
238              // getelementptr
239              Idx[1] =
240                  llvm::ConstantInt::get(
241                      llvm::Type::getInt32Ty(mLLVMContext), i);
242              llvm::Value *Ptr = IB->CreateInBoundsGEP(HelperFunctionParameter,
243                                                       Idx,
244                                                       Idx + 2);
245
246              // load
247              llvm::Value *V = IB->CreateLoad(Ptr);
248              Params.push_back(V);
249            }
250
251            // Call and pass the all elements as paramter to F
252            llvm::CallInst *CI = IB->CreateCall(F,
253                                                Params.data(),
254                                                Params.data() + Params.size());
255
256            CI->setCallingConv(F->getCallingConv());
257
258            if (F->getReturnType() == llvm::Type::getVoidTy(mLLVMContext))
259              IB->CreateRetVoid();
260            else
261              IB->CreateRet(CI);
262
263            delete IB;
264          }
265        }
266
267        ExportFuncInfo.push_back(
268            llvm::MDString::get(mLLVMContext, HelperFunctionName.c_str()));
269      }
270
271      mExportFuncMetadata->addOperand(
272          llvm::MDNode::get(mLLVMContext,
273                            ExportFuncInfo.data(),
274                            ExportFuncInfo.size()));
275
276      ExportFuncInfo.clear();
277    }
278  }
279
280  // Dump export type info
281  if (mContext->hasExportType()) {
282    llvm::SmallVector<llvm::Value*, 1> ExportTypeInfo;
283
284    for (RSContext::const_export_type_iterator
285            I = mContext->export_types_begin(),
286            E = mContext->export_types_end();
287         I != E;
288         I++) {
289      // First, dump type name list to export
290      const RSExportType *ET = I->getValue();
291
292      ExportTypeInfo.clear();
293      // Type name
294      ExportTypeInfo.push_back(
295          llvm::MDString::get(mLLVMContext, ET->getName().c_str()));
296
297      if (ET->getClass() == RSExportType::ExportClassRecord) {
298        const RSExportRecordType *ERT =
299            static_cast<const RSExportRecordType*>(ET);
300
301        if (mExportTypeMetadata == NULL)
302          mExportTypeMetadata =
303              M->getOrInsertNamedMetadata(RS_EXPORT_TYPE_MN);
304
305        mExportTypeMetadata->addOperand(
306            llvm::MDNode::get(mLLVMContext,
307                              ExportTypeInfo.data(),
308                              ExportTypeInfo.size()));
309
310        // Now, export struct field information to %[struct name]
311        std::string StructInfoMetadataName("%");
312        StructInfoMetadataName.append(ET->getName());
313        llvm::NamedMDNode *StructInfoMetadata =
314            M->getOrInsertNamedMetadata(StructInfoMetadataName);
315        llvm::SmallVector<llvm::Value*, 3> FieldInfo;
316
317        assert(StructInfoMetadata->getNumOperands() == 0 &&
318               "Metadata with same name was created before");
319        for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
320                FE = ERT->fields_end();
321             FI != FE;
322             FI++) {
323          const RSExportRecordType::Field *F = *FI;
324
325          // 1. field name
326          FieldInfo.push_back(llvm::MDString::get(mLLVMContext,
327                                                  F->getName().c_str()));
328
329          // 2. field type name
330          FieldInfo.push_back(
331              llvm::MDString::get(mLLVMContext,
332                                  F->getType()->getName().c_str()));
333
334          // 3. field kind
335          switch (F->getType()->getClass()) {
336            case RSExportType::ExportClassPrimitive:
337            case RSExportType::ExportClassVector: {
338              const RSExportPrimitiveType *EPT =
339                  static_cast<const RSExportPrimitiveType*>(F->getType());
340              FieldInfo.push_back(
341                  llvm::MDString::get(mLLVMContext,
342                                      llvm::itostr(EPT->getKind())));
343              break;
344            }
345
346            default: {
347              FieldInfo.push_back(
348                  llvm::MDString::get(mLLVMContext,
349                                      llvm::itostr(
350                                        RSExportPrimitiveType::DataKindUser)));
351              break;
352            }
353          }
354
355          StructInfoMetadata->addOperand(llvm::MDNode::get(mLLVMContext,
356                                                           FieldInfo.data(),
357                                                           FieldInfo.size()));
358
359          FieldInfo.clear();
360        }
361      }   // ET->getClass() == RSExportType::ExportClassRecord
362    }
363  }
364
365  return;
366}
367
368RSBackend::~RSBackend() {
369  return;
370}
371