Home | History | Annotate | Download | only in CodeGen
      1 //===--- ModuleBuilder.cpp - Emit LLVM Code from ASTs ---------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This builds an AST and converts it to LLVM Code.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/CodeGen/ModuleBuilder.h"
     15 #include "CGDebugInfo.h"
     16 #include "CodeGenModule.h"
     17 #include "clang/AST/ASTContext.h"
     18 #include "clang/AST/DeclObjC.h"
     19 #include "clang/AST/Expr.h"
     20 #include "clang/Basic/Diagnostic.h"
     21 #include "clang/Basic/TargetInfo.h"
     22 #include "clang/Frontend/CodeGenOptions.h"
     23 #include "llvm/ADT/StringRef.h"
     24 #include "llvm/IR/DataLayout.h"
     25 #include "llvm/IR/LLVMContext.h"
     26 #include "llvm/IR/Module.h"
     27 #include <memory>
     28 
     29 using namespace clang;
     30 using namespace CodeGen;
     31 
     32 namespace {
     33   class CodeGeneratorImpl : public CodeGenerator {
     34     DiagnosticsEngine &Diags;
     35     ASTContext *Ctx;
     36     const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
     37     const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
     38     const CodeGenOptions CodeGenOpts;  // Intentionally copied in.
     39 
     40     unsigned HandlingTopLevelDecls;
     41 
     42     /// Use this when emitting decls to block re-entrant decl emission. It will
     43     /// emit all deferred decls on scope exit. Set EmitDeferred to false if decl
     44     /// emission must be deferred longer, like at the end of a tag definition.
     45     struct HandlingTopLevelDeclRAII {
     46       CodeGeneratorImpl &Self;
     47       bool EmitDeferred;
     48       HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self,
     49                                bool EmitDeferred = true)
     50           : Self(Self), EmitDeferred(EmitDeferred) {
     51         ++Self.HandlingTopLevelDecls;
     52       }
     53       ~HandlingTopLevelDeclRAII() {
     54         unsigned Level = --Self.HandlingTopLevelDecls;
     55         if (Level == 0 && EmitDeferred)
     56           Self.EmitDeferredDecls();
     57       }
     58     };
     59 
     60     CoverageSourceInfo *CoverageInfo;
     61 
     62   protected:
     63     std::unique_ptr<llvm::Module> M;
     64     std::unique_ptr<CodeGen::CodeGenModule> Builder;
     65 
     66   private:
     67     SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
     68 
     69   public:
     70     CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
     71                       const HeaderSearchOptions &HSO,
     72                       const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
     73                       llvm::LLVMContext &C,
     74                       CoverageSourceInfo *CoverageInfo = nullptr)
     75         : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
     76           PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
     77           CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) {
     78       C.setDiscardValueNames(CGO.DiscardValueNames);
     79     }
     80 
     81     ~CodeGeneratorImpl() override {
     82       // There should normally not be any leftover inline method definitions.
     83       assert(DeferredInlineMethodDefinitions.empty() ||
     84              Diags.hasErrorOccurred());
     85     }
     86 
     87     CodeGenModule &CGM() {
     88       return *Builder;
     89     }
     90 
     91     llvm::Module *GetModule() {
     92       return M.get();
     93     }
     94 
     95     llvm::Module *ReleaseModule() {
     96       return M.release();
     97     }
     98 
     99     const Decl *GetDeclForMangledName(StringRef MangledName) {
    100       GlobalDecl Result;
    101       if (!Builder->lookupRepresentativeDecl(MangledName, Result))
    102         return nullptr;
    103       const Decl *D = Result.getCanonicalDecl().getDecl();
    104       if (auto FD = dyn_cast<FunctionDecl>(D)) {
    105         if (FD->hasBody(FD))
    106           return FD;
    107       } else if (auto TD = dyn_cast<TagDecl>(D)) {
    108         if (auto Def = TD->getDefinition())
    109           return Def;
    110       }
    111       return D;
    112     }
    113 
    114     llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
    115       return Builder->GetAddrOfGlobal(global, isForDefinition);
    116     }
    117 
    118     void Initialize(ASTContext &Context) override {
    119       Ctx = &Context;
    120 
    121       M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
    122       M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
    123       Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
    124                                                PreprocessorOpts, CodeGenOpts,
    125                                                *M, Diags, CoverageInfo));
    126 
    127       for (auto &&Lib : CodeGenOpts.DependentLibraries)
    128         Builder->AddDependentLib(Lib);
    129       for (auto &&Opt : CodeGenOpts.LinkerOptions)
    130         Builder->AppendLinkerOptions(Opt);
    131     }
    132 
    133     void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
    134       if (Diags.hasErrorOccurred())
    135         return;
    136 
    137       Builder->HandleCXXStaticMemberVarInstantiation(VD);
    138     }
    139 
    140     bool HandleTopLevelDecl(DeclGroupRef DG) override {
    141       if (Diags.hasErrorOccurred())
    142         return true;
    143 
    144       HandlingTopLevelDeclRAII HandlingDecl(*this);
    145 
    146       // Make sure to emit all elements of a Decl.
    147       for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
    148         Builder->EmitTopLevelDecl(*I);
    149 
    150       return true;
    151     }
    152 
    153     void EmitDeferredDecls() {
    154       if (DeferredInlineMethodDefinitions.empty())
    155         return;
    156 
    157       // Emit any deferred inline method definitions. Note that more deferred
    158       // methods may be added during this loop, since ASTConsumer callbacks
    159       // can be invoked if AST inspection results in declarations being added.
    160       HandlingTopLevelDeclRAII HandlingDecl(*this);
    161       for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
    162         Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
    163       DeferredInlineMethodDefinitions.clear();
    164     }
    165 
    166     void HandleInlineFunctionDefinition(FunctionDecl *D) override {
    167       if (Diags.hasErrorOccurred())
    168         return;
    169 
    170       assert(D->doesThisDeclarationHaveABody());
    171 
    172       // Handle friend functions.
    173       if (D->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)) {
    174         if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()
    175             && !D->getLexicalDeclContext()->isDependentContext())
    176           Builder->EmitTopLevelDecl(D);
    177         return;
    178       }
    179 
    180       // Otherwise, must be a method.
    181       auto MD = cast<CXXMethodDecl>(D);
    182 
    183       // We may want to emit this definition. However, that decision might be
    184       // based on computing the linkage, and we have to defer that in case we
    185       // are inside of something that will change the method's final linkage,
    186       // e.g.
    187       //   typedef struct {
    188       //     void bar();
    189       //     void foo() { bar(); }
    190       //   } A;
    191       DeferredInlineMethodDefinitions.push_back(MD);
    192 
    193       // Provide some coverage mapping even for methods that aren't emitted.
    194       // Don't do this for templated classes though, as they may not be
    195       // instantiable.
    196       if (!MD->getParent()->getDescribedClassTemplate())
    197         Builder->AddDeferredUnusedCoverageMapping(MD);
    198     }
    199 
    200     /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
    201     /// to (e.g. struct, union, enum, class) is completed. This allows the
    202     /// client hack on the type, which can occur at any point in the file
    203     /// (because these can be defined in declspecs).
    204     void HandleTagDeclDefinition(TagDecl *D) override {
    205       if (Diags.hasErrorOccurred())
    206         return;
    207 
    208       // Don't allow re-entrant calls to CodeGen triggered by PCH
    209       // deserialization to emit deferred decls.
    210       HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
    211 
    212       Builder->UpdateCompletedType(D);
    213 
    214       // For MSVC compatibility, treat declarations of static data members with
    215       // inline initializers as definitions.
    216       if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
    217         for (Decl *Member : D->decls()) {
    218           if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
    219             if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
    220                 Ctx->DeclMustBeEmitted(VD)) {
    221               Builder->EmitGlobal(VD);
    222             }
    223           }
    224         }
    225       }
    226       // For OpenMP emit declare reduction functions, if required.
    227       if (Ctx->getLangOpts().OpenMP) {
    228         for (Decl *Member : D->decls()) {
    229           if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
    230             if (Ctx->DeclMustBeEmitted(DRD))
    231               Builder->EmitGlobal(DRD);
    232           }
    233         }
    234       }
    235     }
    236 
    237     void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
    238       if (Diags.hasErrorOccurred())
    239         return;
    240 
    241       // Don't allow re-entrant calls to CodeGen triggered by PCH
    242       // deserialization to emit deferred decls.
    243       HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
    244 
    245       if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
    246         if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
    247           DI->completeRequiredType(RD);
    248     }
    249 
    250     void HandleTranslationUnit(ASTContext &Ctx) override {
    251       // Release the Builder when there is no error.
    252       if (!Diags.hasErrorOccurred() && Builder)
    253         Builder->Release();
    254 
    255       // If there are errors before or when releasing the Builder, reset
    256       // the module to stop here before invoking the backend.
    257       if (Diags.hasErrorOccurred()) {
    258         if (Builder)
    259           Builder->clear();
    260         M.reset();
    261         return;
    262       }
    263     }
    264 
    265     void AssignInheritanceModel(CXXRecordDecl *RD) override {
    266       if (Diags.hasErrorOccurred())
    267         return;
    268 
    269       Builder->RefreshTypeCacheForClass(RD);
    270     }
    271 
    272     void CompleteTentativeDefinition(VarDecl *D) override {
    273       if (Diags.hasErrorOccurred())
    274         return;
    275 
    276       Builder->EmitTentativeDefinition(D);
    277     }
    278 
    279     void HandleVTable(CXXRecordDecl *RD) override {
    280       if (Diags.hasErrorOccurred())
    281         return;
    282 
    283       Builder->EmitVTable(RD);
    284     }
    285   };
    286 }
    287 
    288 void CodeGenerator::anchor() { }
    289 
    290 CodeGenModule &CodeGenerator::CGM() {
    291   return static_cast<CodeGeneratorImpl*>(this)->CGM();
    292 }
    293 
    294 llvm::Module *CodeGenerator::GetModule() {
    295   return static_cast<CodeGeneratorImpl*>(this)->GetModule();
    296 }
    297 
    298 llvm::Module *CodeGenerator::ReleaseModule() {
    299   return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
    300 }
    301 
    302 const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) {
    303   return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
    304 }
    305 
    306 llvm::Constant *CodeGenerator::GetAddrOfGlobal(GlobalDecl global,
    307                                                bool isForDefinition) {
    308   return static_cast<CodeGeneratorImpl*>(this)
    309            ->GetAddrOfGlobal(global, isForDefinition);
    310 }
    311 
    312 CodeGenerator *clang::CreateLLVMCodeGen(
    313     DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
    314     const HeaderSearchOptions &HeaderSearchOpts,
    315     const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
    316     llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
    317   return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
    318                                PreprocessorOpts, CGO, C, CoverageInfo);
    319 }
    320