slang_rs_backend.cpp revision e639eb5caa2c386b4a60659a4929e8a6141a2cbe
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 <string>
20#include <vector>
21
22#include "llvm/ADT/Twine.h"
23#include "llvm/ADT/StringExtras.h"
24
25#include "llvm/Constant.h"
26#include "llvm/Constants.h"
27#include "llvm/DerivedTypes.h"
28#include "llvm/Function.h"
29#include "llvm/Metadata.h"
30#include "llvm/Module.h"
31
32#include "llvm/Support/IRBuilder.h"
33
34#include "slang_rs.h"
35#include "slang_rs_context.h"
36#include "slang_rs_export_func.h"
37#include "slang_rs_export_type.h"
38#include "slang_rs_export_var.h"
39#include "slang_rs_metadata.h"
40
41namespace slang {
42
43RSBackend::RSBackend(RSContext *Context,
44                     clang::Diagnostic *Diags,
45                     const clang::CodeGenOptions &CodeGenOpts,
46                     const clang::TargetOptions &TargetOpts,
47                     const PragmaList &Pragmas,
48                     llvm::raw_ostream *OS,
49                     Slang::OutputType OT,
50                     clang::SourceManager &SourceMgr,
51                     bool AllowRSPrefix)
52    : Backend(Diags,
53              CodeGenOpts,
54              TargetOpts,
55              Pragmas,
56              OS,
57              OT),
58      mContext(Context),
59      mSourceMgr(SourceMgr),
60      mAllowRSPrefix(AllowRSPrefix),
61      mExportVarMetadata(NULL),
62      mExportFuncMetadata(NULL),
63      mExportTypeMetadata(NULL) {
64  return;
65}
66
67// 1) Add zero initialization of local RS object types
68void RSBackend::AnnotateFunction(clang::FunctionDecl *FD) {
69  if (FD &&
70      FD->hasBody() &&
71      !SlangRS::IsFunctionInRSHeaderFile(FD, mSourceMgr)) {
72    mRefCount.Init(mContext->getASTContext());
73    mRefCount.Visit(FD->getBody());
74  }
75  return;
76}
77
78void RSBackend::HandleTopLevelDecl(clang::DeclGroupRef D) {
79  // Disallow user-defined functions with prefix "rs"
80  if (!mAllowRSPrefix) {
81    // Iterate all function declarations in the program.
82    for (clang::DeclGroupRef::iterator I = D.begin(), E = D.end();
83         I != E; I++) {
84      clang::FunctionDecl *FD = dyn_cast<clang::FunctionDecl>(*I);
85      if (FD == NULL)
86        continue;
87      if (!FD->getName().startswith("rs"))  // Check prefix
88        continue;
89      if (!SlangRS::IsFunctionInRSHeaderFile(FD, mSourceMgr))
90        mDiags.Report(clang::FullSourceLoc(FD->getLocation(), mSourceMgr),
91                      mDiags.getCustomDiagID(clang::Diagnostic::Error,
92                                             "invalid function name prefix, "
93                                             "\"rs\" is reserved: '%0'"))
94            << FD->getName();
95    }
96  }
97
98  // Process any non-static function declarations
99  for (clang::DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; I++) {
100    AnnotateFunction(dyn_cast<clang::FunctionDecl>(*I));
101  }
102
103  Backend::HandleTopLevelDecl(D);
104  return;
105}
106
107void RSBackend::HandleTranslationUnitPre(clang::ASTContext& C) {
108  clang::TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
109
110  // Process any static function declarations
111  for (clang::DeclContext::decl_iterator I = TUDecl->decls_begin(),
112          E = TUDecl->decls_end(); I != E; I++) {
113    if ((I->getKind() >= clang::Decl::firstFunction) &&
114        (I->getKind() <= clang::Decl::lastFunction)) {
115      AnnotateFunction(static_cast<clang::FunctionDecl*>(*I));
116    }
117  }
118
119  return;
120}
121
122///////////////////////////////////////////////////////////////////////////////
123void RSBackend::HandleTranslationUnitPost(llvm::Module *M) {
124  mContext->processExport();
125
126  // Dump export variable info
127  if (mContext->hasExportVar()) {
128    if (mExportVarMetadata == NULL)
129      mExportVarMetadata = M->getOrInsertNamedMetadata(RS_EXPORT_VAR_MN);
130
131    llvm::SmallVector<llvm::Value*, 2> ExportVarInfo;
132
133    for (RSContext::const_export_var_iterator I = mContext->export_vars_begin(),
134            E = mContext->export_vars_end();
135         I != E;
136         I++) {
137      const RSExportVar *EV = *I;
138      const RSExportType *ET = EV->getType();
139
140      // Variable name
141      ExportVarInfo.push_back(
142          llvm::MDString::get(mLLVMContext, EV->getName().c_str()));
143
144      // Type name
145      switch (ET->getClass()) {
146        case RSExportType::ExportClassPrimitive: {
147          ExportVarInfo.push_back(
148              llvm::MDString::get(
149                mLLVMContext, llvm::utostr_32(
150                  static_cast<const RSExportPrimitiveType*>(ET)->getType())));
151          break;
152        }
153        case RSExportType::ExportClassPointer: {
154          ExportVarInfo.push_back(
155              llvm::MDString::get(
156                mLLVMContext, ("*" + static_cast<const RSExportPointerType*>(ET)
157                  ->getPointeeType()->getName()).c_str()));
158          break;
159        }
160        case RSExportType::ExportClassMatrix: {
161          ExportVarInfo.push_back(
162              llvm::MDString::get(
163                mLLVMContext, llvm::utostr_32(
164                  RSExportPrimitiveType::DataTypeRSMatrix2x2 +
165                  static_cast<const RSExportMatrixType*>(ET)->getDim() - 2)));
166          break;
167        }
168        case RSExportType::ExportClassVector:
169        case RSExportType::ExportClassConstantArray:
170        case RSExportType::ExportClassRecord: {
171          ExportVarInfo.push_back(
172              llvm::MDString::get(mLLVMContext,
173                EV->getType()->getName().c_str()));
174          break;
175        }
176      }
177
178      mExportVarMetadata->addOperand(
179          llvm::MDNode::get(mLLVMContext,
180                            ExportVarInfo.data(),
181                            ExportVarInfo.size()) );
182
183      ExportVarInfo.clear();
184    }
185  }
186
187  // Dump export function info
188  if (mContext->hasExportFunc()) {
189    if (mExportFuncMetadata == NULL)
190      mExportFuncMetadata =
191          M->getOrInsertNamedMetadata(RS_EXPORT_FUNC_MN);
192
193    llvm::SmallVector<llvm::Value*, 1> ExportFuncInfo;
194
195    for (RSContext::const_export_func_iterator
196            I = mContext->export_funcs_begin(),
197            E = mContext->export_funcs_end();
198         I != E;
199         I++) {
200      const RSExportFunc *EF = *I;
201
202      // Function name
203      if (!EF->hasParam()) {
204        ExportFuncInfo.push_back(llvm::MDString::get(mLLVMContext,
205                                                     EF->getName().c_str()));
206      } else {
207        llvm::Function *F = M->getFunction(EF->getName());
208        llvm::Function *HelperFunction;
209        const std::string HelperFunctionName(".helper_" + EF->getName());
210
211        assert(F && "Function marked as exported disappeared in Bitcode");
212
213        // Create helper function
214        {
215          llvm::StructType *HelperFunctionParameterTy = NULL;
216
217          if (!F->getArgumentList().empty()) {
218            std::vector<const llvm::Type*> HelperFunctionParameterTys;
219            for (llvm::Function::arg_iterator AI = F->arg_begin(),
220                 AE = F->arg_end(); AI != AE; AI++)
221              HelperFunctionParameterTys.push_back(AI->getType());
222
223            HelperFunctionParameterTy =
224                llvm::StructType::get(mLLVMContext, HelperFunctionParameterTys);
225          }
226
227          if (!EF->checkParameterPacketType(HelperFunctionParameterTy)) {
228            fprintf(stderr, "Failed to export function %s: parameter type "
229                            "mismatch during creation of helper function.\n",
230                    EF->getName().c_str());
231
232            const RSExportRecordType *Expected = EF->getParamPacketType();
233            if (Expected) {
234              fprintf(stderr, "Expected:\n");
235              Expected->getLLVMType()->dump();
236            }
237            if (HelperFunctionParameterTy) {
238              fprintf(stderr, "Got:\n");
239              HelperFunctionParameterTy->dump();
240            }
241          }
242
243          std::vector<const llvm::Type*> Params;
244          if (HelperFunctionParameterTy) {
245            llvm::PointerType *HelperFunctionParameterTyP =
246                llvm::PointerType::getUnqual(HelperFunctionParameterTy);
247            Params.push_back(HelperFunctionParameterTyP);
248          }
249
250          llvm::FunctionType * HelperFunctionType =
251              llvm::FunctionType::get(F->getReturnType(),
252                                      Params,
253                                      /* IsVarArgs = */false);
254
255          HelperFunction =
256              llvm::Function::Create(HelperFunctionType,
257                                     llvm::GlobalValue::ExternalLinkage,
258                                     HelperFunctionName,
259                                     M);
260
261          HelperFunction->addFnAttr(llvm::Attribute::NoInline);
262          HelperFunction->setCallingConv(F->getCallingConv());
263
264          // Create helper function body
265          {
266            llvm::Argument *HelperFunctionParameter =
267                &(*HelperFunction->arg_begin());
268            llvm::BasicBlock *BB =
269                llvm::BasicBlock::Create(mLLVMContext, "entry", HelperFunction);
270            llvm::IRBuilder<> *IB = new llvm::IRBuilder<>(BB);
271            llvm::SmallVector<llvm::Value*, 6> Params;
272            llvm::Value *Idx[2];
273
274            Idx[0] =
275                llvm::ConstantInt::get(llvm::Type::getInt32Ty(mLLVMContext), 0);
276
277            // getelementptr and load instruction for all elements in
278            // parameter .p
279            for (size_t i = 0; i < EF->getNumParameters(); i++) {
280              // getelementptr
281              Idx[1] =
282                  llvm::ConstantInt::get(
283                      llvm::Type::getInt32Ty(mLLVMContext), i);
284              llvm::Value *Ptr = IB->CreateInBoundsGEP(HelperFunctionParameter,
285                                                       Idx,
286                                                       Idx + 2);
287
288              // load
289              llvm::Value *V = IB->CreateLoad(Ptr);
290              Params.push_back(V);
291            }
292
293            // Call and pass the all elements as paramter to F
294            llvm::CallInst *CI = IB->CreateCall(F,
295                                                Params.data(),
296                                                Params.data() + Params.size());
297
298            CI->setCallingConv(F->getCallingConv());
299
300            if (F->getReturnType() == llvm::Type::getVoidTy(mLLVMContext))
301              IB->CreateRetVoid();
302            else
303              IB->CreateRet(CI);
304
305            delete IB;
306          }
307        }
308
309        ExportFuncInfo.push_back(
310            llvm::MDString::get(mLLVMContext, HelperFunctionName.c_str()));
311      }
312
313      mExportFuncMetadata->addOperand(
314          llvm::MDNode::get(mLLVMContext,
315                            ExportFuncInfo.data(),
316                            ExportFuncInfo.size()));
317
318      ExportFuncInfo.clear();
319    }
320  }
321
322  // Dump export type info
323  if (mContext->hasExportType()) {
324    llvm::SmallVector<llvm::Value*, 1> ExportTypeInfo;
325
326    for (RSContext::const_export_type_iterator
327            I = mContext->export_types_begin(),
328            E = mContext->export_types_end();
329         I != E;
330         I++) {
331      // First, dump type name list to export
332      const RSExportType *ET = I->getValue();
333
334      ExportTypeInfo.clear();
335      // Type name
336      ExportTypeInfo.push_back(
337          llvm::MDString::get(mLLVMContext, ET->getName().c_str()));
338
339      if (ET->getClass() == RSExportType::ExportClassRecord) {
340        const RSExportRecordType *ERT =
341            static_cast<const RSExportRecordType*>(ET);
342
343        if (mExportTypeMetadata == NULL)
344          mExportTypeMetadata =
345              M->getOrInsertNamedMetadata(RS_EXPORT_TYPE_MN);
346
347        mExportTypeMetadata->addOperand(
348            llvm::MDNode::get(mLLVMContext,
349                              ExportTypeInfo.data(),
350                              ExportTypeInfo.size()));
351
352        // Now, export struct field information to %[struct name]
353        std::string StructInfoMetadataName("%");
354        StructInfoMetadataName.append(ET->getName());
355        llvm::NamedMDNode *StructInfoMetadata =
356            M->getOrInsertNamedMetadata(StructInfoMetadataName);
357        llvm::SmallVector<llvm::Value*, 3> FieldInfo;
358
359        assert(StructInfoMetadata->getNumOperands() == 0 &&
360               "Metadata with same name was created before");
361        for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
362                FE = ERT->fields_end();
363             FI != FE;
364             FI++) {
365          const RSExportRecordType::Field *F = *FI;
366
367          // 1. field name
368          FieldInfo.push_back(llvm::MDString::get(mLLVMContext,
369                                                  F->getName().c_str()));
370
371          // 2. field type name
372          FieldInfo.push_back(
373              llvm::MDString::get(mLLVMContext,
374                                  F->getType()->getName().c_str()));
375
376          // 3. field kind
377          switch (F->getType()->getClass()) {
378            case RSExportType::ExportClassPrimitive:
379            case RSExportType::ExportClassVector: {
380              const RSExportPrimitiveType *EPT =
381                  static_cast<const RSExportPrimitiveType*>(F->getType());
382              FieldInfo.push_back(
383                  llvm::MDString::get(mLLVMContext,
384                                      llvm::itostr(EPT->getKind())));
385              break;
386            }
387
388            default: {
389              FieldInfo.push_back(
390                  llvm::MDString::get(mLLVMContext,
391                                      llvm::itostr(
392                                        RSExportPrimitiveType::DataKindUser)));
393              break;
394            }
395          }
396
397          StructInfoMetadata->addOperand(llvm::MDNode::get(mLLVMContext,
398                                                           FieldInfo.data(),
399                                                           FieldInfo.size()));
400
401          FieldInfo.clear();
402        }
403      }   // ET->getClass() == RSExportType::ExportClassRecord
404    }
405  }
406
407  return;
408}
409
410RSBackend::~RSBackend() {
411  return;
412}
413
414}  // namespace slang
415