Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Frontend/ChainedIncludesSource.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ChainedIncludesSource.cpp - Chained PCHs in Memory -------*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file defines the ChainedIncludesSource class, which converts headers
10
//  to chained PCHs in memory, mainly used for testing.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Basic/TargetInfo.h"
15
#include "clang/Frontend/ASTUnit.h"
16
#include "clang/Frontend/CompilerInstance.h"
17
#include "clang/Frontend/TextDiagnosticPrinter.h"
18
#include "clang/Lex/Preprocessor.h"
19
#include "clang/Lex/PreprocessorOptions.h"
20
#include "clang/Parse/ParseAST.h"
21
#include "clang/Sema/MultiplexExternalSemaSource.h"
22
#include "clang/Serialization/ASTReader.h"
23
#include "clang/Serialization/ASTWriter.h"
24
#include "llvm/Support/MemoryBuffer.h"
25
26
using namespace clang;
27
28
namespace {
29
class ChainedIncludesSourceImpl : public ExternalSemaSource {
30
public:
31
  ChainedIncludesSourceImpl(std::vector<std::unique_ptr<CompilerInstance>> CIs)
32
27
      : CIs(std::move(CIs)) {}
33
34
protected:
35
  //===----------------------------------------------------------------------===//
36
  // ExternalASTSource interface.
37
  //===----------------------------------------------------------------------===//
38
39
  /// Return the amount of memory used by memory buffers, breaking down
40
  /// by heap-backed versus mmap'ed memory.
41
0
  void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override {
42
0
    for (unsigned i = 0, e = CIs.size(); i != e; ++i) {
43
0
      if (const ExternalASTSource *eSrc =
44
0
          CIs[i]->getASTContext().getExternalSource()) {
45
0
        eSrc->getMemoryBufferSizes(sizes);
46
0
      }
47
0
    }
48
0
  }
49
50
private:
51
  std::vector<std::unique_ptr<CompilerInstance>> CIs;
52
};
53
54
/// Members of ChainedIncludesSource, factored out so we can initialize
55
/// them before we initialize the ExternalSemaSource base class.
56
struct ChainedIncludesSourceMembers {
57
  ChainedIncludesSourceMembers(
58
      std::vector<std::unique_ptr<CompilerInstance>> CIs,
59
      IntrusiveRefCntPtr<ExternalSemaSource> FinalReader)
60
27
      : Impl(std::move(CIs)), FinalReader(std::move(FinalReader)) {}
61
  ChainedIncludesSourceImpl Impl;
62
  IntrusiveRefCntPtr<ExternalSemaSource> FinalReader;
63
};
64
65
/// Use MultiplexExternalSemaSource to dispatch all ExternalSemaSource
66
/// calls to the final reader.
67
class ChainedIncludesSource
68
    : private ChainedIncludesSourceMembers,
69
      public MultiplexExternalSemaSource {
70
public:
71
  ChainedIncludesSource(std::vector<std::unique_ptr<CompilerInstance>> CIs,
72
                        IntrusiveRefCntPtr<ExternalSemaSource> FinalReader)
73
      : ChainedIncludesSourceMembers(std::move(CIs), std::move(FinalReader)),
74
27
        MultiplexExternalSemaSource(Impl, *this->FinalReader) {}
75
};
76
}
77
78
static ASTReader *
79
createASTReader(CompilerInstance &CI, StringRef pchFile,
80
                SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>> &MemBufs,
81
                SmallVectorImpl<std::string> &bufNames,
82
51
                ASTDeserializationListener *deserialListener = nullptr) {
83
51
  Preprocessor &PP = CI.getPreprocessor();
84
51
  std::unique_ptr<ASTReader> Reader;
85
51
  Reader.reset(new ASTReader(PP, CI.getModuleCache(), &CI.getASTContext(),
86
51
                             CI.getPCHContainerReader(),
87
51
                             /*Extensions=*/{},
88
51
                             /*isysroot=*/"", /*DisableValidation=*/true));
89
126
  for (unsigned ti = 0; ti < bufNames.size(); 
++ti75
) {
90
75
    StringRef sr(bufNames[ti]);
91
75
    Reader->addInMemoryBuffer(sr, std::move(MemBufs[ti]));
92
75
  }
93
51
  Reader->setDeserializationListener(deserialListener);
94
51
  switch (Reader->ReadAST(pchFile, serialization::MK_PCH, SourceLocation(),
95
51
                          ASTReader::ARR_None)) {
96
51
  case ASTReader::Success:
97
51
    // Set the predefines buffer as suggested by the PCH reader.
98
51
    PP.setPredefines(Reader->getSuggestedPredefines());
99
51
    return Reader.release();
100
51
101
51
  case ASTReader::Failure:
102
0
  case ASTReader::Missing:
103
0
  case ASTReader::OutOfDate:
104
0
  case ASTReader::VersionMismatch:
105
0
  case ASTReader::ConfigurationMismatch:
106
0
  case ASTReader::HadErrors:
107
0
    break;
108
0
  }
109
0
  return nullptr;
110
0
}
111
112
IntrusiveRefCntPtr<ExternalSemaSource> clang::createChainedIncludesSource(
113
27
    CompilerInstance &CI, IntrusiveRefCntPtr<ExternalSemaSource> &Reader) {
114
27
115
27
  std::vector<std::string> &includes = CI.getPreprocessorOpts().ChainedIncludes;
116
27
  assert(!includes.empty() && "No '-chain-include' in options!");
117
27
118
27
  std::vector<std::unique_ptr<CompilerInstance>> CIs;
119
27
  InputKind IK = CI.getFrontendOpts().Inputs[0].getKind();
120
27
121
27
  SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> SerialBufs;
122
27
  SmallVector<std::string, 4> serialBufNames;
123
27
124
78
  for (unsigned i = 0, e = includes.size(); i != e; 
++i51
) {
125
51
    bool firstInclude = (i == 0);
126
51
    std::unique_ptr<CompilerInvocation> CInvok;
127
51
    CInvok.reset(new CompilerInvocation(CI.getInvocation()));
128
51
129
51
    CInvok->getPreprocessorOpts().ChainedIncludes.clear();
130
51
    CInvok->getPreprocessorOpts().ImplicitPCHInclude.clear();
131
51
    CInvok->getPreprocessorOpts().DisablePCHValidation = true;
132
51
    CInvok->getPreprocessorOpts().Includes.clear();
133
51
    CInvok->getPreprocessorOpts().MacroIncludes.clear();
134
51
    CInvok->getPreprocessorOpts().Macros.clear();
135
51
136
51
    CInvok->getFrontendOpts().Inputs.clear();
137
51
    FrontendInputFile InputFile(includes[i], IK);
138
51
    CInvok->getFrontendOpts().Inputs.push_back(InputFile);
139
51
140
51
    TextDiagnosticPrinter *DiagClient =
141
51
      new TextDiagnosticPrinter(llvm::errs(), new DiagnosticOptions());
142
51
    IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
143
51
    IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
144
51
        new DiagnosticsEngine(DiagID, &CI.getDiagnosticOpts(), DiagClient));
145
51
146
51
    std::unique_ptr<CompilerInstance> Clang(
147
51
        new CompilerInstance(CI.getPCHContainerOperations()));
148
51
    Clang->setInvocation(std::move(CInvok));
149
51
    Clang->setDiagnostics(Diags.get());
150
51
    Clang->setTarget(TargetInfo::CreateTargetInfo(
151
51
        Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
152
51
    Clang->createFileManager();
153
51
    Clang->createSourceManager(Clang->getFileManager());
154
51
    Clang->createPreprocessor(TU_Prefix);
155
51
    Clang->getDiagnosticClient().BeginSourceFile(Clang->getLangOpts(),
156
51
                                                 &Clang->getPreprocessor());
157
51
    Clang->createASTContext();
158
51
159
51
    auto Buffer = std::make_shared<PCHBuffer>();
160
51
    ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions;
161
51
    auto consumer = llvm::make_unique<PCHGenerator>(
162
51
        Clang->getPreprocessor(), Clang->getModuleCache(), "-", /*isysroot=*/"",
163
51
        Buffer, Extensions, /*AllowASTWithErrors=*/true);
164
51
    Clang->getASTContext().setASTMutationListener(
165
51
                                            consumer->GetASTMutationListener());
166
51
    Clang->setASTConsumer(std::move(consumer));
167
51
    Clang->createSema(TU_Prefix, nullptr);
168
51
169
51
    if (firstInclude) {
170
27
      Preprocessor &PP = Clang->getPreprocessor();
171
27
      PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
172
27
                                             PP.getLangOpts());
173
27
    } else {
174
24
      assert(!SerialBufs.empty());
175
24
      SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> Bufs;
176
24
      // TODO: Pass through the existing MemoryBuffer instances instead of
177
24
      // allocating new ones.
178
24
      for (auto &SB : SerialBufs)
179
24
        Bufs.push_back(llvm::MemoryBuffer::getMemBuffer(SB->getBuffer()));
180
24
      std::string pchName = includes[i-1];
181
24
      llvm::raw_string_ostream os(pchName);
182
24
      os << ".pch" << i-1;
183
24
      serialBufNames.push_back(os.str());
184
24
185
24
      IntrusiveRefCntPtr<ASTReader> Reader;
186
24
      Reader = createASTReader(
187
24
          *Clang, pchName, Bufs, serialBufNames,
188
24
          Clang->getASTConsumer().GetASTDeserializationListener());
189
24
      if (!Reader)
190
0
        return nullptr;
191
24
      Clang->setModuleManager(Reader);
192
24
      Clang->getASTContext().setExternalSource(Reader);
193
24
    }
194
51
195
51
    if (!Clang->InitializeSourceManager(InputFile))
196
0
      return nullptr;
197
51
198
51
    ParseAST(Clang->getSema());
199
51
    Clang->getDiagnosticClient().EndSourceFile();
200
51
    assert(Buffer->IsComplete && "serialization did not complete");
201
51
    auto &serialAST = Buffer->Data;
202
51
    SerialBufs.push_back(llvm::MemoryBuffer::getMemBufferCopy(
203
51
        StringRef(serialAST.data(), serialAST.size())));
204
51
    serialAST.clear();
205
51
    CIs.push_back(std::move(Clang));
206
51
  }
207
27
208
27
  assert(!SerialBufs.empty());
209
27
  std::string pchName = includes.back() + ".pch-final";
210
27
  serialBufNames.push_back(pchName);
211
27
  Reader = createASTReader(CI, pchName, SerialBufs, serialBufNames);
212
27
  if (!Reader)
213
0
    return nullptr;
214
27
215
27
  return IntrusiveRefCntPtr<ChainedIncludesSource>(
216
27
      new ChainedIncludesSource(std::move(CIs), Reader));
217
27
}