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 using namespace clang; 29 30 namespace { 31 class CodeGeneratorImpl : public CodeGenerator { 32 DiagnosticsEngine &Diags; 33 ASTContext *Ctx; 34 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info. 35 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info. 36 const CodeGenOptions CodeGenOpts; // Intentionally copied in. 37 38 unsigned HandlingTopLevelDecls; 39 struct HandlingTopLevelDeclRAII { 40 CodeGeneratorImpl &Self; 41 HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self) : Self(Self) { 42 ++Self.HandlingTopLevelDecls; 43 } 44 ~HandlingTopLevelDeclRAII() { 45 if (--Self.HandlingTopLevelDecls == 0) 46 Self.EmitDeferredDecls(); 47 } 48 }; 49 50 CoverageSourceInfo *CoverageInfo; 51 52 protected: 53 std::unique_ptr<llvm::Module> M; 54 std::unique_ptr<CodeGen::CodeGenModule> Builder; 55 56 private: 57 SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions; 58 59 public: 60 CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string &ModuleName, 61 const HeaderSearchOptions &HSO, 62 const PreprocessorOptions &PPO, const CodeGenOptions &CGO, 63 llvm::LLVMContext &C, 64 CoverageSourceInfo *CoverageInfo = nullptr) 65 : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO), 66 PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0), 67 CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) { 68 C.setDiscardValueNames(CGO.DiscardValueNames); 69 } 70 71 ~CodeGeneratorImpl() override { 72 // There should normally not be any leftover inline method definitions. 73 assert(DeferredInlineMethodDefinitions.empty() || 74 Diags.hasErrorOccurred()); 75 } 76 77 llvm::Module* GetModule() override { 78 return M.get(); 79 } 80 81 const Decl *GetDeclForMangledName(StringRef MangledName) override { 82 GlobalDecl Result; 83 if (!Builder->lookupRepresentativeDecl(MangledName, Result)) 84 return nullptr; 85 const Decl *D = Result.getCanonicalDecl().getDecl(); 86 if (auto FD = dyn_cast<FunctionDecl>(D)) { 87 if (FD->hasBody(FD)) 88 return FD; 89 } else if (auto TD = dyn_cast<TagDecl>(D)) { 90 if (auto Def = TD->getDefinition()) 91 return Def; 92 } 93 return D; 94 } 95 96 llvm::Module *ReleaseModule() override { return M.release(); } 97 98 void Initialize(ASTContext &Context) override { 99 Ctx = &Context; 100 101 M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple()); 102 M->setDataLayout(Ctx->getTargetInfo().getDataLayout()); 103 Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts, 104 PreprocessorOpts, CodeGenOpts, 105 *M, Diags, CoverageInfo)); 106 107 for (auto &&Lib : CodeGenOpts.DependentLibraries) 108 Builder->AddDependentLib(Lib); 109 for (auto &&Opt : CodeGenOpts.LinkerOptions) 110 Builder->AppendLinkerOptions(Opt); 111 } 112 113 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override { 114 if (Diags.hasErrorOccurred()) 115 return; 116 117 Builder->HandleCXXStaticMemberVarInstantiation(VD); 118 } 119 120 bool HandleTopLevelDecl(DeclGroupRef DG) override { 121 if (Diags.hasErrorOccurred()) 122 return true; 123 124 HandlingTopLevelDeclRAII HandlingDecl(*this); 125 126 // Make sure to emit all elements of a Decl. 127 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 128 Builder->EmitTopLevelDecl(*I); 129 130 return true; 131 } 132 133 void EmitDeferredDecls() { 134 if (DeferredInlineMethodDefinitions.empty()) 135 return; 136 137 // Emit any deferred inline method definitions. Note that more deferred 138 // methods may be added during this loop, since ASTConsumer callbacks 139 // can be invoked if AST inspection results in declarations being added. 140 HandlingTopLevelDeclRAII HandlingDecl(*this); 141 for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I) 142 Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]); 143 DeferredInlineMethodDefinitions.clear(); 144 } 145 146 void HandleInlineMethodDefinition(CXXMethodDecl *D) override { 147 if (Diags.hasErrorOccurred()) 148 return; 149 150 assert(D->doesThisDeclarationHaveABody()); 151 152 // We may want to emit this definition. However, that decision might be 153 // based on computing the linkage, and we have to defer that in case we 154 // are inside of something that will change the method's final linkage, 155 // e.g. 156 // typedef struct { 157 // void bar(); 158 // void foo() { bar(); } 159 // } A; 160 DeferredInlineMethodDefinitions.push_back(D); 161 162 // Provide some coverage mapping even for methods that aren't emitted. 163 // Don't do this for templated classes though, as they may not be 164 // instantiable. 165 if (!D->getParent()->getDescribedClassTemplate()) 166 Builder->AddDeferredUnusedCoverageMapping(D); 167 } 168 169 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl 170 /// to (e.g. struct, union, enum, class) is completed. This allows the 171 /// client hack on the type, which can occur at any point in the file 172 /// (because these can be defined in declspecs). 173 void HandleTagDeclDefinition(TagDecl *D) override { 174 if (Diags.hasErrorOccurred()) 175 return; 176 177 Builder->UpdateCompletedType(D); 178 179 // For MSVC compatibility, treat declarations of static data members with 180 // inline initializers as definitions. 181 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) { 182 for (Decl *Member : D->decls()) { 183 if (VarDecl *VD = dyn_cast<VarDecl>(Member)) { 184 if (Ctx->isMSStaticDataMemberInlineDefinition(VD) && 185 Ctx->DeclMustBeEmitted(VD)) { 186 Builder->EmitGlobal(VD); 187 } 188 } 189 } 190 } 191 // For OpenMP emit declare reduction functions, if required. 192 if (Ctx->getLangOpts().OpenMP) { 193 for (Decl *Member : D->decls()) { 194 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) { 195 if (Ctx->DeclMustBeEmitted(DRD)) 196 Builder->EmitGlobal(DRD); 197 } 198 } 199 } 200 } 201 202 void HandleTagDeclRequiredDefinition(const TagDecl *D) override { 203 if (Diags.hasErrorOccurred()) 204 return; 205 206 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo()) 207 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) 208 DI->completeRequiredType(RD); 209 } 210 211 void HandleTranslationUnit(ASTContext &Ctx) override { 212 // Release the Builder when there is no error. 213 if (!Diags.hasErrorOccurred() && Builder) 214 Builder->Release(); 215 216 // If there are errors before or when releasing the Builder, reset 217 // the module to stop here before invoking the backend. 218 if (Diags.hasErrorOccurred()) { 219 if (Builder) 220 Builder->clear(); 221 M.reset(); 222 return; 223 } 224 } 225 226 void AssignInheritanceModel(CXXRecordDecl *RD) override { 227 if (Diags.hasErrorOccurred()) 228 return; 229 230 Builder->RefreshTypeCacheForClass(RD); 231 } 232 233 void CompleteTentativeDefinition(VarDecl *D) override { 234 if (Diags.hasErrorOccurred()) 235 return; 236 237 Builder->EmitTentativeDefinition(D); 238 } 239 240 void HandleVTable(CXXRecordDecl *RD) override { 241 if (Diags.hasErrorOccurred()) 242 return; 243 244 Builder->EmitVTable(RD); 245 } 246 }; 247 } 248 249 void CodeGenerator::anchor() { } 250 251 CodeGenerator *clang::CreateLLVMCodeGen( 252 DiagnosticsEngine &Diags, const std::string &ModuleName, 253 const HeaderSearchOptions &HeaderSearchOpts, 254 const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO, 255 llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) { 256 return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts, 257 PreprocessorOpts, CGO, C, CoverageInfo); 258 } 259