Coverage Report

Created: 2020-11-24 06:42

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Frontend/CompilerInstance.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CompilerInstance.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/CompilerInstance.h"
10
#include "clang/AST/ASTConsumer.h"
11
#include "clang/AST/ASTContext.h"
12
#include "clang/AST/Decl.h"
13
#include "clang/Basic/CharInfo.h"
14
#include "clang/Basic/Diagnostic.h"
15
#include "clang/Basic/FileManager.h"
16
#include "clang/Basic/LangStandard.h"
17
#include "clang/Basic/SourceManager.h"
18
#include "clang/Basic/Stack.h"
19
#include "clang/Basic/TargetInfo.h"
20
#include "clang/Basic/Version.h"
21
#include "clang/Config/config.h"
22
#include "clang/Frontend/ChainedDiagnosticConsumer.h"
23
#include "clang/Frontend/FrontendAction.h"
24
#include "clang/Frontend/FrontendActions.h"
25
#include "clang/Frontend/FrontendDiagnostic.h"
26
#include "clang/Frontend/LogDiagnosticPrinter.h"
27
#include "clang/Frontend/SerializedDiagnosticPrinter.h"
28
#include "clang/Frontend/TextDiagnosticPrinter.h"
29
#include "clang/Frontend/Utils.h"
30
#include "clang/Frontend/VerifyDiagnosticConsumer.h"
31
#include "clang/Lex/HeaderSearch.h"
32
#include "clang/Lex/Preprocessor.h"
33
#include "clang/Lex/PreprocessorOptions.h"
34
#include "clang/Sema/CodeCompleteConsumer.h"
35
#include "clang/Sema/Sema.h"
36
#include "clang/Serialization/ASTReader.h"
37
#include "clang/Serialization/GlobalModuleIndex.h"
38
#include "clang/Serialization/InMemoryModuleCache.h"
39
#include "llvm/ADT/Statistic.h"
40
#include "llvm/Support/BuryPointer.h"
41
#include "llvm/Support/CrashRecoveryContext.h"
42
#include "llvm/Support/Errc.h"
43
#include "llvm/Support/FileSystem.h"
44
#include "llvm/Support/Host.h"
45
#include "llvm/Support/LockFileManager.h"
46
#include "llvm/Support/MemoryBuffer.h"
47
#include "llvm/Support/Path.h"
48
#include "llvm/Support/Program.h"
49
#include "llvm/Support/Signals.h"
50
#include "llvm/Support/TimeProfiler.h"
51
#include "llvm/Support/Timer.h"
52
#include "llvm/Support/raw_ostream.h"
53
#include <time.h>
54
#include <utility>
55
56
using namespace clang;
57
58
CompilerInstance::CompilerInstance(
59
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
60
    InMemoryModuleCache *SharedModuleCache)
61
    : ModuleLoader(/* BuildingModule = */ SharedModuleCache),
62
      Invocation(new CompilerInvocation()),
63
      ModuleCache(SharedModuleCache ? SharedModuleCache
64
                                    : new InMemoryModuleCache),
65
83.3k
      ThePCHContainerOperations(std::move(PCHContainerOps)) {}
66
67
74.8k
CompilerInstance::~CompilerInstance() {
68
74.8k
  assert(OutputFiles.empty() && "Still output files in flight?");
69
74.8k
}
70
71
void CompilerInstance::setInvocation(
72
30.5k
    std::shared_ptr<CompilerInvocation> Value) {
73
30.5k
  Invocation = std::move(Value);
74
30.5k
}
75
76
68.4k
bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
77
68.4k
  return (BuildGlobalModuleIndex ||
78
67.7k
          (TheASTReader && 
TheASTReader->isGlobalIndexUnavailable()10.2k
&&
79
597
           getFrontendOpts().GenerateGlobalModuleIndex)) &&
80
853
         !ModuleBuildFailed;
81
68.4k
}
82
83
12.2k
void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
84
12.2k
  Diagnostics = Value;
85
12.2k
}
86
87
1
void CompilerInstance::setVerboseOutputStream(raw_ostream &Value) {
88
1
  OwnedVerboseOutputStream.release();
89
1
  VerboseOutputStream = &Value;
90
1
}
91
92
1
void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) {
93
1
  OwnedVerboseOutputStream.swap(Value);
94
1
  VerboseOutputStream = OwnedVerboseOutputStream.get();
95
1
}
96
97
83.2k
void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; }
98
133
void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; }
99
100
0
llvm::vfs::FileSystem &CompilerInstance::getVirtualFileSystem() const {
101
0
  return getFileManager().getVirtualFileSystem();
102
0
}
103
104
43.8k
void CompilerInstance::setFileManager(FileManager *Value) {
105
43.8k
  FileMgr = Value;
106
43.8k
}
107
108
18.8k
void CompilerInstance::setSourceManager(SourceManager *Value) {
109
18.8k
  SourceMgr = Value;
110
18.8k
}
111
112
76
void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
113
76
  PP = std::move(Value);
114
76
}
115
116
138k
void CompilerInstance::setASTContext(ASTContext *Value) {
117
138k
  Context = Value;
118
119
138k
  if (Context && 
Consumer78.6k
)
120
0
    getASTConsumer().Initialize(getASTContext());
121
138k
}
122
123
86.3k
void CompilerInstance::setSema(Sema *S) {
124
86.3k
  TheSema.reset(S);
125
86.3k
}
126
127
138k
void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
128
138k
  Consumer = std::move(Value);
129
130
138k
  if (Context && 
Consumer77.8k
)
131
77.8k
    getASTConsumer().Initialize(getASTContext());
132
138k
}
133
134
1.15k
void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
135
1.15k
  CompletionConsumer.reset(Value);
136
1.15k
}
137
138
16.0k
std::unique_ptr<Sema> CompilerInstance::takeSema() {
139
16.0k
  return std::move(TheSema);
140
16.0k
}
141
142
27.5k
IntrusiveRefCntPtr<ASTReader> CompilerInstance::getASTReader() const {
143
27.5k
  return TheASTReader;
144
27.5k
}
145
51
void CompilerInstance::setASTReader(IntrusiveRefCntPtr<ASTReader> Reader) {
146
51
  assert(ModuleCache.get() == &Reader->getModuleManager().getModuleCache() &&
147
51
         "Expected ASTReader to use the same PCM cache");
148
51
  TheASTReader = std::move(Reader);
149
51
}
150
151
std::shared_ptr<ModuleDependencyCollector>
152
1.66k
CompilerInstance::getModuleDepCollector() const {
153
1.66k
  return ModuleDepCollector;
154
1.66k
}
155
156
void CompilerInstance::setModuleDepCollector(
157
1.68k
    std::shared_ptr<ModuleDependencyCollector> Collector) {
158
1.68k
  ModuleDepCollector = std::move(Collector);
159
1.68k
}
160
161
static void collectHeaderMaps(const HeaderSearch &HS,
162
54
                              std::shared_ptr<ModuleDependencyCollector> MDC) {
163
54
  SmallVector<std::string, 4> HeaderMapFileNames;
164
54
  HS.getHeaderMapFileNames(HeaderMapFileNames);
165
54
  for (auto &Name : HeaderMapFileNames)
166
1
    MDC->addFile(Name);
167
54
}
168
169
static void collectIncludePCH(CompilerInstance &CI,
170
54
                              std::shared_ptr<ModuleDependencyCollector> MDC) {
171
54
  const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
172
54
  if (PPOpts.ImplicitPCHInclude.empty())
173
53
    return;
174
175
1
  StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
176
1
  FileManager &FileMgr = CI.getFileManager();
177
1
  auto PCHDir = FileMgr.getDirectory(PCHInclude);
178
1
  if (!PCHDir) {
179
1
    MDC->addFile(PCHInclude);
180
1
    return;
181
1
  }
182
183
0
  std::error_code EC;
184
0
  SmallString<128> DirNative;
185
0
  llvm::sys::path::native((*PCHDir)->getName(), DirNative);
186
0
  llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
187
0
  SimpleASTReaderListener Validator(CI.getPreprocessor());
188
0
  for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
189
0
       Dir != DirEnd && !EC; Dir.increment(EC)) {
190
    // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
191
    // used here since we're not interested in validating the PCH at this time,
192
    // but only to check whether this is a file containing an AST.
193
0
    if (!ASTReader::readASTFileControlBlock(
194
0
            Dir->path(), FileMgr, CI.getPCHContainerReader(),
195
0
            /*FindModuleFileExtensions=*/false, Validator,
196
0
            /*ValidateDiagnosticOptions=*/false))
197
0
      MDC->addFile(Dir->path());
198
0
  }
199
0
}
200
201
static void collectVFSEntries(CompilerInstance &CI,
202
54
                              std::shared_ptr<ModuleDependencyCollector> MDC) {
203
54
  if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
204
52
    return;
205
206
  // Collect all VFS found.
207
2
  SmallVector<llvm::vfs::YAMLVFSEntry, 16> VFSEntries;
208
2
  for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) {
209
2
    llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
210
2
        llvm::MemoryBuffer::getFile(VFSFile);
211
2
    if (!Buffer)
212
0
      return;
213
2
    llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()),
214
2
                                  /*DiagHandler*/ nullptr, VFSFile, VFSEntries);
215
2
  }
216
217
2
  for (auto &E : VFSEntries)
218
2
    MDC->addFile(E.VPath, E.RPath);
219
2
}
220
221
// Diagnostics
222
static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
223
                               const CodeGenOptions *CodeGenOpts,
224
8
                               DiagnosticsEngine &Diags) {
225
8
  std::error_code EC;
226
8
  std::unique_ptr<raw_ostream> StreamOwner;
227
8
  raw_ostream *OS = &llvm::errs();
228
8
  if (DiagOpts->DiagnosticLogFile != "-") {
229
    // Create the output stream.
230
2
    auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
231
2
        DiagOpts->DiagnosticLogFile, EC,
232
2
        llvm::sys::fs::OF_Append | llvm::sys::fs::OF_Text);
233
2
    if (EC) {
234
0
      Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
235
0
          << DiagOpts->DiagnosticLogFile << EC.message();
236
2
    } else {
237
2
      FileOS->SetUnbuffered();
238
2
      OS = FileOS.get();
239
2
      StreamOwner = std::move(FileOS);
240
2
    }
241
2
  }
242
243
  // Chain in the diagnostic client which will log the diagnostics.
244
8
  auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
245
8
                                                        std::move(StreamOwner));
246
8
  if (CodeGenOpts)
247
7
    Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
248
8
  if (Diags.ownsClient()) {
249
7
    Diags.setClient(
250
7
        new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
251
1
  } else {
252
1
    Diags.setClient(
253
1
        new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger)));
254
1
  }
255
8
}
256
257
static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
258
                                       DiagnosticsEngine &Diags,
259
20
                                       StringRef OutputFile) {
260
20
  auto SerializedConsumer =
261
20
      clang::serialized_diags::create(OutputFile, DiagOpts);
262
263
20
  if (Diags.ownsClient()) {
264
20
    Diags.setClient(new ChainedDiagnosticConsumer(
265
20
        Diags.takeClient(), std::move(SerializedConsumer)));
266
0
  } else {
267
0
    Diags.setClient(new ChainedDiagnosticConsumer(
268
0
        Diags.getClient(), std::move(SerializedConsumer)));
269
0
  }
270
20
}
271
272
void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
273
71.0k
                                         bool ShouldOwnClient) {
274
71.0k
  Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
275
71.0k
                                  ShouldOwnClient, &getCodeGenOpts());
276
71.0k
}
277
278
IntrusiveRefCntPtr<DiagnosticsEngine>
279
CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
280
                                    DiagnosticConsumer *Client,
281
                                    bool ShouldOwnClient,
282
79.3k
                                    const CodeGenOptions *CodeGenOpts) {
283
79.3k
  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
284
79.3k
  IntrusiveRefCntPtr<DiagnosticsEngine>
285
79.3k
      Diags(new DiagnosticsEngine(DiagID, Opts));
286
287
  // Create the diagnostic client for reporting errors or for
288
  // implementing -verify.
289
79.3k
  if (Client) {
290
3.26k
    Diags->setClient(Client, ShouldOwnClient);
291
3.26k
  } else
292
76.1k
    Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
293
294
  // Chain in -verify checker, if requested.
295
79.3k
  if (Opts->VerifyDiagnostics)
296
16.8k
    Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
297
298
  // Chain in -diagnostic-log-file dumper, if requested.
299
79.3k
  if (!Opts->DiagnosticLogFile.empty())
300
8
    SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
301
302
79.3k
  if (!Opts->DiagnosticSerializationFile.empty())
303
20
    SetupSerializedDiagnostics(Opts, *Diags,
304
20
                               Opts->DiagnosticSerializationFile);
305
306
  // Configure our handling of diagnostics.
307
79.3k
  ProcessWarningOptions(*Diags, *Opts);
308
309
79.3k
  return Diags;
310
79.3k
}
311
312
// File Manager
313
314
FileManager *CompilerInstance::createFileManager(
315
67.9k
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
316
67.9k
  if (!VFS)
317
52.7k
    VFS = FileMgr ? 
&FileMgr->getVirtualFileSystem()13.0k
318
39.7k
                  : createVFSFromCompilerInvocation(getInvocation(),
319
39.7k
                                                    getDiagnostics());
320
67.9k
  assert(VFS && "FileManager has no VFS?");
321
67.9k
  FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS));
322
67.9k
  return FileMgr.get();
323
67.9k
}
324
325
// Source Manager
326
327
72.1k
void CompilerInstance::createSourceManager(FileManager &FileMgr) {
328
72.1k
  SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
329
72.1k
}
330
331
// Initialize the remapping of files to alternative contents, e.g.,
332
// those specified through other files.
333
static void InitializeFileRemapping(DiagnosticsEngine &Diags,
334
                                    SourceManager &SourceMgr,
335
                                    FileManager &FileMgr,
336
82.9k
                                    const PreprocessorOptions &InitOpts) {
337
  // Remap files in the source manager (with buffers).
338
4.02k
  for (const auto &RB : InitOpts.RemappedFileBuffers) {
339
    // Create the file entry for the file that we're mapping from.
340
4.02k
    const FileEntry *FromFile =
341
4.02k
        FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0);
342
4.02k
    if (!FromFile) {
343
0
      Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first;
344
0
      if (!InitOpts.RetainRemappedFileBuffers)
345
0
        delete RB.second;
346
0
      continue;
347
0
    }
348
349
    // Override the contents of the "from" file with the contents of the
350
    // "to" file. If the caller owns the buffers, then pass a MemoryBufferRef;
351
    // otherwise, pass as a std::unique_ptr<MemoryBuffer> to transfer ownership
352
    // to the SourceManager.
353
4.02k
    if (InitOpts.RetainRemappedFileBuffers)
354
554
      SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
355
3.47k
    else
356
3.47k
      SourceMgr.overrideFileContents(
357
3.47k
          FromFile, std::unique_ptr<llvm::MemoryBuffer>(
358
3.47k
                        const_cast<llvm::MemoryBuffer *>(RB.second)));
359
4.02k
  }
360
361
  // Remap files in the source manager (with other files).
362
16
  for (const auto &RF : InitOpts.RemappedFiles) {
363
    // Find the file that we're mapping to.
364
16
    auto ToFile = FileMgr.getFile(RF.second);
365
16
    if (!ToFile) {
366
0
      Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
367
0
      continue;
368
0
    }
369
370
    // Create the file entry for the file that we're mapping from.
371
16
    const FileEntry *FromFile =
372
16
        FileMgr.getVirtualFile(RF.first, (*ToFile)->getSize(), 0);
373
16
    if (!FromFile) {
374
0
      Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
375
0
      continue;
376
0
    }
377
378
    // Override the contents of the "from" file with the contents of
379
    // the "to" file.
380
16
    SourceMgr.overrideFileContents(FromFile, *ToFile);
381
16
  }
382
383
82.9k
  SourceMgr.setOverridenFilesKeepOriginalName(
384
82.9k
      InitOpts.RemappedFilesKeepOriginalName);
385
82.9k
}
386
387
// Preprocessor
388
389
82.9k
void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
390
82.9k
  const PreprocessorOptions &PPOpts = getPreprocessorOpts();
391
392
  // The AST reader holds a reference to the old preprocessor (if any).
393
82.9k
  TheASTReader.reset();
394
395
  // Create the Preprocessor.
396
82.9k
  HeaderSearch *HeaderInfo =
397
82.9k
      new HeaderSearch(getHeaderSearchOptsPtr(), getSourceManager(),
398
82.9k
                       getDiagnostics(), getLangOpts(), &getTarget());
399
82.9k
  PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOptsPtr(),
400
82.9k
                                      getDiagnostics(), getLangOpts(),
401
82.9k
                                      getSourceManager(), *HeaderInfo, *this,
402
82.9k
                                      /*IdentifierInfoLookup=*/nullptr,
403
82.9k
                                      /*OwnsHeaderSearch=*/true, TUKind);
404
82.9k
  getTarget().adjust(getLangOpts());
405
82.9k
  PP->Initialize(getTarget(), getAuxTarget());
406
407
82.9k
  if (PPOpts.DetailedRecord)
408
1.95k
    PP->createPreprocessingRecord();
409
410
  // Apply remappings to the source manager.
411
82.9k
  InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
412
82.9k
                          PP->getFileManager(), PPOpts);
413
414
  // Predefine macros and configure the preprocessor.
415
82.9k
  InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(),
416
82.9k
                         getFrontendOpts());
417
418
  // Initialize the header search object.  In CUDA compilations, we use the aux
419
  // triple (the host triple) to initialize our header search, since we need to
420
  // find the host headers in order to compile the CUDA code.
421
82.9k
  const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
422
82.9k
  if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
423
124
      PP->getAuxTargetInfo())
424
43
    HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
425
426
82.9k
  ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
427
82.9k
                           PP->getLangOpts(), *HeaderSearchTriple);
428
429
82.9k
  PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
430
431
82.9k
  if (PP->getLangOpts().Modules && 
PP->getLangOpts().ImplicitModules9.82k
) {
432
7.05k
    std::string ModuleHash = getInvocation().getModuleHash();
433
7.05k
    PP->getHeaderSearchInfo().setModuleHash(ModuleHash);
434
7.05k
    PP->getHeaderSearchInfo().setModuleCachePath(
435
7.05k
        getSpecificModuleCachePath(ModuleHash));
436
7.05k
  }
437
438
  // Handle generating dependencies, if requested.
439
82.9k
  const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
440
82.9k
  if (!DepOpts.OutputFile.empty())
441
2.94k
    addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts));
442
82.9k
  if (!DepOpts.DOTOutputFile.empty())
443
0
    AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
444
0
                             getHeaderSearchOpts().Sysroot);
445
446
  // If we don't have a collector, but we are collecting module dependencies,
447
  // then we're the top level compiler instance and need to create one.
448
82.9k
  if (!ModuleDepCollector && 
!DepOpts.ModuleDependencyOutputDir.empty()82.9k
) {
449
16
    ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
450
16
        DepOpts.ModuleDependencyOutputDir);
451
16
  }
452
453
  // If there is a module dep collector, register with other dep collectors
454
  // and also (a) collect header maps and (b) TODO: input vfs overlay files.
455
82.9k
  if (ModuleDepCollector) {
456
54
    addDependencyCollector(ModuleDepCollector);
457
54
    collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
458
54
    collectIncludePCH(*this, ModuleDepCollector);
459
54
    collectVFSEntries(*this, ModuleDepCollector);
460
54
  }
461
462
82.9k
  for (auto &Listener : DependencyCollectors)
463
3.16k
    Listener->attachToPreprocessor(*PP);
464
465
  // Handle generating header include information, if requested.
466
82.9k
  if (DepOpts.ShowHeaderIncludes)
467
3
    AttachHeaderIncludeGen(*PP, DepOpts);
468
82.9k
  if (!DepOpts.HeaderIncludeOutputFile.empty()) {
469
6
    StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
470
6
    if (OutputPath == "-")
471
6
      OutputPath = "";
472
6
    AttachHeaderIncludeGen(*PP, DepOpts,
473
6
                           /*ShowAllHeaders=*/true, OutputPath,
474
6
                           /*ShowDepth=*/false);
475
6
  }
476
477
82.9k
  if (DepOpts.ShowIncludesDest != ShowIncludesDestination::None) {
478
10
    AttachHeaderIncludeGen(*PP, DepOpts,
479
10
                           /*ShowAllHeaders=*/true, /*OutputPath=*/"",
480
10
                           /*ShowDepth=*/true, /*MSStyle=*/true);
481
10
  }
482
82.9k
}
483
484
10.5k
std::string CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) {
485
  // Set up the module path, including the hash for the module-creation options.
486
10.5k
  SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath);
487
10.5k
  if (!SpecificModuleCache.empty() && 
!getHeaderSearchOpts().DisableModuleHash6.32k
)
488
6.07k
    llvm::sys::path::append(SpecificModuleCache, ModuleHash);
489
10.5k
  return std::string(SpecificModuleCache.str());
490
10.5k
}
491
492
// ASTContext
493
494
78.3k
void CompilerInstance::createASTContext() {
495
78.3k
  Preprocessor &PP = getPreprocessor();
496
78.3k
  auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
497
78.3k
                                 PP.getIdentifierTable(), PP.getSelectorTable(),
498
78.3k
                                 PP.getBuiltinInfo());
499
78.3k
  Context->InitBuiltinTypes(getTarget(), getAuxTarget());
500
78.3k
  setASTContext(Context);
501
78.3k
}
502
503
// ExternalASTSource
504
505
void CompilerInstance::createPCHExternalASTSource(
506
    StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors,
507
3.49k
    void *DeserializationListener, bool OwnDeserializationListener) {
508
3.49k
  bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
509
3.49k
  TheASTReader = createPCHExternalASTSource(
510
3.49k
      Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation,
511
3.49k
      AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(),
512
3.49k
      getASTContext(), getPCHContainerReader(),
513
3.49k
      getFrontendOpts().ModuleFileExtensions, DependencyCollectors,
514
3.49k
      DeserializationListener, OwnDeserializationListener, Preamble,
515
3.49k
      getFrontendOpts().UseGlobalModuleIndex);
516
3.49k
}
517
518
IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
519
    StringRef Path, StringRef Sysroot, bool DisablePCHValidation,
520
    bool AllowPCHWithCompilerErrors, Preprocessor &PP,
521
    InMemoryModuleCache &ModuleCache, ASTContext &Context,
522
    const PCHContainerReader &PCHContainerRdr,
523
    ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
524
    ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
525
    void *DeserializationListener, bool OwnDeserializationListener,
526
3.49k
    bool Preamble, bool UseGlobalModuleIndex) {
527
3.49k
  HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
528
529
3.49k
  IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader(
530
3.49k
      PP, ModuleCache, &Context, PCHContainerRdr, Extensions,
531
3.49k
      Sysroot.empty() ? 
""0
: Sysroot.data(), DisablePCHValidation,
532
3.49k
      AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
533
3.49k
      HSOpts.ModulesValidateSystemHeaders, HSOpts.ValidateASTInputFilesContent,
534
3.49k
      UseGlobalModuleIndex));
535
536
  // We need the external source to be set up before we read the AST, because
537
  // eagerly-deserialized declarations may use it.
538
3.49k
  Context.setExternalSource(Reader.get());
539
540
3.49k
  Reader->setDeserializationListener(
541
3.49k
      static_cast<ASTDeserializationListener *>(DeserializationListener),
542
3.49k
      /*TakeOwnership=*/OwnDeserializationListener);
543
544
3.49k
  for (auto &Listener : DependencyCollectors)
545
21
    Listener->attachToASTReader(*Reader);
546
547
3.49k
  switch (Reader->ReadAST(Path,
548
331
                          Preamble ? serialization::MK_Preamble
549
3.15k
                                   : serialization::MK_PCH,
550
3.49k
                          SourceLocation(),
551
3.49k
                          ASTReader::ARR_None)) {
552
3.46k
  case ASTReader::Success:
553
    // Set the predefines buffer as suggested by the PCH reader. Typically, the
554
    // predefines buffer will be empty.
555
3.46k
    PP.setPredefines(Reader->getSuggestedPredefines());
556
3.46k
    return Reader;
557
558
2
  case ASTReader::Failure:
559
    // Unrecoverable failure: don't even try to process the input file.
560
2
    break;
561
562
25
  case ASTReader::Missing:
563
25
  case ASTReader::OutOfDate:
564
25
  case ASTReader::VersionMismatch:
565
25
  case ASTReader::ConfigurationMismatch:
566
25
  case ASTReader::HadErrors:
567
    // No suitable PCH file could be found. Return an error.
568
25
    break;
569
27
  }
570
571
27
  Context.setExternalSource(nullptr);
572
27
  return nullptr;
573
27
}
574
575
// Code Completion
576
577
static bool EnableCodeCompletion(Preprocessor &PP,
578
                                 StringRef Filename,
579
                                 unsigned Line,
580
1.15k
                                 unsigned Column) {
581
  // Tell the source manager to chop off the given file at a specific
582
  // line and column.
583
1.15k
  auto Entry = PP.getFileManager().getFile(Filename);
584
1.15k
  if (!Entry) {
585
0
    PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
586
0
      << Filename;
587
0
    return true;
588
0
  }
589
590
  // Truncate the named file at the given line/column.
591
1.15k
  PP.SetCodeCompletionPoint(*Entry, Line, Column);
592
1.15k
  return false;
593
1.15k
}
594
595
1.15k
void CompilerInstance::createCodeCompletionConsumer() {
596
1.15k
  const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
597
1.15k
  if (!CompletionConsumer) {
598
268
    setCodeCompletionConsumer(
599
268
      createCodeCompletionConsumer(getPreprocessor(),
600
268
                                   Loc.FileName, Loc.Line, Loc.Column,
601
268
                                   getFrontendOpts().CodeCompleteOpts,
602
268
                                   llvm::outs()));
603
268
    if (!CompletionConsumer)
604
0
      return;
605
887
  } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
606
0
                                  Loc.Line, Loc.Column)) {
607
0
    setCodeCompletionConsumer(nullptr);
608
0
    return;
609
0
  }
610
1.15k
}
611
612
14
void CompilerInstance::createFrontendTimer() {
613
14
  FrontendTimerGroup.reset(
614
14
      new llvm::TimerGroup("frontend", "Clang front-end time report"));
615
14
  FrontendTimer.reset(
616
14
      new llvm::Timer("frontend", "Clang front-end timer",
617
14
                      *FrontendTimerGroup));
618
14
}
619
620
CodeCompleteConsumer *
621
CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
622
                                               StringRef Filename,
623
                                               unsigned Line,
624
                                               unsigned Column,
625
                                               const CodeCompleteOptions &Opts,
626
268
                                               raw_ostream &OS) {
627
268
  if (EnableCodeCompletion(PP, Filename, Line, Column))
628
0
    return nullptr;
629
630
  // Set up the creation routine for code-completion.
631
268
  return new PrintingCodeCompleteConsumer(Opts, OS);
632
268
}
633
634
void CompilerInstance::createSema(TranslationUnitKind TUKind,
635
64.7k
                                  CodeCompleteConsumer *CompletionConsumer) {
636
64.7k
  TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
637
64.7k
                         TUKind, CompletionConsumer));
638
  // Attach the external sema source if there is any.
639
64.7k
  if (ExternalSemaSrc) {
640
1
    TheSema->addExternalSource(ExternalSemaSrc.get());
641
1
    ExternalSemaSrc->InitializeSema(*TheSema);
642
1
  }
643
64.7k
}
644
645
// Output Files
646
647
25.3k
void CompilerInstance::addOutputFile(OutputFile &&OutFile) {
648
25.3k
  OutputFiles.push_back(std::move(OutFile));
649
25.3k
}
650
651
70.1k
void CompilerInstance::clearOutputFiles(bool EraseFiles) {
652
25.3k
  for (OutputFile &OF : OutputFiles) {
653
25.3k
    if (!OF.TempFilename.empty()) {
654
9.65k
      if (EraseFiles) {
655
79
        llvm::sys::fs::remove(OF.TempFilename);
656
9.57k
      } else {
657
9.57k
        SmallString<128> NewOutFile(OF.Filename);
658
659
        // If '-working-directory' was passed, the output filename should be
660
        // relative to that.
661
9.57k
        FileMgr->FixupRelativePath(NewOutFile);
662
9.57k
        if (std::error_code ec =
663
0
                llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) {
664
0
          getDiagnostics().Report(diag::err_unable_to_rename_temp)
665
0
            << OF.TempFilename << OF.Filename << ec.message();
666
667
0
          llvm::sys::fs::remove(OF.TempFilename);
668
0
        }
669
9.57k
      }
670
15.6k
    } else if (!OF.Filename.empty() && 
EraseFiles352
)
671
30
      llvm::sys::fs::remove(OF.Filename);
672
25.3k
  }
673
70.1k
  OutputFiles.clear();
674
70.1k
  if (DeleteBuiltModules) {
675
70.0k
    for (auto &Module : BuiltModules)
676
75
      llvm::sys::fs::remove(Module.second);
677
70.0k
    BuiltModules.clear();
678
70.0k
  }
679
70.1k
  NonSeekStream.reset();
680
70.1k
}
681
682
std::unique_ptr<raw_pwrite_stream>
683
CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile,
684
20.3k
                                          StringRef Extension) {
685
20.3k
  return createOutputFile(getFrontendOpts().OutputFile, Binary,
686
20.3k
                          /*RemoveFileOnSignal=*/true, InFile, Extension,
687
20.3k
                          getFrontendOpts().UseTemporary);
688
20.3k
}
689
690
4
std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
691
4
  return std::make_unique<llvm::raw_null_ostream>();
692
4
}
693
694
std::unique_ptr<raw_pwrite_stream>
695
CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
696
                                   bool RemoveFileOnSignal, StringRef InFile,
697
                                   StringRef Extension, bool UseTemporary,
698
25.3k
                                   bool CreateMissingDirectories) {
699
25.3k
  std::string OutputPathName, TempPathName;
700
25.3k
  std::error_code EC;
701
25.3k
  std::unique_ptr<raw_pwrite_stream> OS = createOutputFile(
702
25.3k
      OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
703
25.3k
      UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
704
25.3k
  if (!OS) {
705
3
    getDiagnostics().Report(diag::err_fe_unable_to_open_output) << OutputPath
706
3
                                                                << EC.message();
707
3
    return nullptr;
708
3
  }
709
710
  // Add the output file -- but don't try to remove "-", since this means we are
711
  // using stdin.
712
25.3k
  addOutputFile(
713
15.3k
      OutputFile((OutputPathName != "-") ? 
OutputPathName10.0k
: "", TempPathName));
714
715
25.3k
  return OS;
716
25.3k
}
717
718
std::unique_ptr<llvm::raw_pwrite_stream> CompilerInstance::createOutputFile(
719
    StringRef OutputPath, std::error_code &Error, bool Binary,
720
    bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
721
    bool UseTemporary, bool CreateMissingDirectories,
722
25.3k
    std::string *ResultPathName, std::string *TempPathName) {
723
25.3k
  assert((!CreateMissingDirectories || UseTemporary) &&
724
25.3k
         "CreateMissingDirectories is only allowed when using temporary files");
725
726
25.3k
  std::string OutFile, TempFile;
727
25.3k
  if (!OutputPath.empty()) {
728
24.1k
    OutFile = std::string(OutputPath);
729
1.22k
  } else if (InFile == "-") {
730
428
    OutFile = "-";
731
795
  } else if (!Extension.empty()) {
732
4
    SmallString<128> Path(InFile);
733
4
    llvm::sys::path::replace_extension(Path, Extension);
734
4
    OutFile = std::string(Path.str());
735
791
  } else {
736
791
    OutFile = "-";
737
791
  }
738
739
25.3k
  std::unique_ptr<llvm::raw_fd_ostream> OS;
740
25.3k
  std::string OSFile;
741
742
25.3k
  if (UseTemporary) {
743
25.3k
    if (OutFile == "-")
744
15.3k
      UseTemporary = false;
745
10.0k
    else {
746
10.0k
      llvm::sys::fs::file_status Status;
747
10.0k
      llvm::sys::fs::status(OutputPath, Status);
748
10.0k
      if (llvm::sys::fs::exists(Status)) {
749
        // Fail early if we can't write to the final destination.
750
3.49k
        if (!llvm::sys::fs::can_write(OutputPath)) {
751
0
          Error = make_error_code(llvm::errc::operation_not_permitted);
752
0
          return nullptr;
753
0
        }
754
755
        // Don't use a temporary if the output is a special file. This handles
756
        // things like '-o /dev/null'
757
3.49k
        if (!llvm::sys::fs::is_regular_file(Status))
758
350
          UseTemporary = false;
759
3.49k
      }
760
10.0k
    }
761
25.3k
  }
762
763
25.3k
  if (UseTemporary) {
764
    // Create a temporary file.
765
    // Insert -%%%%%%%% before the extension (if any), and because some tools
766
    // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build
767
    // artifacts, also append .tmp.
768
9.65k
    StringRef OutputExtension = llvm::sys::path::extension(OutFile);
769
9.65k
    SmallString<128> TempPath =
770
9.65k
        StringRef(OutFile).drop_back(OutputExtension.size());
771
9.65k
    TempPath += "-%%%%%%%%";
772
9.65k
    TempPath += OutputExtension;
773
9.65k
    TempPath += ".tmp";
774
9.65k
    int fd;
775
9.65k
    std::error_code EC =
776
9.65k
        llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
777
778
9.65k
    if (CreateMissingDirectories &&
779
1.85k
        EC == llvm::errc::no_such_file_or_directory) {
780
55
      StringRef Parent = llvm::sys::path::parent_path(OutputPath);
781
55
      EC = llvm::sys::fs::create_directories(Parent);
782
55
      if (!EC) {
783
55
        EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
784
55
      }
785
55
    }
786
787
9.65k
    if (!EC) {
788
9.65k
      OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
789
9.65k
      OSFile = TempFile = std::string(TempPath.str());
790
9.65k
    }
791
    // If we failed to create the temporary, fallback to writing to the file
792
    // directly. This handles the corner case where we cannot write to the
793
    // directory, but can write to the file.
794
9.65k
  }
795
796
25.3k
  if (!OS) {
797
15.6k
    OSFile = OutFile;
798
15.6k
    OS.reset(new llvm::raw_fd_ostream(
799
15.6k
        OSFile, Error,
800
13.7k
        (Binary ? 
llvm::sys::fs::OF_None1.95k
: llvm::sys::fs::OF_Text)));
801
15.6k
    if (Error)
802
3
      return nullptr;
803
25.3k
  }
804
805
  // Make sure the out stream file gets removed if we crash.
806
25.3k
  if (RemoveFileOnSignal)
807
20.3k
    llvm::sys::RemoveFileOnSignal(OSFile);
808
809
25.3k
  if (ResultPathName)
810
25.3k
    *ResultPathName = OutFile;
811
25.3k
  if (TempPathName)
812
25.3k
    *TempPathName = TempFile;
813
814
25.3k
  if (!Binary || 
OS->supportsSeeking()10.9k
)
815
23.4k
    return std::move(OS);
816
817
1.85k
  auto B = std::make_unique<llvm::buffer_ostream>(*OS);
818
1.85k
  assert(!NonSeekStream);
819
1.85k
  NonSeekStream = std::move(OS);
820
1.85k
  return std::move(B);
821
1.85k
}
822
823
// Initialization Utilities
824
825
69.8k
bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
826
69.8k
  return InitializeSourceManager(Input, getDiagnostics(), getFileManager(),
827
69.8k
                                 getSourceManager());
828
69.8k
}
829
830
// static
831
bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
832
                                               DiagnosticsEngine &Diags,
833
                                               FileManager &FileMgr,
834
69.8k
                                               SourceManager &SourceMgr) {
835
69.8k
  SrcMgr::CharacteristicKind Kind =
836
69.8k
      Input.getKind().getFormat() == InputKind::ModuleMap
837
1.89k
          ? Input.isSystem() ? 
SrcMgr::C_System_ModuleMap347
838
1.54k
                             : SrcMgr::C_User_ModuleMap
839
67.9k
          : Input.isSystem() ? 
SrcMgr::C_System0
: SrcMgr::C_User;
840
841
69.8k
  if (Input.isBuffer()) {
842
8
    SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
843
8
    assert(SourceMgr.getMainFileID().isValid() &&
844
8
           "Couldn't establish MainFileID!");
845
8
    return true;
846
8
  }
847
848
69.8k
  StringRef InputFile = Input.getFile();
849
850
  // Figure out where to get and map in the main file.
851
69.8k
  if (InputFile != "-") {
852
69.1k
    auto FileOrErr = FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
853
69.1k
    if (!FileOrErr) {
854
      // FIXME: include the error in the diagnostic.
855
4
      consumeError(FileOrErr.takeError());
856
4
      Diags.Report(diag::err_fe_error_reading) << InputFile;
857
4
      return false;
858
4
    }
859
69.1k
    FileEntryRef File = *FileOrErr;
860
861
    // The natural SourceManager infrastructure can't currently handle named
862
    // pipes, but we would at least like to accept them for the main
863
    // file. Detect them here, read them with the volatile flag so FileMgr will
864
    // pick up the correct size, and simply override their contents as we do for
865
    // STDIN.
866
69.1k
    if (File.getFileEntry().isNamedPipe()) {
867
1
      auto MB =
868
1
          FileMgr.getBufferForFile(&File.getFileEntry(), /*isVolatile=*/true);
869
1
      if (MB) {
870
        // Create a new virtual file that will have the correct size.
871
1
        const FileEntry *FE =
872
1
            FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
873
1
        SourceMgr.overrideFileContents(FE, std::move(*MB));
874
1
        SourceMgr.setMainFileID(
875
1
            SourceMgr.createFileID(FE, SourceLocation(), Kind));
876
0
      } else {
877
0
        Diags.Report(diag::err_cannot_open_file) << InputFile
878
0
                                                 << MB.getError().message();
879
0
        return false;
880
0
      }
881
69.1k
    } else {
882
69.1k
      SourceMgr.setMainFileID(
883
69.1k
          SourceMgr.createFileID(File, SourceLocation(), Kind));
884
69.1k
    }
885
643
  } else {
886
643
    llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
887
643
        llvm::MemoryBuffer::getSTDIN();
888
643
    if (std::error_code EC = SBOrErr.getError()) {
889
0
      Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
890
0
      return false;
891
0
    }
892
643
    std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
893
894
643
    const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
895
643
                                                   SB->getBufferSize(), 0);
896
643
    SourceMgr.setMainFileID(
897
643
        SourceMgr.createFileID(File, SourceLocation(), Kind));
898
643
    SourceMgr.overrideFileContents(File, std::move(SB));
899
643
  }
900
901
69.8k
  assert(SourceMgr.getMainFileID().isValid() &&
902
69.8k
         "Couldn't establish MainFileID!");
903
69.8k
  return true;
904
69.8k
}
905
906
// High-Level Operations
907
908
59.9k
bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
909
59.9k
  assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
910
59.9k
  assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
911
59.9k
  assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
912
913
  // Mark this point as the bottom of the stack if we don't have somewhere
914
  // better. We generally expect frontend actions to be invoked with (nearly)
915
  // DesiredStackSpace available.
916
59.9k
  noteBottomOfStack();
917
918
59.9k
  raw_ostream &OS = getVerboseOutputStream();
919
920
59.9k
  if (!Act.PrepareToExecute(*this))
921
0
    return false;
922
923
  // Create the target instance.
924
59.9k
  setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
925
59.9k
                                         getInvocation().TargetOpts));
926
59.9k
  if (!hasTarget())
927
105
    return false;
928
929
  // Create TargetInfo for the other side of CUDA/OpenMP/SYCL compilation.
930
59.8k
  if ((getLangOpts().CUDA || 
getLangOpts().OpenMPIsDevice59.4k
||
931
58.7k
       getLangOpts().SYCLIsDevice) &&
932
1.08k
      !getFrontendOpts().AuxTriple.empty()) {
933
133
    auto TO = std::make_shared<TargetOptions>();
934
133
    TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
935
133
    if (getFrontendOpts().AuxTargetCPU)
936
27
      TO->CPU = getFrontendOpts().AuxTargetCPU.getValue();
937
133
    if (getFrontendOpts().AuxTargetFeatures)
938
1
      TO->FeaturesAsWritten = getFrontendOpts().AuxTargetFeatures.getValue();
939
133
    TO->HostTriple = getTarget().getTriple().str();
940
133
    setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
941
133
  }
942
943
59.8k
  if (!getTarget().hasStrictFP() && 
!getLangOpts().ExpStrictFP5.24k
) {
944
5.22k
    if (getLangOpts().getFPRoundingMode() !=
945
2
        llvm::RoundingMode::NearestTiesToEven) {
946
2
      getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding);
947
2
      getLangOpts().setFPRoundingMode(llvm::RoundingMode::NearestTiesToEven);
948
2
    }
949
5.22k
    if (getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore) {
950
2
      getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions);
951
2
      getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore);
952
2
    }
953
    // FIXME: can we disable FEnvAccess?
954
5.22k
  }
955
956
  // Inform the target of the language options.
957
  //
958
  // FIXME: We shouldn't need to do this, the target should be immutable once
959
  // created. This complexity should be lifted elsewhere.
960
59.8k
  getTarget().adjust(getLangOpts());
961
962
  // Adjust target options based on codegen options.
963
59.8k
  getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts());
964
965
59.8k
  if (auto *Aux = getAuxTarget())
966
133
    getTarget().setAuxTarget(Aux);
967
968
  // rewriter project will change target built-in bool type from its default.
969
59.8k
  if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
970
164
    getTarget().noSignedCharForObjCBool();
971
972
  // Validate/process some options.
973
59.8k
  if (getHeaderSearchOpts().Verbose)
974
59
    OS << "clang -cc1 version " CLANG_VERSION_STRING
975
59
       << " based upon " << BACKEND_PACKAGE_STRING
976
59
       << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
977
978
59.8k
  if (getFrontendOpts().ShowTimers)
979
14
    createFrontendTimer();
980
981
59.8k
  if (getFrontendOpts().ShowStats || 
!getFrontendOpts().StatsFile.empty()59.8k
)
982
6
    llvm::EnableStatistics(false);
983
984
59.8k
  for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
985
    // Reset the ID tables if we are reusing the SourceManager and parsing
986
    // regular files.
987
59.8k
    if (hasSourceManager() && 
!Act.isModelParsingAction()20.2k
)
988
20.2k
      getSourceManager().clearIDTables();
989
990
59.8k
    if (Act.BeginSourceFile(*this, FIF)) {
991
59.7k
      if (llvm::Error Err = Act.Execute()) {
992
0
        consumeError(std::move(Err)); // FIXME this drops errors on the floor.
993
0
      }
994
59.7k
      Act.EndSourceFile();
995
59.7k
    }
996
59.8k
  }
997
998
  // Notify the diagnostic client that all files were processed.
999
59.8k
  getDiagnostics().getClient()->finish();
1000
1001
59.8k
  if (getDiagnosticOpts().ShowCarets) {
1002
    // We can have multiple diagnostics sharing one diagnostic client.
1003
    // Get the total number of warnings/errors from the client.
1004
59.7k
    unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
1005
59.7k
    unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
1006
1007
59.7k
    if (NumWarnings)
1008
2.97k
      OS << NumWarnings << " warning" << (NumWarnings == 1 ? 
""1.80k
:
"s"1.17k
);
1009
59.7k
    if (NumWarnings && 
NumErrors2.97k
)
1010
121
      OS << " and ";
1011
59.7k
    if (NumErrors)
1012
652
      OS << NumErrors << " error" << (NumErrors == 1 ? 
""328
:
"s"324
);
1013
59.7k
    if (NumWarnings || 
NumErrors56.7k
) {
1014
3.50k
      OS << " generated";
1015
3.50k
      if (getLangOpts().CUDA) {
1016
19
        if (!getLangOpts().CUDAIsDevice) {
1017
9
          OS << " when compiling for host";
1018
10
        } else {
1019
10
          OS << " when compiling for " << getTargetOpts().CPU;
1020
10
        }
1021
19
      }
1022
3.50k
      OS << ".\n";
1023
3.50k
    }
1024
59.7k
  }
1025
1026
59.8k
  if (getFrontendOpts().ShowStats) {
1027
4
    if (hasFileManager()) {
1028
4
      getFileManager().PrintStats();
1029
4
      OS << '\n';
1030
4
    }
1031
4
    llvm::PrintStatistics(OS);
1032
4
  }
1033
59.8k
  StringRef StatsFile = getFrontendOpts().StatsFile;
1034
59.8k
  if (!StatsFile.empty()) {
1035
2
    std::error_code EC;
1036
2
    auto StatS = std::make_unique<llvm::raw_fd_ostream>(
1037
2
        StatsFile, EC, llvm::sys::fs::OF_Text);
1038
2
    if (EC) {
1039
1
      getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
1040
1
          << StatsFile << EC.message();
1041
1
    } else {
1042
1
      llvm::PrintStatisticsJSON(*StatS);
1043
1
    }
1044
2
  }
1045
1046
59.8k
  return !getDiagnostics().getClient()->getNumErrors();
1047
59.8k
}
1048
1049
/// Determine the appropriate source input kind based on language
1050
/// options.
1051
1.66k
static Language getLanguageFromOptions(const LangOptions &LangOpts) {
1052
1.66k
  if (LangOpts.OpenCL)
1053
6
    return Language::OpenCL;
1054
1.66k
  if (LangOpts.CUDA)
1055
0
    return Language::CUDA;
1056
1.66k
  if (LangOpts.ObjC)
1057
877
    return LangOpts.CPlusPlus ? 
Language::ObjCXX220
:
Language::ObjC657
;
1058
785
  return LangOpts.CPlusPlus ? 
Language::CXX689
:
Language::C96
;
1059
785
}
1060
1061
/// Compile a module file for the given module, using the options
1062
/// provided by the importing compiler instance. Returns true if the module
1063
/// was built without errors.
1064
static bool
1065
compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
1066
                  StringRef ModuleName, FrontendInputFile Input,
1067
                  StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1068
                  llvm::function_ref<void(CompilerInstance &)> PreBuildStep =
1069
1.49k
                      [](CompilerInstance &) {},
1070
                  llvm::function_ref<void(CompilerInstance &)> PostBuildStep =
1071
1.66k
                      [](CompilerInstance &) 
{}1.59k
) {
1072
1.66k
  llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
1073
1074
  // Construct a compiler invocation for creating this module.
1075
1.66k
  auto Invocation =
1076
1.66k
      std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation());
1077
1078
1.66k
  PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1079
1080
  // For any options that aren't intended to affect how a module is built,
1081
  // reset them to their default values.
1082
1.66k
  Invocation->getLangOpts()->resetNonModularOptions();
1083
1.66k
  PPOpts.resetNonModularOptions();
1084
1085
  // Remove any macro definitions that are explicitly ignored by the module.
1086
  // They aren't supposed to affect how the module is built anyway.
1087
1.66k
  HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1088
1.66k
  PPOpts.Macros.erase(
1089
1.66k
      std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
1090
1.09k
                     [&HSOpts](const std::pair<std::string, bool> &def) {
1091
1.09k
        StringRef MacroDef = def.first;
1092
1.09k
        return HSOpts.ModulesIgnoreMacros.count(
1093
1.09k
                   llvm::CachedHashString(MacroDef.split('=').first)) > 0;
1094
1.09k
      }),
1095
1.66k
      PPOpts.Macros.end());
1096
1097
  // If the original compiler invocation had -fmodule-name, pass it through.
1098
1.66k
  Invocation->getLangOpts()->ModuleName =
1099
1.66k
      ImportingInstance.getInvocation().getLangOpts()->ModuleName;
1100
1101
  // Note the name of the module we're building.
1102
1.66k
  Invocation->getLangOpts()->CurrentModule = std::string(ModuleName);
1103
1104
  // Make sure that the failed-module structure has been allocated in
1105
  // the importing instance, and propagate the pointer to the newly-created
1106
  // instance.
1107
1.66k
  PreprocessorOptions &ImportingPPOpts
1108
1.66k
    = ImportingInstance.getInvocation().getPreprocessorOpts();
1109
1.66k
  if (!ImportingPPOpts.FailedModules)
1110
816
    ImportingPPOpts.FailedModules =
1111
816
        std::make_shared<PreprocessorOptions::FailedModulesSet>();
1112
1.66k
  PPOpts.FailedModules = ImportingPPOpts.FailedModules;
1113
1114
  // If there is a module map file, build the module using the module map.
1115
  // Set up the inputs/outputs so that we build the module from its umbrella
1116
  // header.
1117
1.66k
  FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1118
1.66k
  FrontendOpts.OutputFile = ModuleFileName.str();
1119
1.66k
  FrontendOpts.DisableFree = false;
1120
1.66k
  FrontendOpts.GenerateGlobalModuleIndex = false;
1121
1.66k
  FrontendOpts.BuildingImplicitModule = true;
1122
1.66k
  FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile);
1123
  // Force implicitly-built modules to hash the content of the module file.
1124
1.66k
  HSOpts.ModulesHashContent = true;
1125
1.66k
  FrontendOpts.Inputs = {Input};
1126
1127
  // Don't free the remapped file buffers; they are owned by our caller.
1128
1.66k
  PPOpts.RetainRemappedFileBuffers = true;
1129
1130
1.66k
  Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
1131
1.66k
  assert(ImportingInstance.getInvocation().getModuleHash() ==
1132
1.66k
         Invocation->getModuleHash() && "Module hash mismatch!");
1133
1134
  // Construct a compiler instance that will be used to actually create the
1135
  // module.  Since we're sharing an in-memory module cache,
1136
  // CompilerInstance::CompilerInstance is responsible for finalizing the
1137
  // buffers to prevent use-after-frees.
1138
1.66k
  CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
1139
1.66k
                            &ImportingInstance.getModuleCache());
1140
1.66k
  auto &Inv = *Invocation;
1141
1.66k
  Instance.setInvocation(std::move(Invocation));
1142
1143
1.66k
  Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
1144
1.66k
                                   ImportingInstance.getDiagnosticClient()),
1145
1.66k
                             /*ShouldOwnClient=*/true);
1146
1147
  // Note that this module is part of the module build stack, so that we
1148
  // can detect cycles in the module graph.
1149
1.66k
  Instance.setFileManager(&ImportingInstance.getFileManager());
1150
1.66k
  Instance.createSourceManager(Instance.getFileManager());
1151
1.66k
  SourceManager &SourceMgr = Instance.getSourceManager();
1152
1.66k
  SourceMgr.setModuleBuildStack(
1153
1.66k
    ImportingInstance.getSourceManager().getModuleBuildStack());
1154
1.66k
  SourceMgr.pushModuleBuildStack(ModuleName,
1155
1.66k
    FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
1156
1157
  // If we're collecting module dependencies, we need to share a collector
1158
  // between all of the module CompilerInstances. Other than that, we don't
1159
  // want to produce any dependency output from the module build.
1160
1.66k
  Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
1161
1.66k
  Inv.getDependencyOutputOpts() = DependencyOutputOptions();
1162
1163
1.66k
  ImportingInstance.getDiagnostics().Report(ImportLoc,
1164
1.66k
                                            diag::remark_module_build)
1165
1.66k
    << ModuleName << ModuleFileName;
1166
1167
1.66k
  PreBuildStep(Instance);
1168
1169
  // Execute the action to actually build the module in-place. Use a separate
1170
  // thread so that we get a stack large enough.
1171
1.66k
  llvm::CrashRecoveryContext CRC;
1172
1.66k
  CRC.RunSafelyOnThread(
1173
1.66k
      [&]() {
1174
1.66k
        GenerateModuleFromModuleMapAction Action;
1175
1.66k
        Instance.ExecuteAction(Action);
1176
1.66k
      },
1177
1.66k
      DesiredStackSize);
1178
1179
1.66k
  PostBuildStep(Instance);
1180
1181
1.66k
  ImportingInstance.getDiagnostics().Report(ImportLoc,
1182
1.66k
                                            diag::remark_module_build_done)
1183
1.66k
    << ModuleName;
1184
1185
  // Delete the temporary module map file.
1186
  // FIXME: Even though we're executing under crash protection, it would still
1187
  // be nice to do this with RemoveFileOnSignal when we can. However, that
1188
  // doesn't make sense for all clients, so clean this up manually.
1189
1.66k
  Instance.clearOutputFiles(/*EraseFiles=*/true);
1190
1191
1.66k
  return !Instance.getDiagnostics().hasErrorOccurred();
1192
1.66k
}
1193
1194
static const FileEntry *getPublicModuleMap(const FileEntry *File,
1195
1.49k
                                           FileManager &FileMgr) {
1196
1.49k
  StringRef Filename = llvm::sys::path::filename(File->getName());
1197
1.49k
  SmallString<128> PublicFilename(File->getDir()->getName());
1198
1.49k
  if (Filename == "module_private.map")
1199
1
    llvm::sys::path::append(PublicFilename, "module.map");
1200
1.49k
  else if (Filename == "module.private.modulemap")
1201
11
    llvm::sys::path::append(PublicFilename, "module.modulemap");
1202
1.48k
  else
1203
1.48k
    return nullptr;
1204
12
  if (auto FE = FileMgr.getFile(PublicFilename))
1205
11
    return *FE;
1206
1
  return nullptr;
1207
1
}
1208
1209
/// Compile a module file for the given module in a separate compiler instance,
1210
/// using the options provided by the importing compiler instance. Returns true
1211
/// if the module was built without errors.
1212
static bool compileModule(CompilerInstance &ImportingInstance,
1213
                          SourceLocation ImportLoc, Module *Module,
1214
1.59k
                          StringRef ModuleFileName) {
1215
1.59k
  InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()),
1216
1.59k
               InputKind::ModuleMap);
1217
1218
  // Get or create the module map that we'll use to build this module.
1219
1.59k
  ModuleMap &ModMap
1220
1.59k
    = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1221
1.59k
  bool Result;
1222
1.59k
  if (const FileEntry *ModuleMapFile =
1223
1.49k
          ModMap.getContainingModuleMapFile(Module)) {
1224
    // Canonicalize compilation to start with the public module map. This is
1225
    // vital for submodules declarations in the private module maps to be
1226
    // correctly parsed when depending on a top level module in the public one.
1227
1.49k
    if (const FileEntry *PublicMMFile = getPublicModuleMap(
1228
11
            ModuleMapFile, ImportingInstance.getFileManager()))
1229
11
      ModuleMapFile = PublicMMFile;
1230
1231
    // Use the module map where this module resides.
1232
1.49k
    Result = compileModuleImpl(
1233
1.49k
        ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
1234
1.49k
        FrontendInputFile(ModuleMapFile->getName(), IK, +Module->IsSystem),
1235
1.49k
        ModMap.getModuleMapFileForUniquing(Module)->getName(),
1236
1.49k
        ModuleFileName);
1237
96
  } else {
1238
    // FIXME: We only need to fake up an input file here as a way of
1239
    // transporting the module's directory to the module map parser. We should
1240
    // be able to do that more directly, and parse from a memory buffer without
1241
    // inventing this file.
1242
96
    SmallString<128> FakeModuleMapFile(Module->Directory->getName());
1243
96
    llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
1244
1245
96
    std::string InferredModuleMapContent;
1246
96
    llvm::raw_string_ostream OS(InferredModuleMapContent);
1247
96
    Module->print(OS);
1248
96
    OS.flush();
1249
1250
96
    Result = compileModuleImpl(
1251
96
        ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
1252
96
        FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
1253
96
        ModMap.getModuleMapFileForUniquing(Module)->getName(),
1254
96
        ModuleFileName,
1255
96
        [&](CompilerInstance &Instance) {
1256
96
      std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1257
96
          llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
1258
96
      ModuleMapFile = Instance.getFileManager().getVirtualFile(
1259
96
          FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1260
96
      Instance.getSourceManager().overrideFileContents(
1261
96
          ModuleMapFile, std::move(ModuleMapBuffer));
1262
96
    });
1263
96
  }
1264
1265
  // We've rebuilt a module. If we're allowed to generate or update the global
1266
  // module index, record that fact in the importing compiler instance.
1267
1.59k
  if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
1268
1.06k
    ImportingInstance.setBuildGlobalModuleIndex(true);
1269
1.06k
  }
1270
1271
1.59k
  return Result;
1272
1.59k
}
1273
1274
/// Compile a module in a separate compiler instance and read the AST,
1275
/// returning true if the module compiles without errors.
1276
///
1277
/// Uses a lock file manager and exponential backoff to reduce the chances that
1278
/// multiple instances will compete to create the same module.  On timeout,
1279
/// deletes the lock file in order to avoid deadlock from crashing processes or
1280
/// bugs in the lock file manager.
1281
static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
1282
                                    SourceLocation ImportLoc,
1283
                                    SourceLocation ModuleNameLoc,
1284
1.60k
                                    Module *Module, StringRef ModuleFileName) {
1285
1.60k
  DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1286
1287
27
  auto diagnoseBuildFailure = [&] {
1288
27
    Diags.Report(ModuleNameLoc, diag::err_module_not_built)
1289
27
        << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1290
27
  };
1291
1292
  // FIXME: have LockFileManager return an error_code so that we can
1293
  // avoid the mkdir when the directory already exists.
1294
1.60k
  StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1295
1.60k
  llvm::sys::fs::create_directories(Dir);
1296
1297
1.60k
  while (1) {
1298
1.60k
    unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1299
1.60k
    llvm::LockFileManager Locked(ModuleFileName);
1300
1.60k
    switch (Locked) {
1301
0
    case llvm::LockFileManager::LFS_Error:
1302
      // ModuleCache takes care of correctness and locks are only necessary for
1303
      // performance. Fallback to building the module in case of any lock
1304
      // related errors.
1305
0
      Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
1306
0
          << Module->Name << Locked.getErrorMessage();
1307
      // Clear out any potential leftover.
1308
0
      Locked.unsafeRemoveLockFile();
1309
0
      LLVM_FALLTHROUGH;
1310
1.59k
    case llvm::LockFileManager::LFS_Owned:
1311
      // We're responsible for building the module ourselves.
1312
1.59k
      if (!compileModule(ImportingInstance, ModuleNameLoc, Module,
1313
25
                         ModuleFileName)) {
1314
25
        diagnoseBuildFailure();
1315
25
        return false;
1316
25
      }
1317
1.56k
      break;
1318
1319
8
    case llvm::LockFileManager::LFS_Shared:
1320
      // Someone else is responsible for building the module. Wait for them to
1321
      // finish.
1322
8
      switch (Locked.waitForUnlock()) {
1323
8
      case llvm::LockFileManager::Res_Success:
1324
8
        ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1325
8
        break;
1326
0
      case llvm::LockFileManager::Res_OwnerDied:
1327
0
        continue; // try again to get the lock.
1328
0
      case llvm::LockFileManager::Res_Timeout:
1329
        // Since ModuleCache takes care of correctness, we try waiting for
1330
        // another process to complete the build so clang does not do it done
1331
        // twice. If case of timeout, build it ourselves.
1332
0
        Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1333
0
            << Module->Name;
1334
        // Clear the lock file so that future invocations can make progress.
1335
0
        Locked.unsafeRemoveLockFile();
1336
0
        continue;
1337
8
      }
1338
8
      break;
1339
1.57k
    }
1340
1341
    // Try to read the module file, now that we've compiled it.
1342
1.57k
    ASTReader::ASTReadResult ReadResult =
1343
1.57k
        ImportingInstance.getASTReader()->ReadAST(
1344
1.57k
            ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
1345
1.57k
            ModuleLoadCapabilities);
1346
1347
1.57k
    if (ReadResult == ASTReader::OutOfDate &&
1348
1
        Locked == llvm::LockFileManager::LFS_Shared) {
1349
      // The module may be out of date in the presence of file system races,
1350
      // or if one of its imports depends on header search paths that are not
1351
      // consistent with this ImportingInstance.  Try again...
1352
0
      continue;
1353
1.57k
    } else if (ReadResult == ASTReader::Missing) {
1354
2
      diagnoseBuildFailure();
1355
1.57k
    } else if (ReadResult != ASTReader::Success &&
1356
1
               !Diags.hasErrorOccurred()) {
1357
      // The ASTReader didn't diagnose the error, so conservatively report it.
1358
0
      diagnoseBuildFailure();
1359
0
    }
1360
1.57k
    return ReadResult == ASTReader::Success;
1361
1.57k
  }
1362
1.60k
}
1363
1364
/// Diagnose differences between the current definition of the given
1365
/// configuration macro and the definition provided on the command line.
1366
static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1367
10
                             Module *Mod, SourceLocation ImportLoc) {
1368
10
  IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1369
10
  SourceManager &SourceMgr = PP.getSourceManager();
1370
1371
  // If this identifier has never had a macro definition, then it could
1372
  // not have changed.
1373
10
  if (!Id->hadMacroDefinition())
1374
4
    return;
1375
6
  auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
1376
1377
  // Find the macro definition from the command line.
1378
6
  MacroInfo *CmdLineDefinition = nullptr;
1379
18
  for (auto *MD = LatestLocalMD; MD; 
MD = MD->getPrevious()12
) {
1380
    // We only care about the predefines buffer.
1381
17
    FileID FID = SourceMgr.getFileID(MD->getLocation());
1382
17
    if (FID.isInvalid() || FID != PP.getPredefinesFileID())
1383
12
      continue;
1384
5
    if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1385
5
      CmdLineDefinition = DMD->getMacroInfo();
1386
5
    break;
1387
5
  }
1388
1389
6
  auto *CurrentDefinition = PP.getMacroInfo(Id);
1390
6
  if (CurrentDefinition == CmdLineDefinition) {
1391
    // Macro matches. Nothing to do.
1392
5
  } else if (!CurrentDefinition) {
1393
    // This macro was defined on the command line, then #undef'd later.
1394
    // Complain.
1395
1
    PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1396
1
      << true << ConfigMacro << Mod->getFullModuleName();
1397
1
    auto LatestDef = LatestLocalMD->getDefinition();
1398
1
    assert(LatestDef.isUndefined() &&
1399
1
           "predefined macro went away with no #undef?");
1400
1
    PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1401
1
      << true;
1402
1
    return;
1403
4
  } else if (!CmdLineDefinition) {
1404
    // There was no definition for this macro in the predefines buffer,
1405
    // but there was a local definition. Complain.
1406
1
    PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1407
1
      << false << ConfigMacro << Mod->getFullModuleName();
1408
1
    PP.Diag(CurrentDefinition->getDefinitionLoc(),
1409
1
            diag::note_module_def_undef_here)
1410
1
      << false;
1411
3
  } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1412
1
                                               /*Syntactically=*/true)) {
1413
    // The macro definitions differ.
1414
1
    PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1415
1
      << false << ConfigMacro << Mod->getFullModuleName();
1416
1
    PP.Diag(CurrentDefinition->getDefinitionLoc(),
1417
1
            diag::note_module_def_undef_here)
1418
1
      << false;
1419
1
  }
1420
6
}
1421
1422
/// Write a new timestamp file with the given path.
1423
600
static void writeTimestampFile(StringRef TimestampFile) {
1424
600
  std::error_code EC;
1425
600
  llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
1426
600
}
1427
1428
/// Prune the module cache of modules that haven't been accessed in
1429
/// a long time.
1430
4.23k
static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
1431
4.23k
  llvm::sys::fs::file_status StatBuf;
1432
4.23k
  llvm::SmallString<128> TimestampFile;
1433
4.23k
  TimestampFile = HSOpts.ModuleCachePath;
1434
4.23k
  assert(!TimestampFile.empty());
1435
4.23k
  llvm::sys::path::append(TimestampFile, "modules.timestamp");
1436
1437
  // Try to stat() the timestamp file.
1438
4.23k
  if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) {
1439
    // If the timestamp file wasn't there, create one now.
1440
598
    if (EC == std::errc::no_such_file_or_directory) {
1441
598
      writeTimestampFile(TimestampFile);
1442
598
    }
1443
598
    return;
1444
598
  }
1445
1446
  // Check whether the time stamp is older than our pruning interval.
1447
  // If not, do nothing.
1448
3.63k
  time_t TimeStampModTime =
1449
3.63k
      llvm::sys::toTimeT(StatBuf.getLastModificationTime());
1450
3.63k
  time_t CurrentTime = time(nullptr);
1451
3.63k
  if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
1452
3.63k
    return;
1453
1454
  // Write a new timestamp file so that nobody else attempts to prune.
1455
  // There is a benign race condition here, if two Clang instances happen to
1456
  // notice at the same time that the timestamp is out-of-date.
1457
4
  writeTimestampFile(TimestampFile);
1458
1459
  // Walk the entire module cache, looking for unused module files and module
1460
  // indices.
1461
4
  std::error_code EC;
1462
4
  SmallString<128> ModuleCachePathNative;
1463
4
  llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
1464
4
  for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
1465
9
       Dir != DirEnd && 
!EC5
;
Dir.increment(EC)5
) {
1466
    // If we don't have a directory, there's nothing to look into.
1467
5
    if (!llvm::sys::fs::is_directory(Dir->path()))
1468
2
      continue;
1469
1470
    // Walk all of the files within this directory.
1471
3
    for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1472
11
         File != FileEnd && 
!EC8
;
File.increment(EC)8
) {
1473
      // We only care about module and global module index files.
1474
8
      StringRef Extension = llvm::sys::path::extension(File->path());
1475
8
      if (Extension != ".pcm" && 
Extension != ".timestamp"3
&&
1476
3
          llvm::sys::path::filename(File->path()) != "modules.idx")
1477
0
        continue;
1478
1479
      // Look at this file. If we can't stat it, there's nothing interesting
1480
      // there.
1481
8
      if (llvm::sys::fs::status(File->path(), StatBuf))
1482
0
        continue;
1483
1484
      // If the file has been used recently enough, leave it there.
1485
8
      time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime());
1486
8
      if (CurrentTime - FileAccessTime <=
1487
7
              time_t(HSOpts.ModuleCachePruneAfter)) {
1488
7
        continue;
1489
7
      }
1490
1491
      // Remove the file.
1492
1
      llvm::sys::fs::remove(File->path());
1493
1494
      // Remove the timestamp file.
1495
1
      std::string TimpestampFilename = File->path() + ".timestamp";
1496
1
      llvm::sys::fs::remove(TimpestampFilename);
1497
1
    }
1498
1499
    // If we removed all of the files in the directory, remove the directory
1500
    // itself.
1501
3
    if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1502
0
            llvm::sys::fs::directory_iterator() && !EC)
1503
0
      llvm::sys::fs::remove(Dir->path());
1504
3
  }
1505
4
}
1506
1507
10.8k
void CompilerInstance::createASTReader() {
1508
10.8k
  if (TheASTReader)
1509
1.36k
    return;
1510
1511
9.45k
  if (!hasASTContext())
1512
630
    createASTContext();
1513
1514
  // If we're implicitly building modules but not currently recursively
1515
  // building a module, check whether we need to prune the module cache.
1516
9.45k
  if (getSourceManager().getModuleBuildStack().empty() &&
1517
7.57k
      !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
1518
4.23k
      getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
1519
4.23k
      getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
1520
4.23k
    pruneModuleCache(getHeaderSearchOpts());
1521
4.23k
  }
1522
1523
9.45k
  HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
1524
9.45k
  std::string Sysroot = HSOpts.Sysroot;
1525
9.45k
  const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1526
9.45k
  const FrontendOptions &FEOpts = getFrontendOpts();
1527
9.45k
  std::unique_ptr<llvm::Timer> ReadTimer;
1528
1529
9.45k
  if (FrontendTimerGroup)
1530
12
    ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
1531
12
                                                "Reading modules",
1532
12
                                                *FrontendTimerGroup);
1533
9.45k
  TheASTReader = new ASTReader(
1534
9.45k
      getPreprocessor(), getModuleCache(), &getASTContext(),
1535
9.45k
      getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions,
1536
9.45k
      Sysroot.empty() ? 
""0
: Sysroot.c_str(), PPOpts.DisablePCHValidation,
1537
9.45k
      /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors,
1538
9.45k
      /*AllowConfigurationMismatch=*/false, HSOpts.ModulesValidateSystemHeaders,
1539
9.45k
      HSOpts.ValidateASTInputFilesContent,
1540
9.45k
      getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
1541
9.45k
  if (hasASTConsumer()) {
1542
697
    TheASTReader->setDeserializationListener(
1543
697
        getASTConsumer().GetASTDeserializationListener());
1544
697
    getASTContext().setASTMutationListener(
1545
697
      getASTConsumer().GetASTMutationListener());
1546
697
  }
1547
9.45k
  getASTContext().setExternalSource(TheASTReader);
1548
9.45k
  if (hasSema())
1549
697
    TheASTReader->InitializeSema(getSema());
1550
9.45k
  if (hasASTConsumer())
1551
697
    TheASTReader->StartTranslationUnit(&getASTConsumer());
1552
1553
9.45k
  for (auto &Listener : DependencyCollectors)
1554
634
    Listener->attachToASTReader(*TheASTReader);
1555
9.45k
}
1556
1557
409
bool CompilerInstance::loadModuleFile(StringRef FileName) {
1558
409
  llvm::Timer Timer;
1559
409
  if (FrontendTimerGroup)
1560
0
    Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
1561
0
               *FrontendTimerGroup);
1562
409
  llvm::TimeRegion TimeLoading(FrontendTimerGroup ? 
&Timer0
: nullptr);
1563
1564
  // Helper to recursively read the module names for all modules we're adding.
1565
  // We mark these as known and redirect any attempt to load that module to
1566
  // the files we were handed.
1567
409
  struct ReadModuleNames : ASTReaderListener {
1568
409
    CompilerInstance &CI;
1569
409
    llvm::SmallVector<IdentifierInfo*, 8> LoadedModules;
1570
1571
409
    ReadModuleNames(CompilerInstance &CI) : CI(CI) {}
1572
1573
1.21k
    void ReadModuleName(StringRef ModuleName) override {
1574
1.21k
      LoadedModules.push_back(
1575
1.21k
          CI.getPreprocessor().getIdentifierInfo(ModuleName));
1576
1.21k
    }
1577
1578
393
    void registerAll() {
1579
393
      ModuleMap &MM = CI.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1580
393
      for (auto *II : LoadedModules)
1581
1.19k
        MM.cacheModuleLoad(*II, MM.findModule(II->getName()));
1582
393
      LoadedModules.clear();
1583
393
    }
1584
1585
6
    void markAllUnavailable() {
1586
6
      for (auto *II : LoadedModules) {
1587
6
        if (Module *M = CI.getPreprocessor()
1588
6
                            .getHeaderSearchInfo()
1589
6
                            .getModuleMap()
1590
6
                            .findModule(II->getName())) {
1591
6
          M->HasIncompatibleModuleFile = true;
1592
1593
          // Mark module as available if the only reason it was unavailable
1594
          // was missing headers.
1595
6
          SmallVector<Module *, 2> Stack;
1596
6
          Stack.push_back(M);
1597
14
          while (!Stack.empty()) {
1598
8
            Module *Current = Stack.pop_back_val();
1599
8
            if (Current->IsUnimportable) 
continue0
;
1600
8
            Current->IsAvailable = true;
1601
8
            Stack.insert(Stack.end(),
1602
8
                         Current->submodule_begin(), Current->submodule_end());
1603
8
          }
1604
6
        }
1605
6
      }
1606
6
      LoadedModules.clear();
1607
6
    }
1608
409
  };
1609
1610
  // If we don't already have an ASTReader, create one now.
1611
409
  if (!TheASTReader)
1612
15
    createASTReader();
1613
1614
  // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
1615
  // ASTReader to diagnose it, since it can produce better errors that we can.
1616
409
  bool ConfigMismatchIsRecoverable =
1617
409
      getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch,
1618
409
                                          SourceLocation())
1619
409
        <= DiagnosticsEngine::Warning;
1620
1621
409
  auto Listener = std::make_unique<ReadModuleNames>(*this);
1622
409
  auto &ListenerRef = *Listener;
1623
409
  ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader,
1624
409
                                                   std::move(Listener));
1625
1626
  // Try to load the module file.
1627
409
  switch (TheASTReader->ReadAST(
1628
409
      FileName, serialization::MK_ExplicitModule, SourceLocation(),
1629
406
      ConfigMismatchIsRecoverable ? 
ASTReader::ARR_ConfigurationMismatch3
: 0)) {
1630
393
  case ASTReader::Success:
1631
    // We successfully loaded the module file; remember the set of provided
1632
    // modules so that we don't try to load implicit modules for them.
1633
393
    ListenerRef.registerAll();
1634
393
    return true;
1635
1636
6
  case ASTReader::ConfigurationMismatch:
1637
    // Ignore unusable module files.
1638
6
    getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
1639
6
        << FileName;
1640
    // All modules provided by any files we tried and failed to load are now
1641
    // unavailable; includes of those modules should now be handled textually.
1642
6
    ListenerRef.markAllUnavailable();
1643
6
    return true;
1644
1645
10
  default:
1646
10
    return false;
1647
409
  }
1648
409
}
1649
1650
namespace {
1651
enum ModuleSource {
1652
  MS_ModuleNotFound,
1653
  MS_ModuleCache,
1654
  MS_PrebuiltModulePath,
1655
  MS_ModuleBuildPragma
1656
};
1657
} // end namespace
1658
1659
/// Select a source for loading the named module and compute the filename to
1660
/// load it from.
1661
static ModuleSource selectModuleSource(
1662
    Module *M, StringRef ModuleName, std::string &ModuleFilename,
1663
    const std::map<std::string, std::string, std::less<>> &BuiltModules,
1664
4.98k
    HeaderSearch &HS) {
1665
4.98k
  assert(ModuleFilename.empty() && "Already has a module source?");
1666
1667
  // Check to see if the module has been built as part of this compilation
1668
  // via a module build pragma.
1669
4.98k
  auto BuiltModuleIt = BuiltModules.find(ModuleName);
1670
4.98k
  if (BuiltModuleIt != BuiltModules.end()) {
1671
85
    ModuleFilename = BuiltModuleIt->second;
1672
85
    return MS_ModuleBuildPragma;
1673
85
  }
1674
1675
  // Try to load the module from the prebuilt module path.
1676
4.89k
  const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1677
4.89k
  if (!HSOpts.PrebuiltModuleFiles.empty() ||
1678
4.89k
      !HSOpts.PrebuiltModulePaths.empty()) {
1679
17
    ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName);
1680
17
    if (HSOpts.EnablePrebuiltImplicitModules && 
ModuleFilename.empty()4
)
1681
3
      ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M);
1682
17
    if (!ModuleFilename.empty())
1683
16
      return MS_PrebuiltModulePath;
1684
4.88k
  }
1685
1686
  // Try to load the module from the module cache.
1687
4.88k
  if (M) {
1688
4.85k
    ModuleFilename = HS.getCachedModuleFileName(M);
1689
4.85k
    return MS_ModuleCache;
1690
4.85k
  }
1691
1692
31
  return MS_ModuleNotFound;
1693
31
}
1694
1695
ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST(
1696
    StringRef ModuleName, SourceLocation ImportLoc,
1697
4.98k
    SourceLocation ModuleNameLoc, bool IsInclusionDirective) {
1698
  // Search for a module with the given name.
1699
4.98k
  HeaderSearch &HS = PP->getHeaderSearchInfo();
1700
4.98k
  Module *M = HS.lookupModule(ModuleName, true, !IsInclusionDirective);
1701
1702
  // Select the source and filename for loading the named module.
1703
4.98k
  std::string ModuleFilename;
1704
4.98k
  ModuleSource Source =
1705
4.98k
      selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS);
1706
4.98k
  if (Source == MS_ModuleNotFound) {
1707
    // We can't find a module, error out here.
1708
30
    getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1709
30
        << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1710
30
    ModuleBuildFailed = true;
1711
    // FIXME: Why is this not cached?
1712
30
    return ModuleLoadResult::OtherUncachedFailure;
1713
30
  }
1714
4.95k
  if (ModuleFilename.empty()) {
1715
12
    if (M && M->HasIncompatibleModuleFile) {
1716
      // We tried and failed to load a module file for this module. Fall
1717
      // back to textual inclusion for its headers.
1718
8
      return ModuleLoadResult::ConfigMismatch;
1719
8
    }
1720
1721
4
    getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
1722
4
        << ModuleName;
1723
4
    ModuleBuildFailed = true;
1724
    // FIXME: Why is this not cached?
1725
4
    return ModuleLoadResult::OtherUncachedFailure;
1726
4
  }
1727
1728
  // Create an ASTReader on demand.
1729
4.94k
  if (!getASTReader())
1730
610
    createASTReader();
1731
1732
  // Time how long it takes to load the module.
1733
4.94k
  llvm::Timer Timer;
1734
4.94k
  if (FrontendTimerGroup)
1735
8
    Timer.init("loading." + ModuleFilename, "Loading " + ModuleFilename,
1736
8
               *FrontendTimerGroup);
1737
4.93k
  llvm::TimeRegion TimeLoading(FrontendTimerGroup ? 
&Timer8
: nullptr);
1738
4.94k
  llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
1739
1740
  // Try to load the module file. If we are not trying to load from the
1741
  // module cache, we don't know how to rebuild modules.
1742
4.94k
  unsigned ARRFlags = Source == MS_ModuleCache
1743
4.84k
                          ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing
1744
101
                          : Source == MS_PrebuiltModulePath
1745
16
                                ? 0
1746
85
                                : ASTReader::ARR_ConfigurationMismatch;
1747
4.94k
  switch (getASTReader()->ReadAST(ModuleFilename,
1748
4.94k
                                  Source == MS_PrebuiltModulePath
1749
16
                                      ? serialization::MK_PrebuiltModule
1750
4.92k
                                      : Source == MS_ModuleBuildPragma
1751
85
                                            ? serialization::MK_ExplicitModule
1752
4.84k
                                            : serialization::MK_ImplicitModule,
1753
4.94k
                                  ImportLoc, ARRFlags)) {
1754
3.31k
  case ASTReader::Success: {
1755
3.31k
    if (M)
1756
3.21k
      return M;
1757
93
    assert(Source != MS_ModuleCache &&
1758
93
           "missing module, but file loaded from cache");
1759
1760
    // A prebuilt module is indexed as a ModuleFile; the Module does not exist
1761
    // until the first call to ReadAST.  Look it up now.
1762
93
    M = HS.lookupModule(ModuleName, true, !IsInclusionDirective);
1763
1764
    // Check whether M refers to the file in the prebuilt module path.
1765
93
    if (M && M->getASTFile())
1766
93
      if (auto ModuleFile = FileMgr->getFile(ModuleFilename))
1767
93
        if (*ModuleFile == M->getASTFile())
1768
93
          return M;
1769
1770
0
    ModuleBuildFailed = true;
1771
0
    getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
1772
0
        << ModuleName;
1773
0
    return ModuleLoadResult();
1774
0
  }
1775
1776
1.62k
  case ASTReader::OutOfDate:
1777
1.62k
  case ASTReader::Missing:
1778
    // The most interesting case.
1779
1.62k
    break;
1780
1781
4
  case ASTReader::ConfigurationMismatch:
1782
4
    if (Source == MS_PrebuiltModulePath)
1783
      // FIXME: We shouldn't be setting HadFatalFailure below if we only
1784
      // produce a warning here!
1785
2
      getDiagnostics().Report(SourceLocation(),
1786
2
                              diag::warn_module_config_mismatch)
1787
2
          << ModuleFilename;
1788
    // Fall through to error out.
1789
4
    LLVM_FALLTHROUGH;
1790
4
  case ASTReader::VersionMismatch:
1791
4
  case ASTReader::HadErrors:
1792
    // FIXME: Should this set ModuleBuildFailed = true?
1793
4
    ModuleLoader::HadFatalFailure = true;
1794
    // FIXME: The ASTReader will already have complained, but can we shoehorn
1795
    // that diagnostic information into a more useful form?
1796
4
    return ModuleLoadResult();
1797
1798
3
  case ASTReader::Failure:
1799
    // FIXME: Should this set ModuleBuildFailed = true?
1800
3
    ModuleLoader::HadFatalFailure = true;
1801
3
    return ModuleLoadResult();
1802
1.62k
  }
1803
1804
  // ReadAST returned Missing or OutOfDate.
1805
1.62k
  if (Source != MS_ModuleCache) {
1806
    // We don't know the desired configuration for this module and don't
1807
    // necessarily even have a module map. Since ReadAST already produces
1808
    // diagnostics for these two cases, we simply error out here.
1809
0
    ModuleBuildFailed = true;
1810
0
    return ModuleLoadResult();
1811
0
  }
1812
1813
  // The module file is missing or out-of-date. Build it.
1814
1.62k
  assert(M && "missing module, but trying to compile for cache");
1815
1816
  // Check whether there is a cycle in the module graph.
1817
1.62k
  ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
1818
1.62k
  ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1819
2.44k
  for (; Pos != PosEnd; 
++Pos817
) {
1820
821
    if (Pos->first == ModuleName)
1821
4
      break;
1822
821
  }
1823
1824
1.62k
  if (Pos != PosEnd) {
1825
4
    SmallString<256> CyclePath;
1826
12
    for (; Pos != PosEnd; 
++Pos8
) {
1827
8
      CyclePath += Pos->first;
1828
8
      CyclePath += " -> ";
1829
8
    }
1830
4
    CyclePath += ModuleName;
1831
1832
4
    getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1833
4
        << ModuleName << CyclePath;
1834
    // FIXME: Should this set ModuleBuildFailed = true?
1835
    // FIXME: Why is this not cached?
1836
4
    return ModuleLoadResult::OtherUncachedFailure;
1837
4
  }
1838
1839
  // Check whether we have already attempted to build this module (but
1840
  // failed).
1841
1.61k
  if (getPreprocessorOpts().FailedModules &&
1842
837
      getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
1843
19
    getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1844
19
        << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1845
19
    ModuleBuildFailed = true;
1846
    // FIXME: Why is this not cached?
1847
19
    return ModuleLoadResult::OtherUncachedFailure;
1848
19
  }
1849
1850
  // Try to compile and then read the AST.
1851
1.60k
  if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M,
1852
28
                               ModuleFilename)) {
1853
28
    assert(getDiagnostics().hasErrorOccurred() &&
1854
28
           "undiagnosed error in compileModuleAndReadAST");
1855
28
    if (getPreprocessorOpts().FailedModules)
1856
28
      getPreprocessorOpts().FailedModules->addFailed(ModuleName);
1857
28
    ModuleBuildFailed = true;
1858
    // FIXME: Why is this not cached?
1859
28
    return ModuleLoadResult::OtherUncachedFailure;
1860
28
  }
1861
1862
  // Okay, we've rebuilt and now loaded the module.
1863
1.57k
  return M;
1864
1.57k
}
1865
1866
ModuleLoadResult
1867
CompilerInstance::loadModule(SourceLocation ImportLoc,
1868
                             ModuleIdPath Path,
1869
                             Module::NameVisibilityKind Visibility,
1870
16.6k
                             bool IsInclusionDirective) {
1871
  // Determine what file we're searching from.
1872
16.6k
  StringRef ModuleName = Path[0].first->getName();
1873
16.6k
  SourceLocation ModuleNameLoc = Path[0].second;
1874
1875
  // If we've already handled this import, just return the cached result.
1876
  // This one-element cache is important to eliminate redundant diagnostics
1877
  // when both the preprocessor and parser see the same import declaration.
1878
16.6k
  if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
1879
    // Make the named module visible.
1880
1.74k
    if (LastModuleImportResult && 
ModuleName != getLangOpts().CurrentModule1.69k
)
1881
1.68k
      TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility,
1882
1.68k
                                      ImportLoc);
1883
1.74k
    return LastModuleImportResult;
1884
1.74k
  }
1885
1886
  // If we don't already have information on this module, load the module now.
1887
14.8k
  Module *Module = nullptr;
1888
14.8k
  ModuleMap &MM = getPreprocessor().getHeaderSearchInfo().getModuleMap();
1889
14.8k
  if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].first)) {
1890
    // Use the cached result, which may be nullptr.
1891
9.87k
    Module = *MaybeModule;
1892
4.99k
  } else if (ModuleName == getLangOpts().CurrentModule) {
1893
    // This is the module we're building.
1894
14
    Module = PP->getHeaderSearchInfo().lookupModule(
1895
14
        ModuleName, /*AllowSearch*/ true,
1896
14
        /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
1897
    /// FIXME: perhaps we should (a) look for a module using the module name
1898
    //  to file map (PrebuiltModuleFiles) and (b) diagnose if still not found?
1899
    //if (Module == nullptr) {
1900
    //  getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1901
    //    << ModuleName;
1902
    //  ModuleBuildFailed = true;
1903
    //  return ModuleLoadResult();
1904
    //}
1905
14
    MM.cacheModuleLoad(*Path[0].first, Module);
1906
4.98k
  } else {
1907
4.98k
    ModuleLoadResult Result = findOrCompileModuleAndReadAST(
1908
4.98k
        ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective);
1909
    // FIXME: Can we pull 'ModuleBuildFailed = true' out of the return
1910
    // sequences for findOrCompileModuleAndReadAST and do it here (as long as
1911
    // the result is not a config mismatch)?  See FIXMEs there.
1912
4.98k
    if (!Result.isNormal())
1913
93
      return Result;
1914
4.89k
    Module = Result;
1915
4.89k
    MM.cacheModuleLoad(*Path[0].first, Module);
1916
4.89k
    if (!Module)
1917
7
      return Module;
1918
14.7k
  }
1919
1920
  // If we never found the module, fail.  Otherwise, verify the module and link
1921
  // it up.
1922
14.7k
  if (!Module)
1923
2
    return ModuleLoadResult();
1924
1925
  // Verify that the rest of the module path actually corresponds to
1926
  // a submodule.
1927
14.7k
  bool MapPrivateSubModToTopLevel = false;
1928
14.7k
  if (Path.size() > 1) {
1929
20.8k
    for (unsigned I = 1, N = Path.size(); I != N; 
++I12.0k
) {
1930
12.0k
      StringRef Name = Path[I].first->getName();
1931
12.0k
      clang::Module *Sub = Module->findSubmodule(Name);
1932
1933
      // If the user is requesting Foo.Private and it doesn't exist, try to
1934
      // match Foo_Private and emit a warning asking for the user to write
1935
      // @import Foo_Private instead. FIXME: remove this when existing clients
1936
      // migrate off of Foo.Private syntax.
1937
12.0k
      if (!Sub && 
PP->getLangOpts().ImplicitModules11
&&
Name == "Private"11
&&
1938
3
          Module == Module->getTopLevelModule()) {
1939
3
        SmallString<128> PrivateModule(Module->Name);
1940
3
        PrivateModule.append("_Private");
1941
1942
3
        SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> PrivPath;
1943
3
        auto &II = PP->getIdentifierTable().get(
1944
3
            PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
1945
3
        PrivPath.push_back(std::make_pair(&II, Path[0].second));
1946
1947
3
        if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, true,
1948
3
                                                   !IsInclusionDirective))
1949
2
          Sub =
1950
2
              loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
1951
3
        if (Sub) {
1952
2
          MapPrivateSubModToTopLevel = true;
1953
2
          if (!getDiagnostics().isIgnored(
1954
1
                  diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
1955
1
            getDiagnostics().Report(Path[I].second,
1956
1
                                    diag::warn_no_priv_submodule_use_toplevel)
1957
1
                << Path[I].first << Module->getFullModuleName() << PrivateModule
1958
1
                << SourceRange(Path[0].second, Path[I].second)
1959
1
                << FixItHint::CreateReplacement(SourceRange(Path[0].second),
1960
1
                                                PrivateModule);
1961
1
            getDiagnostics().Report(Sub->DefinitionLoc,
1962
1
                                    diag::note_private_top_level_defined);
1963
1
          }
1964
2
        }
1965
3
      }
1966
1967
12.0k
      if (!Sub) {
1968
        // Attempt to perform typo correction to find a module name that works.
1969
9
        SmallVector<StringRef, 2> Best;
1970
9
        unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1971
1972
9
        for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1973
9
                                            JEnd = Module->submodule_end();
1974
19
             J != JEnd; 
++J10
) {
1975
10
          unsigned ED = Name.edit_distance((*J)->Name,
1976
10
                                           /*AllowReplacements=*/true,
1977
10
                                           BestEditDistance);
1978
10
          if (ED <= BestEditDistance) {
1979
8
            if (ED < BestEditDistance) {
1980
6
              Best.clear();
1981
6
              BestEditDistance = ED;
1982
6
            }
1983
1984
8
            Best.push_back((*J)->Name);
1985
8
          }
1986
10
        }
1987
1988
        // If there was a clear winner, user it.
1989
9
        if (Best.size() == 1) {
1990
2
          getDiagnostics().Report(Path[I].second,
1991
2
                                  diag::err_no_submodule_suggest)
1992
2
            << Path[I].first << Module->getFullModuleName() << Best[0]
1993
2
            << SourceRange(Path[0].second, Path[I-1].second)
1994
2
            << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1995
2
                                            Best[0]);
1996
1997
2
          Sub = Module->findSubmodule(Best[0]);
1998
2
        }
1999
9
      }
2000
2001
12.0k
      if (!Sub) {
2002
        // No submodule by this name. Complain, and don't look for further
2003
        // submodules.
2004
7
        getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
2005
7
          << Path[I].first << Module->getFullModuleName()
2006
7
          << SourceRange(Path[0].second, Path[I-1].second);
2007
7
        break;
2008
7
      }
2009
2010
12.0k
      Module = Sub;
2011
12.0k
    }
2012
8.78k
  }
2013
2014
  // Make the named module visible, if it's not already part of the module
2015
  // we are parsing.
2016
14.7k
  if (ModuleName != getLangOpts().CurrentModule) {
2017
14.7k
    if (!Module->IsFromModuleFile && 
!MapPrivateSubModToTopLevel4
) {
2018
      // We have an umbrella header or directory that doesn't actually include
2019
      // all of the headers within the directory it covers. Complain about
2020
      // this missing submodule and recover by forgetting that we ever saw
2021
      // this submodule.
2022
      // FIXME: Should we detect this at module load time? It seems fairly
2023
      // expensive (and rare).
2024
4
      getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
2025
4
        << Module->getFullModuleName()
2026
4
        << SourceRange(Path.front().second, Path.back().second);
2027
2028
4
      return ModuleLoadResult::MissingExpected;
2029
4
    }
2030
2031
    // Check whether this module is available.
2032
14.7k
    if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(),
2033
58
                                             getDiagnostics(), Module)) {
2034
58
      getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
2035
58
        << SourceRange(Path.front().second, Path.back().second);
2036
58
      LastModuleImportLoc = ImportLoc;
2037
58
      LastModuleImportResult = ModuleLoadResult();
2038
58
      return ModuleLoadResult();
2039
58
    }
2040
2041
14.6k
    TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc);
2042
14.6k
  }
2043
2044
  // Check for any configuration macros that have changed.
2045
14.7k
  clang::Module *TopModule = Module->getTopLevelModule();
2046
14.7k
  for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; 
++I10
) {
2047
10
    checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
2048
10
                     Module, ImportLoc);
2049
10
  }
2050
2051
  // Resolve any remaining module using export_as for this one.
2052
14.7k
  getPreprocessor()
2053
14.7k
      .getHeaderSearchInfo()
2054
14.7k
      .getModuleMap()
2055
14.7k
      .resolveLinkAsDependencies(TopModule);
2056
2057
14.7k
  LastModuleImportLoc = ImportLoc;
2058
14.7k
  LastModuleImportResult = ModuleLoadResult(Module);
2059
14.7k
  return LastModuleImportResult;
2060
14.7k
}
2061
2062
void CompilerInstance::createModuleFromSource(SourceLocation ImportLoc,
2063
                                              StringRef ModuleName,
2064
76
                                              StringRef Source) {
2065
  // Avoid creating filenames with special characters.
2066
76
  SmallString<128> CleanModuleName(ModuleName);
2067
76
  for (auto &C : CleanModuleName)
2068
220
    if (!isAlphanumeric(C))
2069
10
      C = '_';
2070
2071
  // FIXME: Using a randomized filename here means that our intermediate .pcm
2072
  // output is nondeterministic (as .pcm files refer to each other by name).
2073
  // Can this affect the output in any way?
2074
76
  SmallString<128> ModuleFileName;
2075
76
  if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2076
0
          CleanModuleName, "pcm", ModuleFileName)) {
2077
0
    getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
2078
0
        << ModuleFileName << EC.message();
2079
0
    return;
2080
0
  }
2081
76
  std::string ModuleMapFileName = (CleanModuleName + ".map").str();
2082
2083
76
  FrontendInputFile Input(
2084
76
      ModuleMapFileName,
2085
76
      InputKind(getLanguageFromOptions(*Invocation->getLangOpts()),
2086
76
                InputKind::ModuleMap, /*Preprocessed*/true));
2087
2088
76
  std::string NullTerminatedSource(Source.str());
2089
2090
76
  auto PreBuildStep = [&](CompilerInstance &Other) {
2091
    // Create a virtual file containing our desired source.
2092
    // FIXME: We shouldn't need to do this.
2093
76
    const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile(
2094
76
        ModuleMapFileName, NullTerminatedSource.size(), 0);
2095
76
    Other.getSourceManager().overrideFileContents(
2096
76
        ModuleMapFile,
2097
76
        llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource.c_str()));
2098
2099
76
    Other.BuiltModules = std::move(BuiltModules);
2100
76
    Other.DeleteBuiltModules = false;
2101
76
  };
2102
2103
76
  auto PostBuildStep = [this](CompilerInstance &Other) {
2104
76
    BuiltModules = std::move(Other.BuiltModules);
2105
76
  };
2106
2107
  // Build the module, inheriting any modules that we've built locally.
2108
76
  if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(),
2109
75
                        ModuleFileName, PreBuildStep, PostBuildStep)) {
2110
75
    BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName.str());
2111
75
    llvm::sys::RemoveFileOnSignal(ModuleFileName);
2112
75
  }
2113
76
}
2114
2115
void CompilerInstance::makeModuleVisible(Module *Mod,
2116
                                         Module::NameVisibilityKind Visibility,
2117
81.7k
                                         SourceLocation ImportLoc) {
2118
81.7k
  if (!TheASTReader)
2119
13
    createASTReader();
2120
81.7k
  if (!TheASTReader)
2121
0
    return;
2122
2123
81.7k
  TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc);
2124
81.7k
}
2125
2126
GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
2127
1
    SourceLocation TriggerLoc) {
2128
1
  if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
2129
0
    return nullptr;
2130
1
  if (!TheASTReader)
2131
0
    createASTReader();
2132
  // Can't do anything if we don't have the module manager.
2133
1
  if (!TheASTReader)
2134
0
    return nullptr;
2135
  // Get an existing global index.  This loads it if not already
2136
  // loaded.
2137
1
  TheASTReader->loadGlobalIndex();
2138
1
  GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex();
2139
  // If the global index doesn't exist, create it.
2140
1
  if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
2141
1
      hasPreprocessor()) {
2142
1
    llvm::sys::fs::create_directories(
2143
1
      getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
2144
1
    if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2145
0
            getFileManager(), getPCHContainerReader(),
2146
0
            getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2147
      // FIXME this drops the error on the floor. This code is only used for
2148
      // typo correction and drops more than just this one source of errors
2149
      // (such as the directory creation failure above). It should handle the
2150
      // error.
2151
0
      consumeError(std::move(Err));
2152
0
      return nullptr;
2153
0
    }
2154
1
    TheASTReader->resetForReload();
2155
1
    TheASTReader->loadGlobalIndex();
2156
1
    GlobalIndex = TheASTReader->getGlobalIndex();
2157
1
  }
2158
  // For finding modules needing to be imported for fixit messages,
2159
  // we need to make the global index cover all modules, so we do that here.
2160
1
  if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
2161
1
    ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
2162
1
    bool RecreateIndex = false;
2163
1
    for (ModuleMap::module_iterator I = MMap.module_begin(),
2164
3
        E = MMap.module_end(); I != E; 
++I2
) {
2165
2
      Module *TheModule = I->second;
2166
2
      const FileEntry *Entry = TheModule->getASTFile();
2167
2
      if (!Entry) {
2168
1
        SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2169
1
        Path.push_back(std::make_pair(
2170
1
            getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
2171
1
        std::reverse(Path.begin(), Path.end());
2172
        // Load a module as hidden.  This also adds it to the global index.
2173
1
        loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
2174
1
        RecreateIndex = true;
2175
1
      }
2176
2
    }
2177
1
    if (RecreateIndex) {
2178
1
      if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2179
0
              getFileManager(), getPCHContainerReader(),
2180
0
              getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2181
        // FIXME As above, this drops the error on the floor.
2182
0
        consumeError(std::move(Err));
2183
0
        return nullptr;
2184
0
      }
2185
1
      TheASTReader->resetForReload();
2186
1
      TheASTReader->loadGlobalIndex();
2187
1
      GlobalIndex = TheASTReader->getGlobalIndex();
2188
1
    }
2189
1
    HaveFullGlobalModuleIndex = true;
2190
1
  }
2191
1
  return GlobalIndex;
2192
1
}
2193
2194
// Check global module index for missing imports.
2195
bool
2196
CompilerInstance::lookupMissingImports(StringRef Name,
2197
6
                                       SourceLocation TriggerLoc) {
2198
  // Look for the symbol in non-imported modules, but only if an error
2199
  // actually occurred.
2200
6
  if (!buildingModule()) {
2201
    // Load global module index, or retrieve a previously loaded one.
2202
1
    GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
2203
1
      TriggerLoc);
2204
2205
    // Only if we have a global index.
2206
1
    if (GlobalIndex) {
2207
1
      GlobalModuleIndex::HitSet FoundModules;
2208
2209
      // Find the modules that reference the identifier.
2210
      // Note that this only finds top-level modules.
2211
      // We'll let diagnoseTypo find the actual declaration module.
2212
1
      if (GlobalIndex->lookupIdentifier(Name, FoundModules))
2213
1
        return true;
2214
5
    }
2215
1
  }
2216
2217
5
  return false;
2218
5
}
2219
8.18k
void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
2220
2221
void CompilerInstance::setExternalSemaSource(
2222
1
    IntrusiveRefCntPtr<ExternalSemaSource> ESS) {
2223
1
  ExternalSemaSrc = std::move(ESS);
2224
1
}