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