Coverage Report

Created: 2019-07-24 05:18

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