slang_rs_backend.cpp revision ab5a535b290d898d0c56036f642d823e3472a804
1/*
2 * Copyright 2010-2012, 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 "clang/AST/ASTContext.h"
23#include "clang/Frontend/CodeGenOptions.h"
24
25#include "llvm/ADT/Twine.h"
26#include "llvm/ADT/StringExtras.h"
27
28#include "llvm/Constant.h"
29#include "llvm/Constants.h"
30#include "llvm/DerivedTypes.h"
31#include "llvm/Function.h"
32#include "llvm/IRBuilder.h"
33#include "llvm/Metadata.h"
34#include "llvm/Module.h"
35
36#include "llvm/Support/DebugLoc.h"
37
38#include "slang_assert.h"
39#include "slang_rs.h"
40#include "slang_rs_context.h"
41#include "slang_rs_export_foreach.h"
42#include "slang_rs_export_func.h"
43#include "slang_rs_export_type.h"
44#include "slang_rs_export_var.h"
45#include "slang_rs_metadata.h"
46
47namespace slang {
48
49RSBackend::RSBackend(RSContext *Context,
50                     clang::DiagnosticsEngine *DiagEngine,
51                     const clang::CodeGenOptions &CodeGenOpts,
52                     const clang::TargetOptions &TargetOpts,
53                     PragmaList *Pragmas,
54                     llvm::raw_ostream *OS,
55                     Slang::OutputType OT,
56                     clang::SourceManager &SourceMgr,
57                     bool AllowRSPrefix)
58  : Backend(DiagEngine, CodeGenOpts, TargetOpts, Pragmas, OS, OT),
59    mContext(Context),
60    mSourceMgr(SourceMgr),
61    mAllowRSPrefix(AllowRSPrefix),
62    mExportVarMetadata(NULL),
63    mExportFuncMetadata(NULL),
64    mExportForEachNameMetadata(NULL),
65    mExportForEachSignatureMetadata(NULL),
66    mExportTypeMetadata(NULL),
67    mRSObjectSlotsMetadata(NULL),
68    mRefCount(mContext->getASTContext()) {
69}
70
71// 1) Add zero initialization of local RS object types
72void RSBackend::AnnotateFunction(clang::FunctionDecl *FD) {
73  if (FD &&
74      FD->hasBody() &&
75      !SlangRS::IsFunctionInRSHeaderFile(FD, mSourceMgr)) {
76    mRefCount.Init();
77    mRefCount.Visit(FD->getBody());
78  }
79  return;
80}
81
82bool RSBackend::HandleTopLevelDecl(clang::DeclGroupRef D) {
83  // Disallow user-defined functions with prefix "rs"
84  if (!mAllowRSPrefix) {
85    // Iterate all function declarations in the program.
86    for (clang::DeclGroupRef::iterator I = D.begin(), E = D.end();
87         I != E; I++) {
88      clang::FunctionDecl *FD = llvm::dyn_cast<clang::FunctionDecl>(*I);
89      if (FD == NULL)
90        continue;
91      if (!FD->getName().startswith("rs"))  // Check prefix
92        continue;
93      if (!SlangRS::IsFunctionInRSHeaderFile(FD, mSourceMgr))
94        mDiagEngine.Report(
95          clang::FullSourceLoc(FD->getLocation(), mSourceMgr),
96          mDiagEngine.getCustomDiagID(clang::DiagnosticsEngine::Error,
97                                      "invalid function name prefix, "
98                                      "\"rs\" is reserved: '%0'"))
99          << FD->getName();
100    }
101  }
102
103  // Process any non-static function declarations
104  for (clang::DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; I++) {
105    clang::FunctionDecl *FD = llvm::dyn_cast<clang::FunctionDecl>(*I);
106    if (FD && FD->isGlobal()) {
107      // Check that we don't have any array parameters being misintrepeted as
108      // kernel pointers due to the C type system's array to pointer decay.
109      size_t numParams = FD->getNumParams();
110      for (size_t i = 0; i < numParams; i++) {
111        const clang::ParmVarDecl *PVD = FD->getParamDecl(i);
112        clang::QualType QT = PVD->getOriginalType();
113        if (QT->isArrayType()) {
114          mDiagEngine.Report(
115            clang::FullSourceLoc(PVD->getTypeSpecStartLoc(), mSourceMgr),
116            mDiagEngine.getCustomDiagID(clang::DiagnosticsEngine::Error,
117                                        "exported function parameters may "
118                                        "not have array type: %0")) << QT;
119        }
120      }
121      AnnotateFunction(FD);
122    }
123  }
124
125  return Backend::HandleTopLevelDecl(D);
126}
127
128namespace {
129
130static bool ValidateVarDecl(clang::VarDecl *VD, unsigned int TargetAPI) {
131  if (!VD) {
132    return true;
133  }
134
135  clang::ASTContext &C = VD->getASTContext();
136  const clang::Type *T = VD->getType().getTypePtr();
137  bool valid = true;
138
139  if (VD->getLinkage() == clang::ExternalLinkage) {
140    llvm::StringRef TypeName;
141    if (!RSExportType::NormalizeType(T, TypeName, &C.getDiagnostics(), VD)) {
142      valid = false;
143    }
144  }
145  valid &= RSExportType::ValidateVarDecl(VD, TargetAPI);
146
147  return valid;
148}
149
150static bool ValidateASTContext(clang::ASTContext &C, unsigned int TargetAPI) {
151  bool valid = true;
152  clang::TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
153  for (clang::DeclContext::decl_iterator DI = TUDecl->decls_begin(),
154          DE = TUDecl->decls_end();
155       DI != DE;
156       DI++) {
157    clang::VarDecl *VD = llvm::dyn_cast<clang::VarDecl>(*DI);
158    if (VD && !ValidateVarDecl(VD, TargetAPI)) {
159      valid = false;
160    }
161  }
162
163  return valid;
164}
165
166}  // namespace
167
168void RSBackend::HandleTranslationUnitPre(clang::ASTContext &C) {
169  clang::TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
170
171  if (!ValidateASTContext(C, getTargetAPI())) {
172    return;
173  }
174
175  int version = mContext->getVersion();
176  if (version == 0) {
177    // Not setting a version is an error
178    mDiagEngine.Report(
179        mSourceMgr.getLocForEndOfFile(mSourceMgr.getMainFileID()),
180        mDiagEngine.getCustomDiagID(
181            clang::DiagnosticsEngine::Error,
182            "missing pragma for version in source file"));
183  } else {
184    slangAssert(version == 1);
185  }
186
187  // Create a static global destructor if necessary (to handle RS object
188  // runtime cleanup).
189  clang::FunctionDecl *FD = mRefCount.CreateStaticGlobalDtor();
190  if (FD) {
191    HandleTopLevelDecl(clang::DeclGroupRef(FD));
192  }
193
194  // Process any static function declarations
195  for (clang::DeclContext::decl_iterator I = TUDecl->decls_begin(),
196          E = TUDecl->decls_end(); I != E; I++) {
197    if ((I->getKind() >= clang::Decl::firstFunction) &&
198        (I->getKind() <= clang::Decl::lastFunction)) {
199      clang::FunctionDecl *FD = llvm::dyn_cast<clang::FunctionDecl>(*I);
200      if (FD && !FD->isGlobal()) {
201        AnnotateFunction(FD);
202      }
203    }
204  }
205
206  return;
207}
208
209///////////////////////////////////////////////////////////////////////////////
210void RSBackend::HandleTranslationUnitPost(llvm::Module *M) {
211  if (!mContext->processExport()) {
212    return;
213  }
214
215  // Write optimization level
216  llvm::SmallVector<llvm::Value*, 1> OptimizationOption;
217  OptimizationOption.push_back(llvm::ConstantInt::get(
218    mLLVMContext, llvm::APInt(32, mCodeGenOpts.OptimizationLevel)));
219
220  // Dump export variable info
221  if (mContext->hasExportVar()) {
222    int slotCount = 0;
223    if (mExportVarMetadata == NULL)
224      mExportVarMetadata = M->getOrInsertNamedMetadata(RS_EXPORT_VAR_MN);
225
226    llvm::SmallVector<llvm::Value*, 2> ExportVarInfo;
227
228    // We emit slot information (#rs_object_slots) for any reference counted
229    // RS type or pointer (which can also be bound).
230
231    for (RSContext::const_export_var_iterator I = mContext->export_vars_begin(),
232            E = mContext->export_vars_end();
233         I != E;
234         I++) {
235      const RSExportVar *EV = *I;
236      const RSExportType *ET = EV->getType();
237      bool countsAsRSObject = false;
238
239      // Variable name
240      ExportVarInfo.push_back(
241          llvm::MDString::get(mLLVMContext, EV->getName().c_str()));
242
243      // Type name
244      switch (ET->getClass()) {
245        case RSExportType::ExportClassPrimitive: {
246          const RSExportPrimitiveType *PT =
247              static_cast<const RSExportPrimitiveType*>(ET);
248          ExportVarInfo.push_back(
249              llvm::MDString::get(
250                mLLVMContext, llvm::utostr_32(PT->getType())));
251          if (PT->isRSObjectType()) {
252            countsAsRSObject = true;
253          }
254          break;
255        }
256        case RSExportType::ExportClassPointer: {
257          ExportVarInfo.push_back(
258              llvm::MDString::get(
259                mLLVMContext, ("*" + static_cast<const RSExportPointerType*>(ET)
260                  ->getPointeeType()->getName()).c_str()));
261          break;
262        }
263        case RSExportType::ExportClassMatrix: {
264          ExportVarInfo.push_back(
265              llvm::MDString::get(
266                mLLVMContext, llvm::utostr_32(
267                  RSExportPrimitiveType::DataTypeRSMatrix2x2 +
268                  static_cast<const RSExportMatrixType*>(ET)->getDim() - 2)));
269          break;
270        }
271        case RSExportType::ExportClassVector:
272        case RSExportType::ExportClassConstantArray:
273        case RSExportType::ExportClassRecord: {
274          ExportVarInfo.push_back(
275              llvm::MDString::get(mLLVMContext,
276                EV->getType()->getName().c_str()));
277          break;
278        }
279      }
280
281      mExportVarMetadata->addOperand(
282          llvm::MDNode::get(mLLVMContext, ExportVarInfo));
283      ExportVarInfo.clear();
284
285      if (mRSObjectSlotsMetadata == NULL) {
286        mRSObjectSlotsMetadata =
287            M->getOrInsertNamedMetadata(RS_OBJECT_SLOTS_MN);
288      }
289
290      if (countsAsRSObject) {
291        mRSObjectSlotsMetadata->addOperand(llvm::MDNode::get(mLLVMContext,
292            llvm::MDString::get(mLLVMContext, llvm::utostr_32(slotCount))));
293      }
294
295      slotCount++;
296    }
297  }
298
299  // Dump export function info
300  if (mContext->hasExportFunc()) {
301    if (mExportFuncMetadata == NULL)
302      mExportFuncMetadata =
303          M->getOrInsertNamedMetadata(RS_EXPORT_FUNC_MN);
304
305    llvm::SmallVector<llvm::Value*, 1> ExportFuncInfo;
306
307    for (RSContext::const_export_func_iterator
308            I = mContext->export_funcs_begin(),
309            E = mContext->export_funcs_end();
310         I != E;
311         I++) {
312      const RSExportFunc *EF = *I;
313
314      // Function name
315      if (!EF->hasParam()) {
316        ExportFuncInfo.push_back(llvm::MDString::get(mLLVMContext,
317                                                     EF->getName().c_str()));
318      } else {
319        llvm::Function *F = M->getFunction(EF->getName());
320        llvm::Function *HelperFunction;
321        const std::string HelperFunctionName(".helper_" + EF->getName());
322
323        slangAssert(F && "Function marked as exported disappeared in Bitcode");
324
325        // Create helper function
326        {
327          llvm::StructType *HelperFunctionParameterTy = NULL;
328
329          if (!F->getArgumentList().empty()) {
330            std::vector<llvm::Type*> HelperFunctionParameterTys;
331            for (llvm::Function::arg_iterator AI = F->arg_begin(),
332                 AE = F->arg_end(); AI != AE; AI++)
333              HelperFunctionParameterTys.push_back(AI->getType());
334
335            HelperFunctionParameterTy =
336                llvm::StructType::get(mLLVMContext, HelperFunctionParameterTys);
337          }
338
339          if (!EF->checkParameterPacketType(HelperFunctionParameterTy)) {
340            fprintf(stderr, "Failed to export function %s: parameter type "
341                            "mismatch during creation of helper function.\n",
342                    EF->getName().c_str());
343
344            const RSExportRecordType *Expected = EF->getParamPacketType();
345            if (Expected) {
346              fprintf(stderr, "Expected:\n");
347              Expected->getLLVMType()->dump();
348            }
349            if (HelperFunctionParameterTy) {
350              fprintf(stderr, "Got:\n");
351              HelperFunctionParameterTy->dump();
352            }
353          }
354
355          std::vector<llvm::Type*> Params;
356          if (HelperFunctionParameterTy) {
357            llvm::PointerType *HelperFunctionParameterTyP =
358                llvm::PointerType::getUnqual(HelperFunctionParameterTy);
359            Params.push_back(HelperFunctionParameterTyP);
360          }
361
362          llvm::FunctionType * HelperFunctionType =
363              llvm::FunctionType::get(F->getReturnType(),
364                                      Params,
365                                      /* IsVarArgs = */false);
366
367          HelperFunction =
368              llvm::Function::Create(HelperFunctionType,
369                                     llvm::GlobalValue::ExternalLinkage,
370                                     HelperFunctionName,
371                                     M);
372
373          HelperFunction->addFnAttr(llvm::Attribute::NoInline);
374          HelperFunction->setCallingConv(F->getCallingConv());
375
376          // Create helper function body
377          {
378            llvm::Argument *HelperFunctionParameter =
379                &(*HelperFunction->arg_begin());
380            llvm::BasicBlock *BB =
381                llvm::BasicBlock::Create(mLLVMContext, "entry", HelperFunction);
382            llvm::IRBuilder<> *IB = new llvm::IRBuilder<>(BB);
383            llvm::SmallVector<llvm::Value*, 6> Params;
384            llvm::Value *Idx[2];
385
386            Idx[0] =
387                llvm::ConstantInt::get(llvm::Type::getInt32Ty(mLLVMContext), 0);
388
389            // getelementptr and load instruction for all elements in
390            // parameter .p
391            for (size_t i = 0; i < EF->getNumParameters(); i++) {
392              // getelementptr
393              Idx[1] = llvm::ConstantInt::get(
394                llvm::Type::getInt32Ty(mLLVMContext), i);
395
396              llvm::Value *Ptr =
397                IB->CreateInBoundsGEP(HelperFunctionParameter, Idx);
398
399              // load
400              llvm::Value *V = IB->CreateLoad(Ptr);
401              Params.push_back(V);
402            }
403
404            // Call and pass the all elements as parameter to F
405            llvm::CallInst *CI = IB->CreateCall(F, Params);
406
407            CI->setCallingConv(F->getCallingConv());
408
409            if (F->getReturnType() == llvm::Type::getVoidTy(mLLVMContext))
410              IB->CreateRetVoid();
411            else
412              IB->CreateRet(CI);
413
414            delete IB;
415          }
416        }
417
418        ExportFuncInfo.push_back(
419            llvm::MDString::get(mLLVMContext, HelperFunctionName.c_str()));
420      }
421
422      mExportFuncMetadata->addOperand(
423          llvm::MDNode::get(mLLVMContext, ExportFuncInfo));
424      ExportFuncInfo.clear();
425    }
426  }
427
428  // Dump export function info
429  if (mContext->hasExportForEach()) {
430    if (mExportForEachNameMetadata == NULL) {
431      mExportForEachNameMetadata =
432          M->getOrInsertNamedMetadata(RS_EXPORT_FOREACH_NAME_MN);
433    }
434    if (mExportForEachSignatureMetadata == NULL) {
435      mExportForEachSignatureMetadata =
436          M->getOrInsertNamedMetadata(RS_EXPORT_FOREACH_MN);
437    }
438
439    llvm::SmallVector<llvm::Value*, 1> ExportForEachName;
440    llvm::SmallVector<llvm::Value*, 1> ExportForEachInfo;
441
442    for (RSContext::const_export_foreach_iterator
443            I = mContext->export_foreach_begin(),
444            E = mContext->export_foreach_end();
445         I != E;
446         I++) {
447      const RSExportForEach *EFE = *I;
448
449      ExportForEachName.push_back(
450          llvm::MDString::get(mLLVMContext, EFE->getName().c_str()));
451
452      mExportForEachNameMetadata->addOperand(
453          llvm::MDNode::get(mLLVMContext, ExportForEachName));
454      ExportForEachName.clear();
455
456      ExportForEachInfo.push_back(
457          llvm::MDString::get(mLLVMContext,
458                              llvm::utostr_32(EFE->getSignatureMetadata())));
459
460      mExportForEachSignatureMetadata->addOperand(
461          llvm::MDNode::get(mLLVMContext, ExportForEachInfo));
462      ExportForEachInfo.clear();
463    }
464  }
465
466  // Dump export type info
467  if (mContext->hasExportType()) {
468    llvm::SmallVector<llvm::Value*, 1> ExportTypeInfo;
469
470    for (RSContext::const_export_type_iterator
471            I = mContext->export_types_begin(),
472            E = mContext->export_types_end();
473         I != E;
474         I++) {
475      // First, dump type name list to export
476      const RSExportType *ET = I->getValue();
477
478      ExportTypeInfo.clear();
479      // Type name
480      ExportTypeInfo.push_back(
481          llvm::MDString::get(mLLVMContext, ET->getName().c_str()));
482
483      if (ET->getClass() == RSExportType::ExportClassRecord) {
484        const RSExportRecordType *ERT =
485            static_cast<const RSExportRecordType*>(ET);
486
487        if (mExportTypeMetadata == NULL)
488          mExportTypeMetadata =
489              M->getOrInsertNamedMetadata(RS_EXPORT_TYPE_MN);
490
491        mExportTypeMetadata->addOperand(
492            llvm::MDNode::get(mLLVMContext, ExportTypeInfo));
493
494        // Now, export struct field information to %[struct name]
495        std::string StructInfoMetadataName("%");
496        StructInfoMetadataName.append(ET->getName());
497        llvm::NamedMDNode *StructInfoMetadata =
498            M->getOrInsertNamedMetadata(StructInfoMetadataName);
499        llvm::SmallVector<llvm::Value*, 3> FieldInfo;
500
501        slangAssert(StructInfoMetadata->getNumOperands() == 0 &&
502                    "Metadata with same name was created before");
503        for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
504                FE = ERT->fields_end();
505             FI != FE;
506             FI++) {
507          const RSExportRecordType::Field *F = *FI;
508
509          // 1. field name
510          FieldInfo.push_back(llvm::MDString::get(mLLVMContext,
511                                                  F->getName().c_str()));
512
513          // 2. field type name
514          FieldInfo.push_back(
515              llvm::MDString::get(mLLVMContext,
516                                  F->getType()->getName().c_str()));
517
518          StructInfoMetadata->addOperand(
519              llvm::MDNode::get(mLLVMContext, FieldInfo));
520          FieldInfo.clear();
521        }
522      }   // ET->getClass() == RSExportType::ExportClassRecord
523    }
524  }
525
526  return;
527}
528
529RSBackend::~RSBackend() {
530  return;
531}
532
533}  // namespace slang
534