blob: dad8a1e1cd42fe189dc3b3c0745cb3e7817f2317 [file] [log] [blame]
Josh Gaob5c49632016-11-08 22:21:31 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "Driver.h"
18
19#include <err.h>
20#include <string.h>
21
22#include <chrono>
23#include <mutex>
24#include <string>
25#include <thread>
26#include <unordered_map>
27#include <vector>
28
29#include <clang/AST/ASTConsumer.h>
30#include <clang/Basic/Diagnostic.h>
31#include <clang/Basic/TargetInfo.h>
32#include <clang/Driver/Compilation.h>
33#include <clang/Driver/Driver.h>
34#include <clang/Frontend/CompilerInstance.h>
35#include <clang/Frontend/CompilerInvocation.h>
36#include <clang/Frontend/FrontendAction.h>
37#include <clang/Frontend/FrontendActions.h>
38#include <clang/Frontend/TextDiagnosticPrinter.h>
39#include <clang/Frontend/Utils.h>
40#include <clang/FrontendTool/Utils.h>
41#include <llvm/ADT/IntrusiveRefCntPtr.h>
42#include <llvm/ADT/SmallVector.h>
43#include <llvm/ADT/StringRef.h>
44
45#include "Arch.h"
46#include "DeclarationDatabase.h"
47#include "versioner.h"
48
49using namespace std::chrono_literals;
50using namespace std::string_literals;
51
52using namespace clang;
53
54class VersionerASTConsumer : public clang::ASTConsumer {
55 public:
56 HeaderDatabase* header_database;
57 CompilationType type;
58
59 VersionerASTConsumer(HeaderDatabase* header_database, CompilationType type)
60 : header_database(header_database), type(type) {
61 }
62
63 virtual void HandleTranslationUnit(ASTContext& ctx) override {
64 header_database->parseAST(type, ctx);
65 }
66};
67
68class VersionerASTAction : public clang::ASTFrontendAction {
69 public:
70 HeaderDatabase* header_database;
71 CompilationType type;
72
73 VersionerASTAction(HeaderDatabase* header_database, CompilationType type)
74 : header_database(header_database), type(type) {
75 }
76
77 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance&, llvm::StringRef) override {
78 return std::make_unique<VersionerASTConsumer>(header_database, type);
79 }
80};
81
82static IntrusiveRefCntPtr<DiagnosticsEngine> constructDiags() {
83 IntrusiveRefCntPtr<DiagnosticOptions> diag_opts(new DiagnosticOptions());
84 auto diag_printer = std::make_unique<TextDiagnosticPrinter>(llvm::errs(), diag_opts.get());
85 IntrusiveRefCntPtr<DiagnosticIDs> diag_ids(new DiagnosticIDs());
86 IntrusiveRefCntPtr<DiagnosticsEngine> diags(
87 new DiagnosticsEngine(diag_ids.get(), diag_opts.get(), diag_printer.release()));
88 return diags;
89}
90
91// clang's driver is slow compared to the work it performs to compile our headers.
92// Run it once to generate flags for each target, and memoize the results.
93static std::unordered_map<CompilationType, std::vector<std::string>> cc1_flags;
94static const char* filename_placeholder = "__VERSIONER_PLACEHOLDER__";
95static void generateTargetCC1Flags(CompilationType type,
96 const std::vector<std::string>& include_dirs) {
97 std::vector<std::string> cmd = { "versioner" };
98 cmd.push_back("-std=c11");
99 cmd.push_back("-x");
100 cmd.push_back("c-header");
101 cmd.push_back("-fsyntax-only");
102
103 cmd.push_back("-Wall");
104 cmd.push_back("-Wextra");
105 cmd.push_back("-Werror");
106 cmd.push_back("-Wundef");
107 cmd.push_back("-Wno-unused-macros");
108 cmd.push_back("-Wno-unused-function");
109 cmd.push_back("-Wno-unused-variable");
110 cmd.push_back("-Wno-unknown-attributes");
111 cmd.push_back("-Wno-pragma-once-outside-header");
112
113 cmd.push_back("-target");
114 cmd.push_back(arch_targets[type.arch]);
115
116 cmd.push_back("-DANDROID");
117 cmd.push_back("-D__ANDROID_API__="s + std::to_string(type.api_level));
118 cmd.push_back("-D_FORTIFY_SOURCE=2");
119 cmd.push_back("-D_GNU_SOURCE");
120 cmd.push_back("-D_FILE_OFFSET_BITS="s + std::to_string(type.file_offset_bits));
121
122 cmd.push_back("-nostdinc");
123
124 if (add_include) {
125 const char* top = getenv("ANDROID_BUILD_TOP");
126 if (!top) {
127 errx(1, "-i passed, but ANDROID_BUILD_TOP is unset");
128 }
129 cmd.push_back("-include");
130 cmd.push_back(to_string(top) + "/bionic/libc/include/android/versioning.h");
131 }
132
133 for (const auto& dir : include_dirs) {
134 cmd.push_back("-isystem");
135 cmd.push_back(dir);
136 }
137
138 cmd.push_back(filename_placeholder);
139
140 auto diags = constructDiags();
141 driver::Driver driver("versioner", llvm::sys::getDefaultTargetTriple(), *diags);
142 driver.setCheckInputsExist(false);
143
144 llvm::SmallVector<const char*, 32> driver_args;
145 for (const std::string& str : cmd) {
146 driver_args.push_back(str.c_str());
147 }
148
149 std::unique_ptr<driver::Compilation> Compilation(driver.BuildCompilation(driver_args));
150 const driver::JobList& jobs = Compilation->getJobs();
151 if (jobs.size() != 1) {
152 errx(1, "driver returned %zu jobs for %s", jobs.size(), to_string(type).c_str());
153 }
154
155 const driver::Command& driver_cmd = llvm::cast<driver::Command>(*jobs.begin());
156 const driver::ArgStringList& cc_args = driver_cmd.getArguments();
157
158 if (cc_args.size() == 0) {
159 errx(1, "driver returned empty command for %s", to_string(type).c_str());
160 }
161
162 std::vector<std::string> result(cc_args.begin(), cc_args.end());
163
164 {
165 static std::mutex cc1_init_mutex;
166 std::unique_lock<std::mutex> lock(cc1_init_mutex);
167 if (cc1_flags.count(type) > 0) {
168 errx(1, "attemped to generate cc1 flags for existing CompilationType %s",
169 to_string(type).c_str());
170 }
171
172 cc1_flags.emplace(std::make_pair(type, std::move(result)));
173 }
174}
175
176static std::vector<const char*> getCC1Command(CompilationType type, const std::string& filename) {
177 const auto& target_flag_it = cc1_flags.find(type);
178 if (target_flag_it == cc1_flags.end()) {
179 errx(1, "failed to find target flags for CompilationType %s", to_string(type).c_str());
180 }
181
182 std::vector<const char*> result;
183 for (const std::string& flag : target_flag_it->second) {
184 if (flag == "-disable-free") {
185 continue;
186 } else if (flag == filename_placeholder) {
187 result.push_back(filename.c_str());
188 } else {
189 result.push_back(flag.c_str());
190 }
191 }
192 return result;
193}
194
195void initializeTargetCC1FlagCache(const std::set<CompilationType>& types,
196 const std::unordered_map<Arch, CompilationRequirements>& reqs) {
197 if (!cc1_flags.empty()) {
198 errx(1, "reinitializing target CC1 flag cache?");
199 }
200
201 auto start = std::chrono::high_resolution_clock::now();
202 std::vector<std::thread> threads;
203 for (const CompilationType type : types) {
204 threads.emplace_back([type, &reqs]() {
205 const auto& arch_req_it = reqs.find(type.arch);
206 if (arch_req_it == reqs.end()) {
207 errx(1, "CompilationRequirement map missing entry for CompilationType %s",
208 to_string(type).c_str());
209 }
210
211 generateTargetCC1Flags(type, arch_req_it->second.dependencies);
212 });
213 }
214 for (auto& thread : threads) {
215 thread.join();
216 }
217 auto end = std::chrono::high_resolution_clock::now();
218
219 if (verbose) {
220 auto diff = (end - start) / 1.0ms;
221 printf("Generated compiler flags for %zu targets in %0.2Lfms\n", types.size(), diff);
222 }
223
224 if (cc1_flags.empty()) {
225 errx(1, "failed to initialize target CC1 flag cache");
226 }
227}
228
229void compileHeader(HeaderDatabase* header_database, CompilationType type,
230 const std::string& filename) {
231 auto diags = constructDiags();
232 std::vector<const char*> cc1_flags = getCC1Command(type, filename);
233 auto invocation = std::make_unique<CompilerInvocation>();
234 if (!CompilerInvocation::CreateFromArgs(*invocation.get(), &cc1_flags.front(),
235 &cc1_flags.front() + cc1_flags.size(), *diags)) {
236 errx(1, "failed to create CompilerInvocation");
237 }
238
239 clang::CompilerInstance Compiler;
240 Compiler.setInvocation(invocation.release());
241 Compiler.setDiagnostics(diags.get());
242
243 VersionerASTAction versioner_action(header_database, type);
244 if (!Compiler.ExecuteAction(versioner_action)) {
245 errx(1, "compilation generated warnings or errors");
246 }
247
248 if (diags->getNumWarnings() || diags->hasErrorOccurred()) {
249 errx(1, "compilation generated warnings or errors");
250 }
251}