Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Frontend/FrontendAction.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- FrontendAction.cpp -----------------------------------------------===//
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
#include "clang/Frontend/FrontendAction.h"
10
#include "clang/AST/ASTConsumer.h"
11
#include "clang/AST/ASTContext.h"
12
#include "clang/AST/DeclGroup.h"
13
#include "clang/Basic/Builtins.h"
14
#include "clang/Basic/LangStandard.h"
15
#include "clang/Frontend/ASTUnit.h"
16
#include "clang/Frontend/CompilerInstance.h"
17
#include "clang/Frontend/FrontendDiagnostic.h"
18
#include "clang/Frontend/FrontendPluginRegistry.h"
19
#include "clang/Frontend/LayoutOverrideSource.h"
20
#include "clang/Frontend/MultiplexConsumer.h"
21
#include "clang/Frontend/Utils.h"
22
#include "clang/Lex/HeaderSearch.h"
23
#include "clang/Lex/LiteralSupport.h"
24
#include "clang/Lex/Preprocessor.h"
25
#include "clang/Lex/PreprocessorOptions.h"
26
#include "clang/Parse/ParseAST.h"
27
#include "clang/Serialization/ASTDeserializationListener.h"
28
#include "clang/Serialization/ASTReader.h"
29
#include "clang/Serialization/GlobalModuleIndex.h"
30
#include "llvm/Support/BuryPointer.h"
31
#include "llvm/Support/ErrorHandling.h"
32
#include "llvm/Support/FileSystem.h"
33
#include "llvm/Support/Path.h"
34
#include "llvm/Support/Timer.h"
35
#include "llvm/Support/raw_ostream.h"
36
#include <system_error>
37
using namespace clang;
38
39
LLVM_INSTANTIATE_REGISTRY(FrontendPluginRegistry)
40
41
namespace {
42
43
class DelegatingDeserializationListener : public ASTDeserializationListener {
44
  ASTDeserializationListener *Previous;
45
  bool DeletePrevious;
46
47
public:
48
  explicit DelegatingDeserializationListener(
49
      ASTDeserializationListener *Previous, bool DeletePrevious)
50
106
      : Previous(Previous), DeletePrevious(DeletePrevious) {}
51
104
  ~DelegatingDeserializationListener() override {
52
104
    if (DeletePrevious)
53
0
      delete Previous;
54
104
  }
55
56
212
  void ReaderInitialized(ASTReader *Reader) override {
57
212
    if (Previous)
58
26
      Previous->ReaderInitialized(Reader);
59
212
  }
60
  void IdentifierRead(serialization::IdentID ID,
61
7.70k
                      IdentifierInfo *II) override {
62
7.70k
    if (Previous)
63
261
      Previous->IdentifierRead(ID, II);
64
7.70k
  }
65
1.13k
  void TypeRead(serialization::TypeIdx Idx, QualType T) override {
66
1.13k
    if (Previous)
67
28
      Previous->TypeRead(Idx, T);
68
1.13k
  }
69
1.30k
  void DeclRead(serialization::DeclID ID, const Decl *D) override {
70
1.30k
    if (Previous)
71
15
      Previous->DeclRead(ID, D);
72
1.30k
  }
73
0
  void SelectorRead(serialization::SelectorID ID, Selector Sel) override {
74
0
    if (Previous)
75
0
      Previous->SelectorRead(ID, Sel);
76
0
  }
77
  void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
78
99
                           MacroDefinitionRecord *MD) override {
79
99
    if (Previous)
80
12
      Previous->MacroDefinitionRead(PPID, MD);
81
99
  }
82
};
83
84
/// Dumps deserialized declarations.
85
class DeserializedDeclsDumper : public DelegatingDeserializationListener {
86
public:
87
  explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous,
88
                                   bool DeletePrevious)
89
0
      : DelegatingDeserializationListener(Previous, DeletePrevious) {}
90
91
0
  void DeclRead(serialization::DeclID ID, const Decl *D) override {
92
0
    llvm::outs() << "PCH DECL: " << D->getDeclKindName();
93
0
    if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
94
0
      llvm::outs() << " - ";
95
0
      ND->printQualifiedName(llvm::outs());
96
0
    }
97
0
    llvm::outs() << "\n";
98
99
0
    DelegatingDeserializationListener::DeclRead(ID, D);
100
0
  }
101
};
102
103
/// Checks deserialized declarations and emits error if a name
104
/// matches one given in command-line using -error-on-deserialized-decl.
105
class DeserializedDeclsChecker : public DelegatingDeserializationListener {
106
  ASTContext &Ctx;
107
  std::set<std::string> NamesToCheck;
108
109
public:
110
  DeserializedDeclsChecker(ASTContext &Ctx,
111
                           const std::set<std::string> &NamesToCheck,
112
                           ASTDeserializationListener *Previous,
113
                           bool DeletePrevious)
114
      : DelegatingDeserializationListener(Previous, DeletePrevious), Ctx(Ctx),
115
106
        NamesToCheck(NamesToCheck) {}
116
117
1.30k
  void DeclRead(serialization::DeclID ID, const Decl *D) override {
118
1.30k
    if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
119
1.18k
      if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
120
2
        unsigned DiagID
121
2
          = Ctx.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error,
122
2
                                                 "%0 was deserialized");
123
2
        Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
124
2
            << ND;
125
2
      }
126
127
1.30k
    DelegatingDeserializationListener::DeclRead(ID, D);
128
1.30k
  }
129
};
130
131
} // end anonymous namespace
132
133
71.5k
FrontendAction::FrontendAction() : Instance(nullptr) {}
134
135
65.7k
FrontendAction::~FrontendAction() {}
136
137
void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput,
138
141k
                                     std::unique_ptr<ASTUnit> AST) {
139
141k
  this->CurrentInput = CurrentInput;
140
141k
  CurrentASTUnit = std::move(AST);
141
141k
}
142
143
19
Module *FrontendAction::getCurrentModule() const {
144
19
  CompilerInstance &CI = getCompilerInstance();
145
19
  return CI.getPreprocessor().getHeaderSearchInfo().lookupModule(
146
19
      CI.getLangOpts().CurrentModule, /*AllowSearch*/false);
147
19
}
148
149
std::unique_ptr<ASTConsumer>
150
FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
151
69.0k
                                         StringRef InFile) {
152
69.0k
  std::unique_ptr<ASTConsumer> Consumer = CreateASTConsumer(CI, InFile);
153
69.0k
  if (!Consumer)
154
3
    return nullptr;
155
156
  // Validate -add-plugin args.
157
69.0k
  bool FoundAllPlugins = true;
158
69.0k
  for (const std::string &Arg : CI.getFrontendOpts().AddPluginActions) {
159
1
    bool Found = false;
160
1
    for (const FrontendPluginRegistry::entry &Plugin :
161
1
         FrontendPluginRegistry::entries()) {
162
0
      if (Plugin.getName() == Arg)
163
0
        Found = true;
164
0
    }
165
1
    if (!Found) {
166
1
      CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name) << Arg;
167
1
      FoundAllPlugins = false;
168
1
    }
169
1
  }
170
69.0k
  if (!FoundAllPlugins)
171
1
    return nullptr;
172
173
  // If there are no registered plugins we don't need to wrap the consumer
174
69.0k
  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
175
69.0k
    return Consumer;
176
177
  // If this is a code completion run, avoid invoking the plugin consumers
178
18.4E
  if (CI.hasCodeCompletionConsumer())
179
0
    return Consumer;
180
181
  // Collect the list of plugins that go before the main action (in Consumers)
182
  // or after it (in AfterConsumers)
183
18.4E
  std::vector<std::unique_ptr<ASTConsumer>> Consumers;
184
18.4E
  std::vector<std::unique_ptr<ASTConsumer>> AfterConsumers;
185
18.4E
  for (const FrontendPluginRegistry::entry &Plugin :
186
18.4E
       FrontendPluginRegistry::entries()) {
187
0
    std::unique_ptr<PluginASTAction> P = Plugin.instantiate();
188
0
    PluginASTAction::ActionType ActionType = P->getActionType();
189
0
    if (ActionType == PluginASTAction::Cmdline) {
190
      // This is O(|plugins| * |add_plugins|), but since both numbers are
191
      // way below 50 in practice, that's ok.
192
0
      if (llvm::any_of(CI.getFrontendOpts().AddPluginActions,
193
0
                       [&](const std::string &PluginAction) {
194
0
                         return PluginAction == Plugin.getName();
195
0
                       }))
196
0
        ActionType = PluginASTAction::AddAfterMainAction;
197
0
    }
198
0
    if ((ActionType == PluginASTAction::AddBeforeMainAction ||
199
0
         ActionType == PluginASTAction::AddAfterMainAction) &&
200
0
        P->ParseArgs(
201
0
            CI,
202
0
            CI.getFrontendOpts().PluginArgs[std::string(Plugin.getName())])) {
203
0
      std::unique_ptr<ASTConsumer> PluginConsumer = P->CreateASTConsumer(CI, InFile);
204
0
      if (ActionType == PluginASTAction::AddBeforeMainAction) {
205
0
        Consumers.push_back(std::move(PluginConsumer));
206
0
      } else {
207
0
        AfterConsumers.push_back(std::move(PluginConsumer));
208
0
      }
209
0
    }
210
0
  }
211
212
  // Add to Consumers the main consumer, then all the plugins that go after it
213
18.4E
  Consumers.push_back(std::move(Consumer));
214
18.4E
  for (auto &C : AfterConsumers) {
215
0
    Consumers.push_back(std::move(C));
216
0
  }
217
218
18.4E
  return std::make_unique<MultiplexConsumer>(std::move(Consumers));
219
18.4E
}
220
221
/// For preprocessed files, if the first line is the linemarker and specifies
222
/// the original source file name, use that name as the input file name.
223
/// Returns the location of the first token after the line marker directive.
224
///
225
/// \param CI The compiler instance.
226
/// \param InputFile Populated with the filename from the line marker.
227
/// \param IsModuleMap If \c true, add a line note corresponding to this line
228
///        directive. (We need to do this because the directive will not be
229
///        visited by the preprocessor.)
230
static SourceLocation ReadOriginalFileName(CompilerInstance &CI,
231
                                           std::string &InputFile,
232
179
                                           bool IsModuleMap = false) {
233
179
  auto &SourceMgr = CI.getSourceManager();
234
179
  auto MainFileID = SourceMgr.getMainFileID();
235
236
179
  auto MainFileBuf = SourceMgr.getBufferOrNone(MainFileID);
237
179
  if (!MainFileBuf)
238
0
    return SourceLocation();
239
240
179
  std::unique_ptr<Lexer> RawLexer(
241
179
      new Lexer(MainFileID, *MainFileBuf, SourceMgr, CI.getLangOpts()));
242
243
  // If the first line has the syntax of
244
  //
245
  // # NUM "FILENAME"
246
  //
247
  // we use FILENAME as the input file name.
248
179
  Token T;
249
179
  if (RawLexer->LexFromRawLexer(T) || 
T.getKind() != tok::hash177
)
250
139
    return SourceLocation();
251
40
  if (RawLexer->LexFromRawLexer(T) || T.isAtStartOfLine() ||
252
40
      T.getKind() != tok::numeric_constant)
253
4
    return SourceLocation();
254
255
36
  unsigned LineNo;
256
36
  SourceLocation LineNoLoc = T.getLocation();
257
36
  if (IsModuleMap) {
258
16
    llvm::SmallString<16> Buffer;
259
16
    if (Lexer::getSpelling(LineNoLoc, Buffer, SourceMgr, CI.getLangOpts())
260
16
            .getAsInteger(10, LineNo))
261
0
      return SourceLocation();
262
16
  }
263
264
36
  RawLexer->LexFromRawLexer(T);
265
36
  if (T.isAtStartOfLine() || T.getKind() != tok::string_literal)
266
0
    return SourceLocation();
267
268
36
  StringLiteralParser Literal(T, CI.getPreprocessor());
269
36
  if (Literal.hadError)
270
0
    return SourceLocation();
271
36
  RawLexer->LexFromRawLexer(T);
272
36
  if (T.isNot(tok::eof) && !T.isAtStartOfLine())
273
0
    return SourceLocation();
274
36
  InputFile = Literal.GetString().str();
275
276
36
  if (IsModuleMap)
277
16
    CI.getSourceManager().AddLineNote(
278
16
        LineNoLoc, LineNo, SourceMgr.getLineTableFilenameID(InputFile), false,
279
16
        false, SrcMgr::C_User_ModuleMap);
280
281
36
  return T.getLocation();
282
36
}
283
284
static SmallVectorImpl<char> &
285
66.1k
operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
286
66.1k
  Includes.append(RHS.begin(), RHS.end());
287
66.1k
  return Includes;
288
66.1k
}
289
290
static void addHeaderInclude(StringRef HeaderName,
291
                             SmallVectorImpl<char> &Includes,
292
                             const LangOptions &LangOpts,
293
17.9k
                             bool IsExternC) {
294
17.9k
  if (IsExternC && 
LangOpts.CPlusPlus11.5k
)
295
6.09k
    Includes += "extern \"C\" {\n";
296
17.9k
  if (LangOpts.ObjC)
297
6.10k
    Includes += "#import \"";
298
11.8k
  else
299
11.8k
    Includes += "#include \"";
300
301
17.9k
  Includes += HeaderName;
302
303
17.9k
  Includes += "\"\n";
304
17.9k
  if (IsExternC && 
LangOpts.CPlusPlus11.5k
)
305
6.09k
    Includes += "}\n";
306
17.9k
}
307
308
/// Collect the set of header includes needed to construct the given
309
/// module and update the TopHeaders file set of the module.
310
///
311
/// \param Module The module we're collecting includes from.
312
///
313
/// \param Includes Will be augmented with the set of \#includes or \#imports
314
/// needed to load all of the named headers.
315
static std::error_code collectModuleHeaderIncludes(
316
    const LangOptions &LangOpts, FileManager &FileMgr, DiagnosticsEngine &Diag,
317
15.7k
    ModuleMap &ModMap, clang::Module *Module, SmallVectorImpl<char> &Includes) {
318
  // Don't collect any headers for unavailable modules.
319
15.7k
  if (!Module->isAvailable())
320
407
    return std::error_code();
321
322
  // Resolve all lazy header directives to header files.
323
15.3k
  ModMap.resolveHeaderDirectives(Module);
324
325
  // If any headers are missing, we can't build this module. In most cases,
326
  // diagnostics for this should have already been produced; we only get here
327
  // if explicit stat information was provided.
328
  // FIXME: If the name resolves to a file with different stat information,
329
  // produce a better diagnostic.
330
15.3k
  if (!Module->MissingHeaders.empty()) {
331
1
    auto &MissingHeader = Module->MissingHeaders.front();
332
1
    Diag.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
333
1
      << MissingHeader.IsUmbrella << MissingHeader.FileName;
334
1
    return std::error_code();
335
1
  }
336
337
  // Add includes for each of these headers.
338
30.6k
  
for (auto HK : {Module::HK_Normal, Module::HK_Private})15.3k
{
339
30.6k
    for (Module::Header &H : Module->Headers[HK]) {
340
14.2k
      Module->addTopHeader(H.Entry);
341
      // Use the path as specified in the module map file. We'll look for this
342
      // file relative to the module build directory (the directory containing
343
      // the module map file) so this will find the same file that we found
344
      // while parsing the module map.
345
14.2k
      addHeaderInclude(H.PathRelativeToRootModuleDirectory, Includes, LangOpts,
346
14.2k
                       Module->IsExternC);
347
14.2k
    }
348
30.6k
  }
349
  // Note that Module->PrivateHeaders will not be a TopHeader.
350
351
15.3k
  if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
352
485
    Module->addTopHeader(UmbrellaHeader.Entry);
353
485
    if (Module->Parent)
354
      // Include the umbrella header for submodules.
355
222
      addHeaderInclude(UmbrellaHeader.PathRelativeToRootModuleDirectory,
356
222
                       Includes, LangOpts, Module->IsExternC);
357
14.8k
  } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
358
    // Add all of the headers we find in this subdirectory.
359
201
    std::error_code EC;
360
201
    SmallString<128> DirNative;
361
201
    llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
362
363
201
    llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
364
201
    SmallVector<std::pair<std::string, const FileEntry *>, 8> Headers;
365
201
    for (llvm::vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
366
3.52k
         Dir != End && 
!EC3.32k
;
Dir.increment(EC)3.32k
) {
367
      // Check whether this entry has an extension typically associated with
368
      // headers.
369
3.32k
      if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
370
3.32k
               .Cases(".h", ".H", ".hh", ".hpp", true)
371
3.32k
               .Default(false))
372
40
        continue;
373
374
3.28k
      auto Header = FileMgr.getFile(Dir->path());
375
      // FIXME: This shouldn't happen unless there is a file system race. Is
376
      // that worth diagnosing?
377
3.28k
      if (!Header)
378
1
        continue;
379
380
      // If this header is marked 'unavailable' in this module, don't include
381
      // it.
382
3.28k
      if (ModMap.isHeaderUnavailableInModule(*Header, Module))
383
8
        continue;
384
385
      // Compute the relative path from the directory to this file.
386
3.27k
      SmallVector<StringRef, 16> Components;
387
3.27k
      auto PathIt = llvm::sys::path::rbegin(Dir->path());
388
6.55k
      for (int I = 0; I != Dir.level() + 1; 
++I, ++PathIt3.27k
)
389
3.27k
        Components.push_back(*PathIt);
390
3.27k
      SmallString<128> RelativeHeader(
391
3.27k
          UmbrellaDir.PathRelativeToRootModuleDirectory);
392
6.55k
      for (auto It = Components.rbegin(), End = Components.rend(); It != End;
393
3.27k
           ++It)
394
3.27k
        llvm::sys::path::append(RelativeHeader, *It);
395
396
3.27k
      std::string RelName = RelativeHeader.c_str();
397
3.27k
      Headers.push_back(std::make_pair(RelName, *Header));
398
3.27k
    }
399
400
201
    if (EC)
401
0
      return EC;
402
403
    // Sort header paths and make the header inclusion order deterministic
404
    // across different OSs and filesystems.
405
201
    llvm::sort(Headers.begin(), Headers.end(), [](
406
201
      const std::pair<std::string, const FileEntry *> &LHS,
407
16.4k
      const std::pair<std::string, const FileEntry *> &RHS) {
408
16.4k
        return LHS.first < RHS.first;
409
16.4k
    });
410
3.27k
    for (auto &H : Headers) {
411
      // Include this header as part of the umbrella directory.
412
3.27k
      Module->addTopHeader(H.second);
413
3.27k
      addHeaderInclude(H.first, Includes, LangOpts, Module->IsExternC);
414
3.27k
    }
415
201
  }
416
417
  // Recurse into submodules.
418
15.3k
  for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
419
15.3k
                                      SubEnd = Module->submodule_end();
420
29.2k
       Sub != SubEnd; 
++Sub13.9k
)
421
13.9k
    if (std::error_code Err = collectModuleHeaderIncludes(
422
13.9k
            LangOpts, FileMgr, Diag, ModMap, *Sub, Includes))
423
0
      return Err;
424
425
15.3k
  return std::error_code();
426
15.3k
}
427
428
static bool loadModuleMapForModuleBuild(CompilerInstance &CI, bool IsSystem,
429
                                        bool IsPreprocessed,
430
                                        std::string &PresumedModuleMapFile,
431
1.90k
                                        unsigned &Offset) {
432
1.90k
  auto &SrcMgr = CI.getSourceManager();
433
1.90k
  HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
434
435
  // Map the current input to a file.
436
1.90k
  FileID ModuleMapID = SrcMgr.getMainFileID();
437
1.90k
  const FileEntry *ModuleMap = SrcMgr.getFileEntryForID(ModuleMapID);
438
439
  // If the module map is preprocessed, handle the initial line marker;
440
  // line directives are not part of the module map syntax in general.
441
1.90k
  Offset = 0;
442
1.90k
  if (IsPreprocessed) {
443
83
    SourceLocation EndOfLineMarker =
444
83
        ReadOriginalFileName(CI, PresumedModuleMapFile, /*IsModuleMap*/ true);
445
83
    if (EndOfLineMarker.isValid())
446
16
      Offset = CI.getSourceManager().getDecomposedLoc(EndOfLineMarker).second;
447
83
  }
448
449
  // Load the module map file.
450
1.90k
  if (HS.loadModuleMapFile(ModuleMap, IsSystem, ModuleMapID, &Offset,
451
1.90k
                           PresumedModuleMapFile))
452
0
    return true;
453
454
1.90k
  if (SrcMgr.getBufferOrFake(ModuleMapID).getBufferSize() == Offset)
455
1.82k
    Offset = 0;
456
457
1.90k
  return false;
458
1.90k
}
459
460
static Module *prepareToBuildModule(CompilerInstance &CI,
461
1.90k
                                    StringRef ModuleMapFilename) {
462
1.90k
  if (CI.getLangOpts().CurrentModule.empty()) {
463
0
    CI.getDiagnostics().Report(diag::err_missing_module_name);
464
465
    // FIXME: Eventually, we could consider asking whether there was just
466
    // a single module described in the module map, and use that as a
467
    // default. Then it would be fairly trivial to just "compile" a module
468
    // map with a single module (the common case).
469
0
    return nullptr;
470
0
  }
471
472
  // Dig out the module definition.
473
1.90k
  HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
474
1.90k
  Module *M = HS.lookupModule(CI.getLangOpts().CurrentModule,
475
1.90k
                              /*AllowSearch=*/true);
476
1.90k
  if (!M) {
477
2
    CI.getDiagnostics().Report(diag::err_missing_module)
478
2
      << CI.getLangOpts().CurrentModule << ModuleMapFilename;
479
480
2
    return nullptr;
481
2
  }
482
483
  // Check whether we can build this module at all.
484
1.90k
  if (Preprocessor::checkModuleIsAvailable(CI.getLangOpts(), CI.getTarget(),
485
1.90k
                                           CI.getDiagnostics(), M))
486
3
    return nullptr;
487
488
  // Inform the preprocessor that includes from within the input buffer should
489
  // be resolved relative to the build directory of the module map file.
490
1.90k
  CI.getPreprocessor().setMainFileDir(M->Directory);
491
492
  // If the module was inferred from a different module map (via an expanded
493
  // umbrella module definition), track that fact.
494
  // FIXME: It would be preferable to fill this in as part of processing
495
  // the module map, rather than adding it after the fact.
496
1.90k
  StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
497
1.90k
  if (!OriginalModuleMapName.empty()) {
498
1.59k
    auto OriginalModuleMap =
499
1.59k
        CI.getFileManager().getFile(OriginalModuleMapName,
500
1.59k
                                    /*openFile*/ true);
501
1.59k
    if (!OriginalModuleMap) {
502
0
      CI.getDiagnostics().Report(diag::err_module_map_not_found)
503
0
        << OriginalModuleMapName;
504
0
      return nullptr;
505
0
    }
506
1.59k
    if (*OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
507
1.59k
                                 CI.getSourceManager().getMainFileID())) {
508
108
      M->IsInferred = true;
509
108
      CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()
510
108
        .setInferredModuleAllowedBy(M, *OriginalModuleMap);
511
108
    }
512
1.59k
  }
513
514
  // If we're being run from the command-line, the module build stack will not
515
  // have been filled in yet, so complete it now in order to allow us to detect
516
  // module cycles.
517
1.90k
  SourceManager &SourceMgr = CI.getSourceManager();
518
1.90k
  if (SourceMgr.getModuleBuildStack().empty())
519
235
    SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
520
235
                                   FullSourceLoc(SourceLocation(), SourceMgr));
521
1.90k
  return M;
522
1.90k
}
523
524
/// Compute the input buffer that should be used to build the specified module.
525
static std::unique_ptr<llvm::MemoryBuffer>
526
1.81k
getInputBufferForModule(CompilerInstance &CI, Module *M) {
527
1.81k
  FileManager &FileMgr = CI.getFileManager();
528
529
  // Collect the set of #includes we need to build the module.
530
1.81k
  SmallString<256> HeaderContents;
531
1.81k
  std::error_code Err = std::error_code();
532
1.81k
  if (Module::Header UmbrellaHeader = M->getUmbrellaHeader())
533
263
    addHeaderInclude(UmbrellaHeader.PathRelativeToRootModuleDirectory,
534
263
                     HeaderContents, CI.getLangOpts(), M->IsExternC);
535
1.81k
  Err = collectModuleHeaderIncludes(
536
1.81k
      CI.getLangOpts(), FileMgr, CI.getDiagnostics(),
537
1.81k
      CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), M,
538
1.81k
      HeaderContents);
539
540
1.81k
  if (Err) {
541
0
    CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
542
0
      << M->getFullModuleName() << Err.message();
543
0
    return nullptr;
544
0
  }
545
546
1.81k
  return llvm::MemoryBuffer::getMemBufferCopy(
547
1.81k
      HeaderContents, Module::getModuleInputBufferName());
548
1.81k
}
549
550
bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
551
71.3k
                                     const FrontendInputFile &RealInput) {
552
71.3k
  FrontendInputFile Input(RealInput);
553
71.3k
  assert(!Instance && "Already processing a source file!");
554
0
  assert(!Input.isEmpty() && "Unexpected empty filename!");
555
0
  setCurrentInput(Input);
556
71.3k
  setCompilerInstance(&CI);
557
558
71.3k
  bool HasBegunSourceFile = false;
559
71.3k
  bool ReplayASTFile = Input.getKind().getFormat() == InputKind::Precompiled &&
560
71.3k
                       
usesPreprocessorOnly()51
;
561
71.3k
  if (!BeginInvocation(CI))
562
12
    goto failure;
563
564
  // If we're replaying the build of an AST file, import it and set up
565
  // the initial state from its build.
566
71.3k
  if (ReplayASTFile) {
567
15
    IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
568
569
    // The AST unit populates its own diagnostics engine rather than ours.
570
15
    IntrusiveRefCntPtr<DiagnosticsEngine> ASTDiags(
571
15
        new DiagnosticsEngine(Diags->getDiagnosticIDs(),
572
15
                              &Diags->getDiagnosticOptions()));
573
15
    ASTDiags->setClient(Diags->getClient(), /*OwnsClient*/false);
574
575
    // FIXME: What if the input is a memory buffer?
576
15
    StringRef InputFile = Input.getFile();
577
578
15
    std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
579
15
        std::string(InputFile), CI.getPCHContainerReader(),
580
15
        ASTUnit::LoadPreprocessorOnly, ASTDiags, CI.getFileSystemOpts(),
581
15
        CI.getCodeGenOpts().DebugTypeExtRefs);
582
15
    if (!AST)
583
0
      goto failure;
584
585
    // Options relating to how we treat the input (but not what we do with it)
586
    // are inherited from the AST unit.
587
15
    CI.getHeaderSearchOpts() = AST->getHeaderSearchOpts();
588
15
    CI.getPreprocessorOpts() = AST->getPreprocessorOpts();
589
15
    CI.getLangOpts() = AST->getLangOpts();
590
591
    // Set the shared objects, these are reset when we finish processing the
592
    // file, otherwise the CompilerInstance will happily destroy them.
593
15
    CI.setFileManager(&AST->getFileManager());
594
15
    CI.createSourceManager(CI.getFileManager());
595
15
    CI.getSourceManager().initializeForReplay(AST->getSourceManager());
596
597
    // Preload all the module files loaded transitively by the AST unit. Also
598
    // load all module map files that were parsed as part of building the AST
599
    // unit.
600
15
    if (auto ASTReader = AST->getASTReader()) {
601
15
      auto &MM = ASTReader->getModuleManager();
602
15
      auto &PrimaryModule = MM.getPrimaryModule();
603
604
15
      for (serialization::ModuleFile &MF : MM)
605
25
        if (&MF != &PrimaryModule)
606
10
          CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName);
607
608
15
      ASTReader->visitTopLevelModuleMaps(
609
15
          PrimaryModule, [&](const FileEntry *FE) {
610
14
            CI.getFrontendOpts().ModuleMapFiles.push_back(
611
14
                std::string(FE->getName()));
612
14
          });
613
15
    }
614
615
    // Set up the input file for replay purposes.
616
15
    auto Kind = AST->getInputKind();
617
15
    if (Kind.getFormat() == InputKind::ModuleMap) {
618
13
      Module *ASTModule =
619
13
          AST->getPreprocessor().getHeaderSearchInfo().lookupModule(
620
13
              AST->getLangOpts().CurrentModule, /*AllowSearch*/ false);
621
13
      assert(ASTModule && "module file does not define its own module");
622
0
      Input = FrontendInputFile(ASTModule->PresumedModuleMapFile, Kind);
623
13
    } else {
624
2
      auto &OldSM = AST->getSourceManager();
625
2
      FileID ID = OldSM.getMainFileID();
626
2
      if (auto *File = OldSM.getFileEntryForID(ID))
627
0
        Input = FrontendInputFile(File->getName(), Kind);
628
2
      else
629
2
        Input = FrontendInputFile(OldSM.getBufferOrFake(ID), Kind);
630
2
    }
631
0
    setCurrentInput(Input, std::move(AST));
632
15
  }
633
634
  // AST files follow a very different path, since they share objects via the
635
  // AST unit.
636
71.3k
  if (Input.getKind().getFormat() == InputKind::Precompiled) {
637
36
    assert(!usesPreprocessorOnly() && "this case was handled above");
638
0
    assert(hasASTFileSupport() &&
639
36
           "This action does not have AST file support!");
640
641
0
    IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
642
643
    // FIXME: What if the input is a memory buffer?
644
36
    StringRef InputFile = Input.getFile();
645
646
36
    std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
647
36
        std::string(InputFile), CI.getPCHContainerReader(),
648
36
        ASTUnit::LoadEverything, Diags, CI.getFileSystemOpts(),
649
36
        CI.getCodeGenOpts().DebugTypeExtRefs);
650
651
36
    if (!AST)
652
0
      goto failure;
653
654
    // Inform the diagnostic client we are processing a source file.
655
36
    CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
656
36
    HasBegunSourceFile = true;
657
658
    // Set the shared objects, these are reset when we finish processing the
659
    // file, otherwise the CompilerInstance will happily destroy them.
660
36
    CI.setFileManager(&AST->getFileManager());
661
36
    CI.setSourceManager(&AST->getSourceManager());
662
36
    CI.setPreprocessor(AST->getPreprocessorPtr());
663
36
    Preprocessor &PP = CI.getPreprocessor();
664
36
    PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
665
36
                                           PP.getLangOpts());
666
36
    CI.setASTContext(&AST->getASTContext());
667
668
36
    setCurrentInput(Input, std::move(AST));
669
670
    // Initialize the action.
671
36
    if (!BeginSourceFileAction(CI))
672
0
      goto failure;
673
674
    // Create the AST consumer.
675
36
    CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
676
36
    if (!CI.hasASTConsumer())
677
0
      goto failure;
678
679
36
    return true;
680
36
  }
681
682
  // Set up the file and source managers, if needed.
683
71.3k
  if (!CI.hasFileManager()) {
684
39.9k
    if (!CI.createFileManager()) {
685
0
      goto failure;
686
0
    }
687
39.9k
  }
688
71.3k
  if (!CI.hasSourceManager())
689
41.2k
    CI.createSourceManager(CI.getFileManager());
690
691
  // Set up embedding for any specified files. Do this before we load any
692
  // source files, including the primary module map for the compilation.
693
71.3k
  for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
694
3
    if (auto FE = CI.getFileManager().getFile(F, /*openFile*/true))
695
2
      CI.getSourceManager().setFileIsTransient(*FE);
696
1
    else
697
1
      CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
698
3
  }
699
71.3k
  if (CI.getFrontendOpts().ModulesEmbedAllFiles)
700
10
    CI.getSourceManager().setAllFilesAreTransient(true);
701
702
  // IR files bypass the rest of initialization.
703
71.3k
  if (Input.getKind().getLanguage() == Language::LLVM_IR) {
704
122
    assert(hasIRSupport() &&
705
122
           "This action does not have IR file support!");
706
707
    // Inform the diagnostic client we are processing a source file.
708
0
    CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
709
122
    HasBegunSourceFile = true;
710
711
    // Initialize the action.
712
122
    if (!BeginSourceFileAction(CI))
713
0
      goto failure;
714
715
    // Initialize the main file entry.
716
122
    if (!CI.InitializeSourceManager(CurrentInput))
717
0
      goto failure;
718
719
122
    return true;
720
122
  }
721
722
  // If the implicit PCH include is actually a directory, rather than
723
  // a single file, search for a suitable PCH file in that directory.
724
71.2k
  if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
725
3.61k
    FileManager &FileMgr = CI.getFileManager();
726
3.61k
    PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
727
3.61k
    StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
728
3.61k
    std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
729
3.61k
    if (auto PCHDir = FileMgr.getDirectory(PCHInclude)) {
730
6
      std::error_code EC;
731
6
      SmallString<128> DirNative;
732
6
      llvm::sys::path::native((*PCHDir)->getName(), DirNative);
733
6
      bool Found = false;
734
6
      llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
735
6
      for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
736
6
                                         DirEnd;
737
16
           Dir != DirEnd && 
!EC13
;
Dir.increment(EC)10
) {
738
        // Check whether this is an acceptable AST file.
739
13
        if (ASTReader::isAcceptableASTFile(
740
13
                Dir->path(), FileMgr, CI.getPCHContainerReader(),
741
13
                CI.getLangOpts(), CI.getTargetOpts(), CI.getPreprocessorOpts(),
742
13
                SpecificModuleCachePath)) {
743
3
          PPOpts.ImplicitPCHInclude = std::string(Dir->path());
744
3
          Found = true;
745
3
          break;
746
3
        }
747
13
      }
748
749
6
      if (!Found) {
750
3
        CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
751
3
        goto failure;
752
3
      }
753
6
    }
754
3.61k
  }
755
756
  // Set up the preprocessor if needed. When parsing model files the
757
  // preprocessor of the original source is reused.
758
71.2k
  if (!isModelParsingAction())
759
71.1k
    CI.createPreprocessor(getTranslationUnitKind());
760
761
  // Inform the diagnostic client we are processing a source file.
762
71.2k
  CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
763
71.2k
                                           &CI.getPreprocessor());
764
71.2k
  HasBegunSourceFile = true;
765
766
  // Initialize the main file entry.
767
71.2k
  if (!CI.InitializeSourceManager(Input))
768
4
    goto failure;
769
770
  // For module map files, we first parse the module map and synthesize a
771
  // "<module-includes>" buffer before more conventional processing.
772
71.2k
  if (Input.getKind().getFormat() == InputKind::ModuleMap) {
773
1.90k
    CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
774
775
1.90k
    std::string PresumedModuleMapFile;
776
1.90k
    unsigned OffsetToContents;
777
1.90k
    if (loadModuleMapForModuleBuild(CI, Input.isSystem(),
778
1.90k
                                    Input.isPreprocessed(),
779
1.90k
                                    PresumedModuleMapFile, OffsetToContents))
780
0
      goto failure;
781
782
1.90k
    auto *CurrentModule = prepareToBuildModule(CI, Input.getFile());
783
1.90k
    if (!CurrentModule)
784
5
      goto failure;
785
786
1.90k
    CurrentModule->PresumedModuleMapFile = PresumedModuleMapFile;
787
788
1.90k
    if (OffsetToContents)
789
      // If the module contents are in the same file, skip to them.
790
88
      CI.getPreprocessor().setSkipMainFilePreamble(OffsetToContents, true);
791
1.81k
    else {
792
      // Otherwise, convert the module description to a suitable input buffer.
793
1.81k
      auto Buffer = getInputBufferForModule(CI, CurrentModule);
794
1.81k
      if (!Buffer)
795
0
        goto failure;
796
797
      // Reinitialize the main file entry to refer to the new input.
798
1.81k
      auto Kind = CurrentModule->IsSystem ? 
SrcMgr::C_System323
:
SrcMgr::C_User1.49k
;
799
1.81k
      auto &SourceMgr = CI.getSourceManager();
800
1.81k
      auto BufferID = SourceMgr.createFileID(std::move(Buffer), Kind);
801
1.81k
      assert(BufferID.isValid() && "couldn't create module buffer ID");
802
0
      SourceMgr.setMainFileID(BufferID);
803
1.81k
    }
804
1.90k
  }
805
806
  // Initialize the action.
807
71.1k
  if (!BeginSourceFileAction(CI))
808
1
    goto failure;
809
810
  // If we were asked to load any module map files, do so now.
811
71.1k
  for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
812
276
    if (auto File = CI.getFileManager().getFile(Filename))
813
275
      CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
814
275
          *File, /*IsSystem*/false);
815
1
    else
816
1
      CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
817
276
  }
818
819
  // Add a module declaration scope so that modules from -fmodule-map-file
820
  // arguments may shadow modules found implicitly in search paths.
821
71.1k
  CI.getPreprocessor()
822
71.1k
      .getHeaderSearchInfo()
823
71.1k
      .getModuleMap()
824
71.1k
      .finishModuleDeclarationScope();
825
826
  // Create the AST context and consumer unless this is a preprocessor only
827
  // action.
828
71.1k
  if (!usesPreprocessorOnly()) {
829
    // Parsing a model file should reuse the existing ASTContext.
830
68.9k
    if (!isModelParsingAction())
831
68.9k
      CI.createASTContext();
832
833
    // For preprocessed files, check if the first line specifies the original
834
    // source file name with a linemarker.
835
68.9k
    std::string PresumedInputFile = std::string(getCurrentFileOrBufferName());
836
68.9k
    if (Input.isPreprocessed())
837
96
      ReadOriginalFileName(CI, PresumedInputFile);
838
839
68.9k
    std::unique_ptr<ASTConsumer> Consumer =
840
68.9k
        CreateWrappedASTConsumer(CI, PresumedInputFile);
841
68.9k
    if (!Consumer)
842
4
      goto failure;
843
844
    // FIXME: should not overwrite ASTMutationListener when parsing model files?
845
68.9k
    if (!isModelParsingAction())
846
68.9k
      CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
847
848
68.9k
    if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
849
      // Convert headers to PCH and chain them.
850
27
      IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
851
27
      source = createChainedIncludesSource(CI, FinalReader);
852
27
      if (!source)
853
0
        goto failure;
854
27
      CI.setASTReader(static_cast<ASTReader *>(FinalReader.get()));
855
27
      CI.getASTContext().setExternalSource(source);
856
68.9k
    } else if (CI.getLangOpts().Modules ||
857
68.9k
               
!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()60.2k
) {
858
      // Use PCM or PCH.
859
12.2k
      assert(hasPCHSupport() && "This action does not have PCH support!");
860
0
      ASTDeserializationListener *DeserialListener =
861
12.2k
          Consumer->GetASTDeserializationListener();
862
12.2k
      bool DeleteDeserialListener = false;
863
12.2k
      if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls) {
864
0
        DeserialListener = new DeserializedDeclsDumper(DeserialListener,
865
0
                                                       DeleteDeserialListener);
866
0
        DeleteDeserialListener = true;
867
0
      }
868
12.2k
      if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty()) {
869
106
        DeserialListener = new DeserializedDeclsChecker(
870
106
            CI.getASTContext(),
871
106
            CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
872
106
            DeserialListener, DeleteDeserialListener);
873
106
        DeleteDeserialListener = true;
874
106
      }
875
12.2k
      if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
876
3.60k
        CI.createPCHExternalASTSource(
877
3.60k
            CI.getPreprocessorOpts().ImplicitPCHInclude,
878
3.60k
            CI.getPreprocessorOpts().DisablePCHOrModuleValidation,
879
3.60k
            CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
880
3.60k
            DeserialListener, DeleteDeserialListener);
881
3.60k
        if (!CI.getASTContext().getExternalSource())
882
28
          goto failure;
883
3.60k
      }
884
      // If modules are enabled, create the AST reader before creating
885
      // any builtins, so that all declarations know that they might be
886
      // extended by an external source.
887
12.1k
      if (CI.getLangOpts().Modules || 
!CI.hasASTContext()3.48k
||
888
12.1k
          
!CI.getASTContext().getExternalSource()3.48k
) {
889
8.71k
        CI.createASTReader();
890
8.71k
        CI.getASTReader()->setDeserializationListener(DeserialListener,
891
8.71k
                                                      DeleteDeserialListener);
892
8.71k
      }
893
12.1k
    }
894
895
68.9k
    CI.setASTConsumer(std::move(Consumer));
896
68.9k
    if (!CI.hasASTConsumer())
897
0
      goto failure;
898
68.9k
  }
899
900
  // Initialize built-in info as long as we aren't using an external AST
901
  // source.
902
71.1k
  if (CI.getLangOpts().Modules || 
!CI.hasASTContext()62.3k
||
903
71.1k
      
!CI.getASTContext().getExternalSource()60.2k
) {
904
67.6k
    Preprocessor &PP = CI.getPreprocessor();
905
67.6k
    PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
906
67.6k
                                           PP.getLangOpts());
907
67.6k
  } else {
908
    // FIXME: If this is a problem, recover from it by creating a multiplex
909
    // source.
910
3.50k
    assert((!CI.getLangOpts().Modules || CI.getASTReader()) &&
911
3.50k
           "modules enabled but created an external source that "
912
3.50k
           "doesn't support modules");
913
3.50k
  }
914
915
  // If we were asked to load any module files, do so now.
916
0
  for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
917
424
    if (!CI.loadModuleFile(ModuleFile))
918
11
      goto failure;
919
920
  // If there is a layout overrides file, attach an external AST source that
921
  // provides the layouts from that file.
922
71.1k
  if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
923
71.1k
      
CI.hasASTContext()6
&&
!CI.getASTContext().getExternalSource()6
) {
924
6
    IntrusiveRefCntPtr<ExternalASTSource>
925
6
      Override(new LayoutOverrideSource(
926
6
                     CI.getFrontendOpts().OverrideRecordLayoutsFile));
927
6
    CI.getASTContext().setExternalSource(Override);
928
6
  }
929
930
71.1k
  return true;
931
932
  // If we failed, reset state since the client will not end up calling the
933
  // matching EndSourceFile().
934
68
failure:
935
68
  if (HasBegunSourceFile)
936
53
    CI.getDiagnosticClient().EndSourceFile();
937
68
  CI.clearOutputFiles(/*EraseFiles=*/true);
938
68
  CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
939
68
  setCurrentInput(FrontendInputFile());
940
68
  setCompilerInstance(nullptr);
941
68
  return false;
942
71.1k
}
943
944
69.9k
llvm::Error FrontendAction::Execute() {
945
69.9k
  CompilerInstance &CI = getCompilerInstance();
946
947
69.9k
  if (CI.hasFrontendTimer()) {
948
18
    llvm::TimeRegion Timer(CI.getFrontendTimer());
949
18
    ExecuteAction();
950
18
  }
951
69.9k
  else ExecuteAction();
952
953
  // If we are supposed to rebuild the global module index, do so now unless
954
  // there were any module-build failures.
955
69.9k
  if (CI.shouldBuildGlobalModuleIndex() && 
CI.hasFileManager()853
&&
956
69.9k
      
CI.hasPreprocessor()853
) {
957
853
    StringRef Cache =
958
853
        CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
959
853
    if (!Cache.empty()) {
960
774
      if (llvm::Error Err = GlobalModuleIndex::writeIndex(
961
774
              CI.getFileManager(), CI.getPCHContainerReader(), Cache)) {
962
        // FIXME this drops the error on the floor, but
963
        // Index/pch-from-libclang.c seems to rely on dropping at least some of
964
        // the error conditions!
965
26
        consumeError(std::move(Err));
966
26
      }
967
774
    }
968
853
  }
969
970
69.9k
  return llvm::Error::success();
971
69.9k
}
972
973
69.8k
void FrontendAction::EndSourceFile() {
974
69.8k
  CompilerInstance &CI = getCompilerInstance();
975
976
  // Inform the diagnostic client we are done with this source file.
977
69.8k
  CI.getDiagnosticClient().EndSourceFile();
978
979
  // Inform the preprocessor we are done.
980
69.8k
  if (CI.hasPreprocessor())
981
69.7k
    CI.getPreprocessor().EndSourceFile();
982
983
  // Finalize the action.
984
69.8k
  EndSourceFileAction();
985
986
  // Sema references the ast consumer, so reset sema first.
987
  //
988
  // FIXME: There is more per-file stuff we could just drop here?
989
69.8k
  bool DisableFree = CI.getFrontendOpts().DisableFree;
990
69.8k
  if (DisableFree) {
991
5.74k
    CI.resetAndLeakSema();
992
5.74k
    CI.resetAndLeakASTContext();
993
5.74k
    llvm::BuryPointer(CI.takeASTConsumer().get());
994
64.1k
  } else {
995
64.1k
    CI.setSema(nullptr);
996
64.1k
    CI.setASTContext(nullptr);
997
64.1k
    CI.setASTConsumer(nullptr);
998
64.1k
  }
999
1000
69.8k
  if (CI.getFrontendOpts().ShowStats) {
1001
3
    llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
1002
3
    CI.getPreprocessor().PrintStats();
1003
3
    CI.getPreprocessor().getIdentifierTable().PrintStats();
1004
3
    CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
1005
3
    CI.getSourceManager().PrintStats();
1006
3
    llvm::errs() << "\n";
1007
3
  }
1008
1009
  // Cleanup the output streams, and erase the output files if instructed by the
1010
  // FrontendAction.
1011
69.8k
  CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
1012
1013
69.8k
  if (isCurrentFileAST()) {
1014
51
    if (DisableFree) {
1015
9
      CI.resetAndLeakPreprocessor();
1016
9
      CI.resetAndLeakSourceManager();
1017
9
      CI.resetAndLeakFileManager();
1018
9
      llvm::BuryPointer(std::move(CurrentASTUnit));
1019
42
    } else {
1020
42
      CI.setPreprocessor(nullptr);
1021
42
      CI.setSourceManager(nullptr);
1022
42
      CI.setFileManager(nullptr);
1023
42
    }
1024
51
  }
1025
1026
69.8k
  setCompilerInstance(nullptr);
1027
69.8k
  setCurrentInput(FrontendInputFile());
1028
69.8k
  CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
1029
69.8k
}
1030
1031
69.7k
bool FrontendAction::shouldEraseOutputFiles() {
1032
69.7k
  return getCompilerInstance().getDiagnostics().hasErrorOccurred();
1033
69.7k
}
1034
1035
//===----------------------------------------------------------------------===//
1036
// Utility Actions
1037
//===----------------------------------------------------------------------===//
1038
1039
67.4k
void ASTFrontendAction::ExecuteAction() {
1040
67.4k
  CompilerInstance &CI = getCompilerInstance();
1041
67.4k
  if (!CI.hasPreprocessor())
1042
0
    return;
1043
1044
  // FIXME: Move the truncation aspect of this into Sema, we delayed this till
1045
  // here so the source manager would be initialized.
1046
67.4k
  if (hasCodeCompletionSupport() &&
1047
67.4k
      
!CI.getFrontendOpts().CodeCompletionAt.FileName.empty()12.3k
)
1048
1.18k
    CI.createCodeCompletionConsumer();
1049
1050
  // Use a code completion consumer?
1051
67.4k
  CodeCompleteConsumer *CompletionConsumer = nullptr;
1052
67.4k
  if (CI.hasCodeCompletionConsumer())
1053
1.18k
    CompletionConsumer = &CI.getCodeCompletionConsumer();
1054
1055
67.4k
  if (!CI.hasSema())
1056
67.3k
    CI.createSema(getTranslationUnitKind(), CompletionConsumer);
1057
1058
67.4k
  ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
1059
67.4k
           CI.getFrontendOpts().SkipFunctionBodies);
1060
67.4k
}
1061
1062
0
void PluginASTAction::anchor() { }
1063
1064
std::unique_ptr<ASTConsumer>
1065
PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
1066
0
                                              StringRef InFile) {
1067
0
  llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
1068
0
}
1069
1070
59
bool WrapperFrontendAction::PrepareToExecuteAction(CompilerInstance &CI) {
1071
59
  return WrappedAction->PrepareToExecuteAction(CI);
1072
59
}
1073
std::unique_ptr<ASTConsumer>
1074
WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
1075
44
                                         StringRef InFile) {
1076
44
  return WrappedAction->CreateASTConsumer(CI, InFile);
1077
44
}
1078
8
bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
1079
8
  return WrappedAction->BeginInvocation(CI);
1080
8
}
1081
46
bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI) {
1082
46
  WrappedAction->setCurrentInput(getCurrentInput());
1083
46
  WrappedAction->setCompilerInstance(&CI);
1084
46
  auto Ret = WrappedAction->BeginSourceFileAction(CI);
1085
  // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
1086
46
  setCurrentInput(WrappedAction->getCurrentInput());
1087
46
  return Ret;
1088
46
}
1089
38
void WrapperFrontendAction::ExecuteAction() {
1090
38
  WrappedAction->ExecuteAction();
1091
38
}
1092
46
void WrapperFrontendAction::EndSourceFile() { WrappedAction->EndSourceFile(); }
1093
0
void WrapperFrontendAction::EndSourceFileAction() {
1094
0
  WrappedAction->EndSourceFileAction();
1095
0
}
1096
0
bool WrapperFrontendAction::shouldEraseOutputFiles() {
1097
0
  return WrappedAction->shouldEraseOutputFiles();
1098
0
}
1099
1100
46
bool WrapperFrontendAction::usesPreprocessorOnly() const {
1101
46
  return WrappedAction->usesPreprocessorOnly();
1102
46
}
1103
39
TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
1104
39
  return WrappedAction->getTranslationUnitKind();
1105
39
}
1106
4
bool WrapperFrontendAction::hasPCHSupport() const {
1107
4
  return WrappedAction->hasPCHSupport();
1108
4
}
1109
0
bool WrapperFrontendAction::hasASTFileSupport() const {
1110
0
  return WrappedAction->hasASTFileSupport();
1111
0
}
1112
0
bool WrapperFrontendAction::hasIRSupport() const {
1113
0
  return WrappedAction->hasIRSupport();
1114
0
}
1115
8
bool WrapperFrontendAction::hasCodeCompletionSupport() const {
1116
8
  return WrappedAction->hasCodeCompletionSupport();
1117
8
}
1118
1119
WrapperFrontendAction::WrapperFrontendAction(
1120
    std::unique_ptr<FrontendAction> WrappedAction)
1121
59
  : WrappedAction(std::move(WrappedAction)) {}
1122