Coverage Report

Created: 2021-06-15 06:44

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