Debian Codegraph @

clang/lib/Interpreter/IncrementalParser.cpp

raw
1 //===--------- IncrementalParser.cpp - Incremental Compilation -----------===//
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 file implements the class which performs incremental code compilation.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "IncrementalParser.h"
14 #include "IncrementalAction.h"
15
16 #include "clang/AST/DeclContextInternals.h"
17 #include "clang/Frontend/CompilerInstance.h"
18 #include "clang/Interpreter/PartialTranslationUnit.h"
19 #include "clang/Parse/Parser.h"
20 #include "clang/Sema/Sema.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Support/CrashRecoveryContext.h"
23 #include "llvm/Support/Error.h"
24
25 #include <sstream>
26
27 #define DEBUG_TYPE "clang-repl"
28
29 namespace clang {
30
31 // IncrementalParser::IncrementalParser() {}
32
33 IncrementalParser::IncrementalParser(CompilerInstance &Instance,
34 IncrementalAction *Act, llvm::Error &Err,
35 std::list<PartialTranslationUnit> &PTUs)
36 : S(Instance.getSema()), Act(Act), PTUs(PTUs) {
37 llvm::ErrorAsOutParameter EAO(&Err);
38 Consumer = &S.getASTConsumer();
39 P.reset(new Parser(S.getPreprocessor(), S, /*SkipBodies=*/false));
40
41 if (ExternalASTSource *External = S.getASTContext().getExternalSource())
42 External->StartTranslationUnit(Consumer);
43
44 P->Initialize();
45 }
46
47 IncrementalParser::~IncrementalParser() { P.reset(); }
48
49 llvm::Expected<TranslationUnitDecl *>
50 IncrementalParser::ParseOrWrapTopLevelDecl() {
51 // Recover resources if we crash before exiting this method.
52 llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(&S);
53 Sema::GlobalEagerInstantiationScope GlobalInstantiations(S, /*Enabled=*/true,
54 /*AtEndOfTU=*/true);
55 Sema::LocalEagerInstantiationScope LocalInstantiations(S, /*AtEndOfTU=*/true);
56
57 // Add a new PTU.
58 ASTContext &C = S.getASTContext();
59 C.addTranslationUnitDecl();
60
61 // Skip previous eof due to last incremental input.
62 if (P->getCurToken().is(tok::annot_repl_input_end)) {
63 P->ConsumeAnyToken();
64 // FIXME: Clang does not call ExitScope on finalizing the regular TU, we
65 // might want to do that around HandleEndOfTranslationUnit.
66 P->ExitScope();
67 S.CurContext = nullptr;
68 // Start a new PTU.
69 P->EnterScope(Scope::DeclScope);
70 S.ActOnTranslationUnitScope(P->getCurScope());
71 }
72
73 Parser::DeclGroupPtrTy ADecl;
74 Sema::ModuleImportState ImportState;
75 for (bool AtEOF = P->ParseFirstTopLevelDecl(ADecl, ImportState); !AtEOF;
76 AtEOF = P->ParseTopLevelDecl(ADecl, ImportState)) {
77 if (ADecl && !Consumer->HandleTopLevelDecl(ADecl.get()))
78 return llvm::make_error<llvm::StringError>("Parsing failed. "
79 "The consumer rejected a decl",
80 std::error_code());
81 }
82
83 DiagnosticsEngine &Diags = S.getDiagnostics();
84 if (Diags.hasErrorOccurred()) {
85 CleanUpPTU(C.getTranslationUnitDecl());
86
87 Diags.Reset(/*soft=*/true);
88 Diags.getClient()->clear();
89 return llvm::make_error<llvm::StringError>("Parsing failed.",
90 std::error_code());
91 }
92
93 // Process any TopLevelDecls generated by #pragma weak.
94 for (Decl *D : S.WeakTopLevelDecls()) {
95 DeclGroupRef DGR(D);
96 Consumer->HandleTopLevelDecl(DGR);
97 }
98
99 LocalInstantiations.perform();
100 GlobalInstantiations.perform();
101
102 Consumer->HandleTranslationUnit(C);
103
104 return C.getTranslationUnitDecl();
105 }
106
107 llvm::Expected<TranslationUnitDecl *>
108 IncrementalParser::Parse(llvm::StringRef input) {
109 Preprocessor &PP = S.getPreprocessor();
110 assert(PP.isIncrementalProcessingEnabled() && "Not in incremental mode!?");
111
112 std::ostringstream SourceName;
113 SourceName << "input_line_" << InputCount++;
114
115 // Create an uninitialized memory buffer, copy code in and append "\n"
116 size_t InputSize = input.size(); // don't include trailing 0
117 // MemBuffer size should *not* include terminating zero
118 std::unique_ptr<llvm::MemoryBuffer> MB(
119 llvm::WritableMemoryBuffer::getNewUninitMemBuffer(InputSize + 1,
120 SourceName.str()));
121 char *MBStart = const_cast<char *>(MB->getBufferStart());
122 memcpy(MBStart, input.data(), InputSize);
123 MBStart[InputSize] = '\n';
124
125 SourceManager &SM = S.getSourceManager();
126
127 // FIXME: Create SourceLocation, which will allow clang to order the overload
128 // candidates for example
129 SourceLocation NewLoc = SM.getLocForStartOfFile(SM.getMainFileID());
130
131 // Create FileID for the current buffer.
132 FileID FID;
133 // Create FileEntry and FileID for the current buffer.
134 FileEntryRef FE = SM.getFileManager().getVirtualFileRef(
135 SourceName.str(), InputSize, 0 /* mod time*/);
136 SM.overrideFileContents(FE, std::move(MB));
137
138 // Ensure HeaderFileInfo exists before lookup to prevent assertion
139 HeaderSearch &HS = PP.getHeaderSearchInfo();
140 HS.getFileInfo(FE);
141
142 FID = SM.createFileID(FE, NewLoc, SrcMgr::C_User);
143
144 // NewLoc only used for diags.
145 if (PP.EnterSourceFile(FID, /*DirLookup=*/nullptr, NewLoc))
146 return llvm::make_error<llvm::StringError>("Parsing failed. "
147 "Cannot enter source file.",
148 std::error_code());
149
150 auto PTU = ParseOrWrapTopLevelDecl();
151 if (!PTU)
152 return PTU.takeError();
153
154 if (PP.getLangOpts().DelayedTemplateParsing) {
155 // Microsoft-specific:
156 // Late parsed templates can leave unswallowed "macro"-like tokens.
157 // They will seriously confuse the Parser when entering the next
158 // source file. So lex until we are EOF.
159 Token Tok;
160 do {
161 PP.Lex(Tok);
162 } while (Tok.isNot(tok::annot_repl_input_end));
163 } else {
164 Token AssertTok;
165 PP.Lex(AssertTok);
166 assert(AssertTok.is(tok::annot_repl_input_end) &&
167 "Lexer must be EOF when starting incremental parse!");
168 }
169
170 return PTU;
171 }
172
173 void IncrementalParser::CleanUpPTU(TranslationUnitDecl *MostRecentTU) {
174 if (StoredDeclsMap *Map = MostRecentTU->getPrimaryContext()->getLookupPtr()) {
175 for (auto &&[Key, List] : *Map) {
176 DeclContextLookupResult R = List.getLookupResult();
177 std::vector<NamedDecl *> NamedDeclsToRemove;
178 bool RemoveAll = true;
179 for (NamedDecl *D : R) {
180 if (D->getTranslationUnitDecl() == MostRecentTU)
181 NamedDeclsToRemove.push_back(D);
182 else
183 RemoveAll = false;
184 }
185 if (LLVM_LIKELY(RemoveAll)) {
186 Map->erase(Key);
187 } else {
188 for (NamedDecl *D : NamedDeclsToRemove)
189 List.remove(D);
190 }
191 }
192 }
193
194 // FIXME: We should de-allocate MostRecentTU
195 for (Decl *D : MostRecentTU->decls()) {
196 auto *ND = dyn_cast<NamedDecl>(D);
197 if (!ND || ND->getDeclName().isEmpty())
198 continue;
199 // Check if we need to clean up the IdResolver chain.
200 if (ND->getDeclName().getFETokenInfo() && !D->getLangOpts().ObjC &&
201 !D->getLangOpts().CPlusPlus)
202 S.IdResolver.RemoveDecl(ND);
203 }
204 }
205
206 PartialTranslationUnit &
207 IncrementalParser::RegisterPTU(TranslationUnitDecl *TU,
208 std::unique_ptr<llvm::Module> M /*={}*/) {
209 PTUs.emplace_back(PartialTranslationUnit());
210 PartialTranslationUnit &LastPTU = PTUs.back();
211 LastPTU.TUPart = TU;
212
213 if (!M)
214 M = Act->GenModule();
215
216 assert((!Act->getCodeGen() || M) && "Must have a llvm::Module at this point");
217
218 LastPTU.TheModule = std::move(M);
219 LLVM_DEBUG(llvm::dbgs() << "compile-ptu " << PTUs.size() - 1
220 << ": [TU=" << LastPTU.TUPart);
221 if (LastPTU.TheModule)
222 LLVM_DEBUG(llvm::dbgs() << ", M=" << LastPTU.TheModule.get() << " ("
223 << LastPTU.TheModule->getName() << ")");
224 LLVM_DEBUG(llvm::dbgs() << "]\n");
225 return LastPTU;
226 }
227 } // end namespace clang