Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(372)

Side by Side Diff: src/main.cpp

Issue 997773002: Refactor Subzero initialization and add a browser callback handler. (Closed) Base URL: https://chromium.googlesource.com/native_client/pnacl-subzero.git@master
Patch Set: remember to EOF Created 5 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« src/IceCompiler.cpp ('K') | « src/IceCompiler.cpp ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 //===- subzero/src/main.cpp - Driver for bitcode translation --------------===// 1 //===- subzero/src/main.cpp - Entry point for bitcode translation ---------===//
2 // 2 //
3 // The Subzero Code Generator 3 // The Subzero Code Generator
4 // 4 //
5 // This file is distributed under the University of Illinois Open Source 5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details. 6 // License. See LICENSE.TXT for details.
7 // 7 //
8 //===----------------------------------------------------------------------===// 8 //===----------------------------------------------------------------------===//
9 // 9 //
10 // This file defines a driver for translating PNaCl bitcode into native code. 10 // This file defines the entry point for translating PNaCl bitcode into
11 // It can either directly parse the binary bitcode file, or use LLVM routines to 11 // native code.
12 // parse a textual bitcode file into LLVM IR and then convert LLVM IR into ICE.
13 // In either case, the high-level ICE is then compiled down to native code, as
14 // either an ELF object file or a textual asm file.
15 // 12 //
16 //===----------------------------------------------------------------------===// 13 //===----------------------------------------------------------------------===//
17 14
18 #include <fstream> 15 #include "IceBrowserCompileServer.h"
19 #include <iostream> 16 #include "IceCompiler.h"
20 17 #include "IceCompileServer.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IRReader/IRReader.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/raw_os_ostream.h"
28 #include "llvm/Support/SourceMgr.h"
29 #include "llvm/Support/StreamingMemoryObject.h"
30
31 #include "IceCfg.h"
32 #include "IceClFlags.h"
33 #include "IceConverter.h"
34 #include "IceELFObjectWriter.h"
35 #include "IceELFStreamer.h"
36 #include "PNaClTranslator.h"
37
38 using namespace llvm;
39
40 static cl::list<Ice::VerboseItem> VerboseList(
41 "verbose", cl::CommaSeparated,
42 cl::desc("Verbose options (can be comma-separated):"),
43 cl::values(
44 clEnumValN(Ice::IceV_Instructions, "inst", "Print basic instructions"),
45 clEnumValN(Ice::IceV_Deleted, "del", "Include deleted instructions"),
46 clEnumValN(Ice::IceV_InstNumbers, "instnum",
47 "Print instruction numbers"),
48 clEnumValN(Ice::IceV_Preds, "pred", "Show predecessors"),
49 clEnumValN(Ice::IceV_Succs, "succ", "Show successors"),
50 clEnumValN(Ice::IceV_Liveness, "live", "Liveness information"),
51 clEnumValN(Ice::IceV_RegOrigins, "orig", "Physical register origins"),
52 clEnumValN(Ice::IceV_LinearScan, "regalloc", "Linear scan details"),
53 clEnumValN(Ice::IceV_Frame, "frame", "Stack frame layout details"),
54 clEnumValN(Ice::IceV_AddrOpt, "addropt", "Address mode optimization"),
55 clEnumValN(Ice::IceV_Random, "random", "Randomization details"),
56 clEnumValN(Ice::IceV_All, "all", "Use all verbose options"),
57 clEnumValN(Ice::IceV_Most, "most",
58 "Use all verbose options except 'regalloc' and 'time'"),
59 clEnumValN(Ice::IceV_None, "none", "No verbosity"), clEnumValEnd));
60 static cl::opt<Ice::TargetArch> TargetArch(
61 "target", cl::desc("Target architecture:"), cl::init(Ice::Target_X8632),
62 cl::values(
63 clEnumValN(Ice::Target_X8632, "x8632", "x86-32"),
64 clEnumValN(Ice::Target_X8632, "x86-32", "x86-32 (same as x8632)"),
65 clEnumValN(Ice::Target_X8632, "x86_32", "x86-32 (same as x8632)"),
66 clEnumValN(Ice::Target_X8664, "x8664", "x86-64"),
67 clEnumValN(Ice::Target_X8664, "x86-64", "x86-64 (same as x8664)"),
68 clEnumValN(Ice::Target_X8664, "x86_64", "x86-64 (same as x8664)"),
69 clEnumValN(Ice::Target_ARM32, "arm", "arm32"),
70 clEnumValN(Ice::Target_ARM32, "arm32", "arm32 (same as arm)"),
71 clEnumValN(Ice::Target_ARM64, "arm64", "arm64"), clEnumValEnd));
72 static cl::opt<bool> UseSandboxing("sandbox", cl::desc("Use sandboxing"));
73 static cl::opt<bool>
74 FunctionSections("ffunction-sections",
75 cl::desc("Emit functions into separate sections"));
76 static cl::opt<bool>
77 DataSections("fdata-sections",
78 cl::desc("Emit (global) data into separate sections"));
79 static cl::opt<Ice::OptLevel>
80 OptLevel(cl::desc("Optimization level"), cl::init(Ice::Opt_m1),
81 cl::value_desc("level"),
82 cl::values(clEnumValN(Ice::Opt_m1, "Om1", "-1"),
83 clEnumValN(Ice::Opt_m1, "O-1", "-1"),
84 clEnumValN(Ice::Opt_0, "O0", "0"),
85 clEnumValN(Ice::Opt_1, "O1", "1"),
86 clEnumValN(Ice::Opt_2, "O2", "2"), clEnumValEnd));
87 static cl::opt<std::string> IRFilename(cl::Positional, cl::desc("<IR file>"),
88 cl::init("-"));
89 static cl::opt<std::string> OutputFilename("o",
90 cl::desc("Override output filename"),
91 cl::init("-"),
92 cl::value_desc("filename"));
93 static cl::opt<std::string> LogFilename("log", cl::desc("Set log filename"),
94 cl::init("-"),
95 cl::value_desc("filename"));
96 static cl::opt<std::string>
97 TestPrefix("prefix",
98 cl::desc("Prepend a prefix to symbol names for testing"),
99 cl::init(""), cl::value_desc("prefix"));
100 static cl::opt<bool> DisableInternal("externalize",
101 cl::desc("Externalize all symbols"));
102 static cl::opt<bool>
103 DisableTranslation("notranslate", cl::desc("Disable Subzero translation"));
104 // Note: Modifiable only if ALLOW_DISABLE_IR_GEN.
105 static cl::opt<bool>
106 DisableIRGeneration("no-ir-gen",
107 cl::desc("Disable generating Subzero IR."));
108 static cl::opt<std::string>
109 TranslateOnly("translate-only",
110 cl::desc("Translate only the given function"), cl::init(""));
111
112 static cl::opt<bool> SubzeroTimingEnabled(
113 "timing", cl::desc("Enable breakdown timing of Subzero translation"));
114
115 static cl::opt<bool> TimeEachFunction(
116 "timing-funcs", cl::desc("Print total translation time for each function"));
117
118 static cl::opt<std::string> TimingFocusOn(
119 "timing-focus",
120 cl::desc("Break down timing for a specific function (use '*' for all)"),
121 cl::init(""));
122
123 static cl::opt<std::string> VerboseFocusOn(
124 "verbose-focus",
125 cl::desc("Temporarily enable full verbosity for a specific function"),
126 cl::init(""));
127
128 static cl::opt<bool>
129 EnablePhiEdgeSplit("phi-edge-split",
130 cl::desc("Enable edge splitting for Phi lowering"),
131 cl::init(true));
132
133 static cl::opt<bool> DecorateAsm(
134 "asm-verbose",
135 cl::desc("Decorate textual asm output with register liveness info"));
136
137 static cl::opt<bool>
138 DumpStats("szstats",
139 cl::desc("Print statistics after translating each function"));
140
141 // This is currently needed by crosstest.py.
142 static cl::opt<bool> AllowUninitializedGlobals(
143 "allow-uninitialized-globals",
144 cl::desc("Allow global variables to be uninitialized"));
145
146 static cl::opt<NaClFileFormat> InputFileFormat(
147 "bitcode-format", cl::desc("Define format of input file:"),
148 cl::values(clEnumValN(LLVMFormat, "llvm", "LLVM file (default)"),
149 clEnumValN(PNaClFormat, "pnacl", "PNaCl bitcode file"),
150 clEnumValEnd),
151 cl::init(LLVMFormat));
152
153 static cl::opt<std::string>
154 DefaultGlobalPrefix("default-global-prefix",
155 cl::desc("Define default global prefix for naming "
156 "unnamed globals"),
157 cl::init("Global"));
158
159 static cl::opt<std::string>
160 DefaultFunctionPrefix("default-function-prefix",
161 cl::desc("Define default function prefix for naming "
162 "unnamed functions"),
163 cl::init("Function"));
164
165 // Note: While this flag isn't used in the minimal build, we keep this
166 // flag so that tests can set this command-line flag without concern
167 // to the type of build. We double check that this flag at runtime
168 // to make sure the consistency is maintained.
169 static cl::opt<bool>
170 BuildOnRead("build-on-read",
171 cl::desc("Build ICE instructions when reading bitcode"),
172 cl::init(true));
173
174 static cl::opt<bool> AllowErrorRecovery(
175 "allow-pnacl-reader-error-recovery",
176 cl::desc("Allow error recovery when reading PNaCl bitcode."),
177 cl::init(false));
178
179 // TODO(kschimpf) Remove once the emitter handles these cases.
180 static cl::opt<bool>
181 StubConstantCalls("stub-const-calls",
182 cl::desc("Stub indirect calls to constants."),
183 cl::init(false));
184
185 static cl::opt<bool> LLVMVerboseErrors(
186 "verbose-llvm-parse-errors",
187 cl::desc("Print out more descriptive PNaCl bitcode parse errors when "
188 "building LLVM IR first"),
189 cl::init(false));
190
191 static cl::opt<Ice::FileType> OutFileType(
192 "filetype", cl::desc("Output file type"), cl::init(Ice::FT_Iasm),
193 cl::values(clEnumValN(Ice::FT_Elf, "obj", "Native ELF object ('.o') file"),
194 clEnumValN(Ice::FT_Asm, "asm", "Assembly ('.s') file"),
195 clEnumValN(Ice::FT_Iasm, "iasm",
196 "Low-level integrated assembly ('.s') file"),
197 clEnumValEnd));
198
199 static cl::opt<bool> AlwaysExitSuccess(
200 "exit-success", cl::desc("Exit with success status, even if errors found"),
201 cl::init(false));
202
203 static cl::opt<bool> GenerateBuildAtts(
204 "build-atts", cl::desc("Generate list of build attributes associated with "
205 "this executable."),
206 cl::init(false));
207
208 // Number of translation threads (in addition to the parser thread and
209 // the emitter thread). The special case of 0 means purely
210 // sequential, i.e. parser, translator, and emitter all within the
211 // same single thread. (This may need a slight rework if we expand to
212 // multiple parser or emitter threads.)
213 static cl::opt<uint32_t> NumThreads(
214 "threads",
215 cl::desc("Number of translation threads (0 for purely sequential)"),
216 // TODO(stichnot): Settle on a good default. Consider
217 // something related to std::thread::hardware_concurrency().
218 cl::init(2));
219
220 static int GetReturnValue(int Val) {
221 if (AlwaysExitSuccess)
222 return 0;
223 return Val;
224 }
225
226 static struct {
227 const char *FlagName;
228 int FlagValue;
229 } ConditionalBuildAttributes[] = {{"dump", ALLOW_DUMP},
230 {"disable_ir_gen", ALLOW_DISABLE_IR_GEN},
231 {"llvm_cl", ALLOW_LLVM_CL},
232 {"llvm_ir", ALLOW_LLVM_IR},
233 {"llvm_ir_as_input", ALLOW_LLVM_IR_AS_INPUT},
234 {"minimal_build", ALLOW_MINIMAL_BUILD}};
235
236 // Validates values of build attributes. Prints them to Stream if
237 // Stream is non-null.
238 static void ValidateAndGenerateBuildAttributes(Ice::Ostream *Stream) {
239
240 if (Stream)
241 *Stream << TargetArch << "\n";
242
243 for (size_t i = 0; i < array_lengthof(ConditionalBuildAttributes); ++i) {
244 switch (ConditionalBuildAttributes[i].FlagValue) {
245 case 0:
246 if (Stream)
247 *Stream << "no_" << ConditionalBuildAttributes[i].FlagName << "\n";
248 break;
249 case 1:
250 if (Stream)
251 *Stream << "allow_" << ConditionalBuildAttributes[i].FlagName << "\n";
252 break;
253 default: {
254 std::string Buffer;
255 raw_string_ostream StrBuf(Buffer);
256 StrBuf << "Flag " << ConditionalBuildAttributes[i].FlagName
257 << " must be defined as 0/1. Found: "
258 << ConditionalBuildAttributes[i].FlagValue;
259 report_fatal_error(StrBuf.str());
260 }
261 }
262 }
263 }
264 18
265 int main(int argc, char **argv) { 19 int main(int argc, char **argv) {
266 20 // Start file server and "wait" for compile request.
267 cl::ParseCommandLineOptions(argc, argv); 21 Ice::Compiler Comp;
268 22 // Can only compile the BrowserCompileServer w/ the NaCl compiler.
269 if (DisableIRGeneration) 23 #if PNACL_BROWSER_TRANSLATOR
270 DisableTranslation = true; 24 // There are no real commandline arguments in the browser case.
271 25 // They are supplied via IPC.
272 Ice::VerboseMask VMask = Ice::IceV_None; 26 assert(argc == 1);
273 // Don't generate verbose messages if routines 27 Ice::BrowserCompileServer Server(Comp);
274 // to dump messages are not available. 28 Server.run();
275 if (ALLOW_DUMP) { 29 return Server.getReturnValue();
276 for (unsigned i = 0; i != VerboseList.size(); ++i) 30 #else
277 VMask |= VerboseList[i]; 31 Ice::CLCompileServer Server(Comp, argc, argv);
278 } 32 Server.run();
279 33 return Server.getReturnValue();
280 std::ofstream Lfs; 34 #endif
281 std::unique_ptr<Ice::Ostream> Ls;
282 if (LogFilename != "-") {
283 Lfs.open(LogFilename.c_str(), std::ofstream::out);
284 Ls.reset(new raw_os_ostream(Lfs));
285 } else {
286 Ls.reset(new raw_os_ostream(std::cout));
287 }
288 Ls->SetUnbuffered();
289
290 ValidateAndGenerateBuildAttributes(GenerateBuildAtts ? Ls.get() : nullptr);
291 if (GenerateBuildAtts)
292 return GetReturnValue(Ice::EC_None);
293
294 if (!ALLOW_DISABLE_IR_GEN && DisableIRGeneration) {
295 *Ls << "Error: Build doesn't allow --no-ir-gen when not "
296 << "ALLOW_DISABLE_IR_GEN!\n";
297 return GetReturnValue(Ice::EC_Args);
298 }
299
300 Ice::ClFlags Flags;
301 Flags.setAllowErrorRecovery(AllowErrorRecovery);
302 Flags.setAllowUninitializedGlobals(AllowUninitializedGlobals);
303 Flags.setDataSections(DataSections);
304 Flags.setDecorateAsm(DecorateAsm);
305 Flags.setDefaultFunctionPrefix(DefaultFunctionPrefix);
306 Flags.setDefaultGlobalPrefix(DefaultGlobalPrefix);
307 Flags.setDisableInternal(DisableInternal);
308 Flags.setDisableIRGeneration(DisableIRGeneration);
309 Flags.setDisableTranslation(DisableTranslation);
310 Flags.setDumpStats(DumpStats);
311 Flags.setFunctionSections(FunctionSections);
312 Flags.setNumTranslationThreads(NumThreads);
313 Flags.setPhiEdgeSplit(EnablePhiEdgeSplit);
314 Flags.setStubConstantCalls(StubConstantCalls);
315 Flags.setSubzeroTimingEnabled(SubzeroTimingEnabled);
316 Flags.setTimeEachFunction(TimeEachFunction);
317 Flags.setTimingFocusOn(TimingFocusOn);
318 Flags.setTranslateOnly(TranslateOnly);
319 Flags.setUseSandboxing(UseSandboxing);
320 Flags.setVerboseFocusOn(VerboseFocusOn);
321 Flags.setOutFileType(OutFileType);
322
323 // Force -build-on-read=0 for .ll files.
324 const std::string LLSuffix = ".ll";
325 if (IRFilename.length() >= LLSuffix.length() &&
326 IRFilename.compare(IRFilename.length() - LLSuffix.length(),
327 LLSuffix.length(), LLSuffix) == 0)
328 BuildOnRead = false;
329
330 // With the ELF writer, use a raw_fd_ostream to allow seeking.
331 // Also don't buffer, otherwise it gets pretty slow.
332 std::unique_ptr<Ice::Ostream> Os;
333 std::unique_ptr<Ice::ELFStreamer> ELFStr;
334 std::ofstream Ofs;
335 switch (OutFileType) {
336 case Ice::FT_Elf: {
337 if (OutputFilename == "-") {
338 *Ls << "Error: writing binary ELF to stdout is unsupported\n";
339 return GetReturnValue(Ice::EC_Args);
340 }
341 std::error_code EC;
342 raw_fd_ostream *FdOs =
343 new raw_fd_ostream(OutputFilename, EC, sys::fs::F_None);
344 // NaCl sets st_blksize to 0, and LLVM uses that to pick the
345 // default preferred buffer size. Set to something non-zero.
346 FdOs->SetBufferSize(1 << 14);
347 Os.reset(FdOs);
348 if (EC) {
349 *Ls << "Failed to open output file: " << OutputFilename << ":\n"
350 << EC.message() << "\n";
351 return GetReturnValue(Ice::EC_Args);
352 }
353 ELFStr.reset(new Ice::ELFStreamer(*FdOs));
354 } break;
355 case Ice::FT_Asm:
356 case Ice::FT_Iasm: {
357 if (OutputFilename != "-") {
358 Ofs.open(OutputFilename.c_str(), std::ofstream::out);
359 Os.reset(new raw_os_ostream(Ofs));
360 } else {
361 Os.reset(new raw_os_ostream(std::cout));
362 }
363 Os->SetUnbuffered();
364 } break;
365 }
366
367 Ice::GlobalContext Ctx(Ls.get(), Os.get(), ELFStr.get(), VMask, TargetArch,
368 OptLevel, TestPrefix, Flags);
369
370 Ice::TimerMarker T(Ice::TimerStack::TT_szmain, &Ctx);
371
372 if (OutFileType == Ice::FT_Elf) {
373 Ice::TimerMarker T1(Ice::TimerStack::TT_emit, &Ctx);
374 Ctx.getObjectWriter()->writeInitialELFHeader();
375 }
376
377 Ctx.startWorkerThreads();
378
379 std::unique_ptr<Ice::Translator> Translator;
380 if (BuildOnRead) {
381 std::unique_ptr<Ice::PNaClTranslator> PTranslator(
382 new Ice::PNaClTranslator(&Ctx));
383 std::string StrError;
384 std::unique_ptr<DataStreamer> FileStreamer(
385 getDataFileStreamer(IRFilename, &StrError));
386 if (!StrError.empty() || !FileStreamer) {
387 SMDiagnostic Err(IRFilename, SourceMgr::DK_Error, StrError);
388 Err.print(argv[0], errs());
389 return GetReturnValue(Ice::EC_Bitcode);
390 }
391 std::unique_ptr<StreamingMemoryObject> MemObj(
392 new StreamingMemoryObjectImpl(FileStreamer.release()));
393 PTranslator->translate(IRFilename, std::move(MemObj));
394 Translator.reset(PTranslator.release());
395 } else if (ALLOW_LLVM_IR) {
396 // Parse the input LLVM IR file into a module.
397 SMDiagnostic Err;
398 Ice::TimerMarker T1(Ice::TimerStack::TT_parse, &Ctx);
399 raw_ostream *Verbose = LLVMVerboseErrors ? &errs() : nullptr;
400 std::unique_ptr<Module> Mod = NaClParseIRFile(
401 IRFilename, InputFileFormat, Err, Verbose, getGlobalContext());
402 if (!Mod) {
403 Err.print(argv[0], errs());
404 return GetReturnValue(Ice::EC_Bitcode);
405 }
406
407 std::unique_ptr<Ice::Converter> Converter(
408 new Ice::Converter(Mod.get(), &Ctx));
409 Converter->convertToIce();
410 Translator.reset(Converter.release());
411 } else {
412 *Ls << "Error: Build doesn't allow LLVM IR, "
413 << "--build-on-read=0 not allowed\n";
414 return GetReturnValue(Ice::EC_Args);
415 }
416
417 Ctx.waitForWorkerThreads();
418 Translator->transferErrorCode();
419 Translator->emitConstants();
420
421 if (OutFileType == Ice::FT_Elf) {
422 Ice::TimerMarker T1(Ice::TimerStack::TT_emit, &Ctx);
423 Ctx.getObjectWriter()->setUndefinedSyms(Ctx.getConstantExternSyms());
424 Ctx.getObjectWriter()->writeNonUserSections();
425 }
426 if (SubzeroTimingEnabled)
427 Ctx.dumpTimers();
428 if (TimeEachFunction) {
429 const bool DumpCumulative = false;
430 Ctx.dumpTimers(Ice::GlobalContext::TSK_Funcs, DumpCumulative);
431 }
432 const bool FinalStats = true;
433 Ctx.dumpStats("_FINAL_", FinalStats);
434 return GetReturnValue(Ctx.getErrorStatus()->value());
435 } 35 }
OLDNEW
« src/IceCompiler.cpp ('K') | « src/IceCompiler.cpp ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698