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