Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
924 lines (812 loc) · 34.7 KB
/
Copy pathmain.cpp
File metadata and controls
924 lines (812 loc) · 34.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
// SPDX-License-Identifier: Apache-2.0
#include "coretrace_concurrency_analyzer.hpp"
#include "coretrace_concurrency_analysis.hpp"
#include "internal/compilation_database.hpp"
#include "internal/ir_cache.hpp"
#include "internal/ir_loader.hpp"
#include "internal/diagnostics/compiler_diagnostic_parser.hpp"
#include "internal/reporting/report_renderer.hpp"
#include <llvm/IR/Module.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/raw_ostream.h>
#include <sys/resource.h>
#include <charconv>
#include <chrono>
#include <optional>
#include <memory>
#include <cstddef>
#include <filesystem>
#include <algorithm>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace
{
// 2, not 1: 1 already means the analysis failed to produce a verdict, and the
// difference matters to whoever reads the job.
constexpr int kFindingsExitCode = 2;
void printHelp()
{
llvm::outs()
<< "CoreTrace Concurrency Analyzer bootstrap CLI\n\n"
<< "Usage:\n"
<< " coretrace_concurrency_analyzer <file.c|cpp> [options]\n\n"
<< "Options:\n"
<< " --ir-format=ll|bc Compilation output mode (default: bc)\n"
<< " --compile-arg=<arg> Forward a compile argument (repeatable)\n"
<< " --instrument Enable compilerlib instrumentation mode\n"
<< " --compile-commands=PATH Analyse a whole project from a compile_commands.json\n"
<< " instead of a single file (implies --analyze)\n"
<< " --no-cache Recompile every unit, and neither read nor write the\n"
<< " IR cache; the bitcode is then kept in memory\n"
<< " --max-live-units=N Most units held in memory at once during a project\n"
<< " analysis (default: one per hardware thread)\n"
<< "\n"
<< "Sources are always compiled unoptimized: the analysis describes the program as\n"
<< "written, and an optimizer removes the very structure the rules read.\n"
<< " --analyze Run selected single-TU concurrency checks on the IR "
"module\n"
<< " --rules=<comma-separated>|all\n"
<< " Rule selection for --analyze. Available: data-race,\n"
<< " missing-join, deadlock-lock-order, condition-wait,\n"
<< " fork-after-thread, unreaped-child, thread-arg-escape,\n"
<< " unsafe-signal-handler, weak-publication,\n"
<< " thread-arg-freed, thread-local-escape, or `all`\n"
<< " (default: every rule)\n"
<< " --format=human|json|sarif\n"
<< " Diagnostic output format for --analyze (default: "
"human)\n"
<< " --verbose Print request details for debugging\n"
<< " -- Forward all following args to compilerlib\n"
<< " -h, --help Show this help message\n"
<< " --version Print the analyzer version and exit\n"
<< " --fail-on=none|error|warning\n"
<< " Exit " + std::to_string(kFindingsExitCode) +
" when the analysis reports at that severity or\n"
" above (default: none). Exit 1 still means the\n"
" analysis could not run.\n\n"
<< "Examples:\n"
<< " coretrace_concurrency_analyzer test.c --ir-format=ll\n"
<< " coretrace_concurrency_analyzer test.c --ir-format=bc --compile-arg=-Iinclude\n"
<< " coretrace_concurrency_analyzer test.c --analyze --format=human\n"
<< " coretrace_concurrency_analyzer test.c --analyze --rules=all --format=human\n"
<< " coretrace_concurrency_analyzer test.c --analyze --format=sarif\n"
<< " coretrace_concurrency_analyzer test.c -- --std=gnu11 -Wall\n"
<< " coretrace_concurrency_analyzer --compile-commands=build/compile_commands.json\n";
}
void printRequestSummary(const ctrace::concurrency::CompileRequest& request, bool analyze,
const ctrace::concurrency::AnalysisOptions& analysisOptions,
ctrace::concurrency::OutputFormat outputFormat,
llvm::raw_ostream& stream)
{
stream << "request.input-file: " << request.inputFile << "\n";
stream << "request.ir-format: " << ctrace::concurrency::toString(request.format) << "\n";
stream << "request.instrument: " << (request.instrument ? "true" : "false") << "\n";
stream << "request.analyze: " << (analyze ? "true" : "false") << "\n";
if (analyze)
{
auto ruleLabel = [](ctrace::concurrency::RuleId ruleId) -> std::string_view
{
switch (ruleId)
{
case ctrace::concurrency::RuleId::DataRaceGlobal:
return "data-race";
case ctrace::concurrency::RuleId::MissingJoin:
return "missing-join";
case ctrace::concurrency::RuleId::ConditionWaitWithoutPredicate:
return "condition-wait";
case ctrace::concurrency::RuleId::ForkAfterThreadCreation:
return "fork-after-thread";
case ctrace::concurrency::RuleId::UnreapedChildProcess:
return "unreaped-child";
case ctrace::concurrency::RuleId::ThreadArgumentEscapesFrame:
return "thread-arg-escape";
case ctrace::concurrency::RuleId::UnsafeSignalHandler:
return "unsafe-signal-handler";
case ctrace::concurrency::RuleId::WeakPublicationOrdering:
return "weak-publication";
case ctrace::concurrency::RuleId::ThreadArgumentFreedEarly:
return "thread-arg-freed";
case ctrace::concurrency::RuleId::ThreadLocalOutlivesThread:
return "thread-local-escape";
case ctrace::concurrency::RuleId::DeadlockLockOrder:
return "deadlock-lock-order";
case ctrace::concurrency::RuleId::CompilerDiagnostic:
return "compiler-diagnostic";
}
return "unknown";
};
stream << "request.output-format: " << ctrace::concurrency::toString(outputFormat)
<< "\n";
stream << "request.rules:";
for (const ctrace::concurrency::RuleId ruleId : analysisOptions.enabledRules)
stream << " " << ruleLabel(ruleId);
stream << "\n";
}
stream << "request.extra-args-count: " << request.extraCompileArgs.size() << "\n";
for (const std::string& arg : request.extraCompileArgs)
stream << "request.extra-arg: " << arg << "\n";
}
/// Peak resident set size of this process so far, in megabytes. What `/usr/bin/time`
/// reports from outside, made available from inside so a run can state its own ceiling.
long peakResidentMegabytes()
{
rusage usage{};
if (getrusage(RUSAGE_SELF, &usage) != 0)
return -1;
#if defined(__APPLE__)
return usage.ru_maxrss / (1024 * 1024); // bytes
#else
return usage.ru_maxrss / 1024; // kibibytes
#endif
}
std::size_t countDefinedFunctions(const llvm::Module& module)
{
std::size_t count = 0;
for (const llvm::Function& function : module)
{
if (!function.isDeclaration())
++count;
}
return count;
}
bool parseFormat(std::string_view value, ctrace::concurrency::IRFormat& out)
{
if (value == "ll")
{
out = ctrace::concurrency::IRFormat::LL;
return true;
}
if (value == "bc")
{
out = ctrace::concurrency::IRFormat::BC;
return true;
}
return false;
}
bool parseOutputFormat(std::string_view value, ctrace::concurrency::OutputFormat& out)
{
if (value == "human")
{
out = ctrace::concurrency::OutputFormat::Human;
return true;
}
if (value == "json")
{
out = ctrace::concurrency::OutputFormat::Json;
return true;
}
if (value == "sarif")
{
out = ctrace::concurrency::OutputFormat::Sarif;
return true;
}
return false;
}
std::string_view ruleOptionLabel(ctrace::concurrency::RuleId ruleId)
{
using ctrace::concurrency::RuleId;
switch (ruleId)
{
case RuleId::DataRaceGlobal:
return "data-race";
case RuleId::MissingJoin:
return "missing-join";
case RuleId::DeadlockLockOrder:
return "deadlock-lock-order";
case RuleId::ConditionWaitWithoutPredicate:
return "condition-wait";
case RuleId::ForkAfterThreadCreation:
return "fork-after-thread";
case RuleId::UnreapedChildProcess:
return "unreaped-child";
case RuleId::ThreadArgumentEscapesFrame:
return "thread-arg-escape";
case RuleId::UnsafeSignalHandler:
return "unsafe-signal-handler";
case RuleId::WeakPublicationOrdering:
return "weak-publication";
case RuleId::ThreadArgumentFreedEarly:
return "thread-arg-freed";
case RuleId::ThreadLocalOutlivesThread:
return "thread-local-escape";
case RuleId::CompilerDiagnostic:
return "compiler-diagnostic";
}
return "unknown";
}
bool parseAnalysisRule(std::string_view value, ctrace::concurrency::RuleId& out)
{
using ctrace::concurrency::RuleId;
if (value == "data-race")
{
out = RuleId::DataRaceGlobal;
return true;
}
if (value == "missing-join")
{
out = RuleId::MissingJoin;
return true;
}
if (value == "deadlock-lock-order")
{
out = RuleId::DeadlockLockOrder;
return true;
}
if (value == "condition-wait")
{
out = RuleId::ConditionWaitWithoutPredicate;
return true;
}
if (value == "fork-after-thread")
{
out = RuleId::ForkAfterThreadCreation;
return true;
}
if (value == "unreaped-child")
{
out = RuleId::UnreapedChildProcess;
return true;
}
if (value == "thread-arg-escape")
{
out = RuleId::ThreadArgumentEscapesFrame;
return true;
}
if (value == "unsafe-signal-handler")
{
out = RuleId::UnsafeSignalHandler;
return true;
}
if (value == "weak-publication")
{
out = RuleId::WeakPublicationOrdering;
return true;
}
if (value == "thread-arg-freed")
{
out = RuleId::ThreadArgumentFreedEarly;
return true;
}
if (value == "thread-local-escape")
{
out = RuleId::ThreadLocalOutlivesThread;
return true;
}
return false;
}
void appendRuleIfMissing(std::vector<ctrace::concurrency::RuleId>& enabledRules,
ctrace::concurrency::RuleId ruleId)
{
if (std::find(enabledRules.begin(), enabledRules.end(), ruleId) == enabledRules.end())
enabledRules.push_back(ruleId);
}
bool parseAnalysisRules(std::string_view value, ctrace::concurrency::AnalysisOptions& options)
{
if (value == "all")
{
options = ctrace::concurrency::AnalysisOptions::allAvailable();
return true;
}
ctrace::concurrency::AnalysisOptions parsedOptions;
parsedOptions.enabledRules.clear();
std::size_t start = 0;
while (start <= value.size())
{
const std::size_t comma = value.find(',', start);
const std::string_view token = value.substr(
start, comma == std::string_view::npos ? std::string_view::npos : comma - start);
if (token.empty())
return false;
ctrace::concurrency::RuleId ruleId = ctrace::concurrency::RuleId::CompilerDiagnostic;
if (!parseAnalysisRule(token, ruleId))
return false;
appendRuleIfMissing(parsedOptions.enabledRules, ruleId);
if (comma == std::string_view::npos)
break;
start = comma + 1;
}
if (parsedOptions.enabledRules.empty())
return false;
options = std::move(parsedOptions);
return true;
}
ctrace::concurrency::internal::reporting::RenderContext
makeRenderContext(std::string_view inputFile, std::int64_t analysisTimeMs = -1)
{
std::error_code currentPathError;
const std::filesystem::path sourceRoot = std::filesystem::current_path(currentPathError);
return ctrace::concurrency::internal::reporting::RenderContext{
.toolName = "coretrace-concurrency-analyzer",
.inputFile = std::string(inputFile),
.mode = "IR",
.analysisTimeMs = analysisTimeMs,
.sourceRoot = currentPathError ? std::filesystem::path{} : sourceRoot,
};
}
// What a caller running in CI wants to know from the exit code alone: did the
// analysis find something worth failing a build over. Kept separate from the
// codes that mean the analysis could not run at all, because a pipeline that
// cannot tell those apart reports a crashed tool as a clean tree.
enum class FailOn
{
None,
Error,
Warning,
};
bool parseFailOn(std::string_view value, FailOn& out)
{
if (value == "none")
{
out = FailOn::None;
return true;
}
if (value == "error")
{
out = FailOn::Error;
return true;
}
if (value == "warning")
{
out = FailOn::Warning;
return true;
}
return false;
}
int gateExitCode(FailOn policy, const ctrace::concurrency::DiagnosticSummary& summary)
{
switch (policy)
{
case FailOn::None:
return 0;
case FailOn::Error:
return summary.error > 0 ? kFindingsExitCode : 0;
case FailOn::Warning:
return (summary.error > 0 || summary.warning > 0) ? kFindingsExitCode : 0;
}
return 0;
}
void
emitStructuredReport(const ctrace::concurrency::DiagnosticReport& report,
const ctrace::concurrency::internal::reporting::RenderContext& context,
ctrace::concurrency::OutputFormat outputFormat)
{
std::string rendered =
ctrace::concurrency::internal::reporting::renderReport(report, context, outputFormat);
llvm::outs() << rendered;
if (!rendered.empty() && rendered.back() != '\n')
llvm::outs() << "\n";
}
bool hasStructuredLocations(const ctrace::concurrency::DiagnosticReport& report)
{
for (const ctrace::concurrency::Diagnostic& diagnostic : report.diagnostics)
{
if (diagnostic.location.line != 0 || diagnostic.location.column != 0)
return true;
}
return false;
}
ctrace::concurrency::DiagnosticReport
buildCompileFailureReport(const ctrace::concurrency::CompileRequest& request,
const ctrace::concurrency::CompileResult& result,
ctrace::concurrency::InMemoryIRCompiler& compiler)
{
ctrace::concurrency::DiagnosticReport report =
ctrace::concurrency::internal::diagnostics::parseCompilerDiagnostics(
result.diagnostics, result.error, request.inputFile);
if (request.format != ctrace::concurrency::IRFormat::BC || hasStructuredLocations(report))
return report;
ctrace::concurrency::CompileRequest llRequest = request;
llRequest.format = ctrace::concurrency::IRFormat::LL;
llvm::LLVMContext retryContext;
const ctrace::concurrency::CompileResult llResult =
compiler.compile(llRequest, retryContext);
if (llResult.success)
return report;
const ctrace::concurrency::DiagnosticReport recovered =
ctrace::concurrency::internal::diagnostics::parseCompilerDiagnostics(
llResult.diagnostics, llResult.error, request.inputFile);
if (hasStructuredLocations(recovered))
return recovered;
if (!llResult.diagnostics.empty())
return recovered;
return report;
}
int analyzeProject(const std::string& databasePath,
const ctrace::concurrency::AnalysisOptions& analysisOptions,
ctrace::concurrency::OutputFormat outputFormat, bool verbose, bool useCache,
FailOn failOn)
{
namespace internal = ctrace::concurrency::internal;
std::string loadError;
const std::optional<internal::CompilationDatabase> database =
internal::CompilationDatabase::loadFromFile(databasePath, loadError);
if (!database.has_value())
{
llvm::errs() << "failed to read compilation database '" << databasePath
<< "': " << loadError << "\n";
return 1;
}
const std::vector<internal::CompileCommand> commands =
database->analyzableSources(/*includeDependencies=*/false);
if (commands.empty())
{
llvm::errs() << "compilation database '" << databasePath
<< "' contains no analyzable source\n";
return 1;
}
// Compiled one at a time on purpose: the clang backend relies on process-wide state, and
// a race inside a race detector would be a poor trade for the wall-clock it would save.
// The analysis itself, which dominates once the IR exists, runs in parallel.
const auto startedAt = std::chrono::steady_clock::now();
// The cache lives beside the database, with the build it describes, so that discarding
// the build discards it too.
std::optional<internal::IRCache> cache;
if (useCache)
{
cache = internal::IRCache::open(std::filesystem::path(databasePath).parent_path() /
".coretrace-ir-cache");
}
// Only the bitcode is kept from this loop. The analysis parses each unit when it gets
// to it and lets the module go afterwards, so the number of modules in memory is bound
// by the number of workers rather than by the size of the project. With the cache, even
// the bitcode is not kept: a unit whose entry is on disk is read from it when analysed,
// so the memory floor is what the cache could not hold. Without the cache nothing is read
// from or written to it, and the bitcode stays in memory.
ctrace::concurrency::InMemoryIRCompiler compiler;
internal::LLVMIRLoader irLoader;
ctrace::concurrency::ProjectUnitSource units;
std::vector<std::string> failedSources;
std::size_t reusedUnits = 0;
std::size_t compiledUnits = 0;
for (const internal::CompileCommand& command : commands)
{
if (cache.has_value())
{
if (const std::optional<std::filesystem::path> entry = cache->lookupPath(command))
{
// Parsed once here to prove the entry readable, then dropped with its bytes:
// an entry that does not parse is unusable, not a sign that the unit is
// broken, so it falls through to compilation exactly as before.
bool readable = false;
if (const llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> cached =
llvm::MemoryBuffer::getFile(entry->string(), /*IsText=*/false,
/*RequiresNullTerminator=*/false,
/*IsVolatile=*/true))
{
llvm::LLVMContext probeContext;
ctrace::concurrency::CompileError parseError;
readable = irLoader.parseBC(std::string_view((*cached)->getBufferStart(),
(*cached)->getBufferSize()),
probeContext, parseError) != nullptr;
}
if (readable)
{
++reusedUnits;
units.addFile(command.file, *entry);
continue;
}
}
}
ctrace::concurrency::CompileRequest request;
request.inputFile = command.file;
request.extraCompileArgs = command.arguments;
request.format = ctrace::concurrency::IRFormat::BC;
std::filesystem::path depfile;
if (cache.has_value())
{
depfile = cache->depfilePathFor(command);
request.extraCompileArgs.emplace_back("-MD");
request.extraCompileArgs.emplace_back("-MF");
request.extraCompileArgs.push_back(depfile.string());
}
// The compiler parses into this context to validate its output; both are released
// at the end of the iteration.
llvm::LLVMContext compileContext;
ctrace::concurrency::CompileResult result = compiler.compile(request, compileContext);
if (!result.success || result.module == nullptr)
{
failedSources.push_back(command.file);
if (verbose && !result.diagnostics.empty())
llvm::errs() << result.diagnostics;
continue;
}
std::optional<std::filesystem::path> stored;
if (cache.has_value())
{
// Stored against the command as the database states it, without the flags added
// to obtain the dependency list.
stored = cache->store(command, result.llvmBitcode, depfile);
std::error_code removeError;
std::filesystem::remove(depfile, removeError);
}
// The module the compiler parsed reads from the bitcode buffer, so it goes first;
// the analysis parses the same bytes again when it reaches this unit, from the cache
// entry when there is one, and from memory otherwise.
result.module.reset();
++compiledUnits;
if (stored.has_value())
units.addFile(command.file, *stored);
else
units.add(command.file, std::move(result.llvmBitcode));
}
if (units.size() == 0)
{
llvm::errs() << "no unit of '" << databasePath << "' could be compiled\n";
return 1;
}
const auto compiledAt = std::chrono::steady_clock::now();
const ctrace::concurrency::ProjectAnalysisReport analysis =
ctrace::concurrency::ProjectConcurrencyAnalyzer(analysisOptions).analyze(units);
const auto finishedAt = std::chrono::steady_clock::now();
// The analysis is done with the bitcode: what it held in memory goes before the report
// is rendered.
const std::size_t heldBitcodeBytes = units.bitcodeBytes();
units = {};
if (verbose)
{
const auto milliseconds = [](auto from, auto to)
{ return std::chrono::duration_cast<std::chrono::milliseconds>(to - from).count(); };
// Reused units are reported apart from compiled ones. Adding them together under
// "compiled" claims a compilation that never ran: a project whose sources no longer
// build reads as fully healthy for as long as its cache entries stay valid, which is
// exactly when the reader most needs to be told otherwise.
llvm::errs() << "units: " << compiledUnits << " compiled, " << reusedUnits
<< " reused, " << failedSources.size() + analysis.failedUnits.size()
<< " failed\n"
<< "compile-ms: " << milliseconds(startedAt, compiledAt) << "\n"
<< "analysis-ms: " << milliseconds(compiledAt, finishedAt) << "\n"
<< "load-ms: " << analysis.loadMilliseconds << "\n"
<< "reanalyzed-units: " << analysis.reanalyzedUnitCount << "\n"
<< "live-units-max: " << analysis.peakLiveUnits << "\n"
<< "bitcode-mb: " << heldBitcodeBytes / (1024 * 1024) << "\n"
<< "peak-rss-mb: " << peakResidentMegabytes() << "\n";
}
// A partial project yields partial conclusions; saying so is part of the result.
for (const std::string& source : failedSources)
llvm::errs() << "skipped (compilation failed): " << source << "\n";
for (const ctrace::concurrency::FailedUnit& unit : analysis.failedUnits)
{
llvm::errs() << "skipped (bitcode failed to load): " << unit.identifier << ": "
<< unit.error.message << "\n";
}
for (const std::string& module : analysis.skippedIncompatibleModules)
llvm::errs() << "skipped (target ABI differs from the project): " << module << "\n";
const auto duration =
std::chrono::duration_cast<std::chrono::milliseconds>(finishedAt - startedAt).count();
emitStructuredReport(analysis.report, makeRenderContext(databasePath, duration),
outputFormat);
if (!failedSources.empty() || !analysis.complete())
return 1;
return gateExitCode(failOn, analysis.report.diagnosticsSummary);
}
} // namespace
int main(int argc, char** argv)
{
ctrace::concurrency::CompileRequest request;
bool analyze = false;
bool passthroughMode = false;
bool verbose = false;
FailOn failOn = FailOn::None;
bool outputFormatExplicit = false;
bool rulesExplicit = false;
std::string compileCommandsPath;
bool useCache = true;
ctrace::concurrency::OutputFormat outputFormat = ctrace::concurrency::OutputFormat::Human;
ctrace::concurrency::AnalysisOptions analysisOptions;
for (int i = 1; i < argc; ++i)
{
const std::string_view arg = argv[i];
if (passthroughMode)
{
request.extraCompileArgs.emplace_back(arg);
continue;
}
if (arg == "--")
{
passthroughMode = true;
continue;
}
if (arg == "-h" || arg == "--help")
{
printHelp();
return 0;
}
if (arg == "--version")
{
llvm::outs() << "coretrace_concurrency_analyzer "
<< CORETRACE_CONCURRENCY_ANALYZER_VERSION << "\n";
return 0;
}
if (arg == "--verbose")
{
verbose = true;
continue;
}
if (arg == "--analyze")
{
analyze = true;
continue;
}
constexpr std::string_view formatPrefix = "--ir-format=";
if (arg.rfind(formatPrefix, 0) == 0)
{
if (!parseFormat(arg.substr(formatPrefix.size()), request.format))
{
llvm::errs() << "Unsupported --ir-format value: " << std::string(arg) << "\n";
return 1;
}
continue;
}
constexpr std::string_view maxLiveUnitsPrefix = "--max-live-units=";
if (arg.rfind(maxLiveUnitsPrefix, 0) == 0)
{
const std::string_view value = arg.substr(maxLiveUnitsPrefix.size());
std::size_t parsed = 0;
const auto [end, errc] =
std::from_chars(value.data(), value.data() + value.size(), parsed);
if (errc != std::errc{} || end != value.data() + value.size() || parsed == 0)
{
llvm::errs() << "Unsupported --max-live-units value: " << std::string(arg)
<< " (expected a positive integer)\n";
return 1;
}
analysisOptions.maxLiveUnits = parsed;
continue;
}
constexpr std::string_view failOnPrefix = "--fail-on=";
if (arg.rfind(failOnPrefix, 0) == 0)
{
if (!parseFailOn(arg.substr(failOnPrefix.size()), failOn))
{
llvm::errs() << "Unsupported --fail-on value: " << std::string(arg) << "\n";
return 1;
}
continue;
}
constexpr std::string_view outputFormatPrefix = "--format=";
if (arg.rfind(outputFormatPrefix, 0) == 0)
{
if (!parseOutputFormat(arg.substr(outputFormatPrefix.size()), outputFormat))
{
llvm::errs() << "Unsupported --format value: " << std::string(arg) << "\n";
return 1;
}
outputFormatExplicit = true;
continue;
}
constexpr std::string_view rulesPrefix = "--rules=";
if (arg.rfind(rulesPrefix, 0) == 0)
{
if (!parseAnalysisRules(arg.substr(rulesPrefix.size()), analysisOptions))
{
llvm::errs() << "Unsupported --rules value: " << std::string(arg) << "\n";
return 1;
}
rulesExplicit = true;
continue;
}
if (arg == "--no-cache")
{
useCache = false;
continue;
}
constexpr std::string_view compileCommandsPrefix = "--compile-commands=";
if (arg.starts_with(compileCommandsPrefix))
{
compileCommandsPath = std::string(arg.substr(compileCommandsPrefix.size()));
if (compileCommandsPath.empty())
{
llvm::errs() << "--compile-commands requires a path\n";
return 1;
}
analyze = true;
continue;
}
constexpr std::string_view compileArgPrefix = "--compile-arg=";
if (arg.rfind(compileArgPrefix, 0) == 0)
{
request.extraCompileArgs.emplace_back(arg.substr(compileArgPrefix.size()));
continue;
}
if (arg == "--instrument")
{
request.instrument = true;
continue;
}
if (!arg.empty() && arg.front() == '-')
{
llvm::errs() << "Unknown option: " << std::string(arg) << "\n";
return 1;
}
if (request.inputFile.empty())
{
request.inputFile = std::string(arg);
continue;
}
llvm::errs() << "Unexpected positional argument: " << std::string(arg) << "\n";
return 1;
}
if (!compileCommandsPath.empty())
{
// The database names the sources and how to build them; a positional file would describe
// a different, contradictory input.
if (!request.inputFile.empty())
{
llvm::errs() << "--compile-commands and a positional input file are exclusive\n";
return 1;
}
if (!request.extraCompileArgs.empty())
{
llvm::errs() << "--compile-arg does not apply to --compile-commands: each unit uses "
"the flags recorded in the database\n";
return 1;
}
return analyzeProject(compileCommandsPath, analysisOptions, outputFormat, verbose, useCache,
failOn);
}
if (request.inputFile.empty())
{
printHelp();
return 1;
}
if (outputFormatExplicit && !analyze)
{
llvm::errs() << "--format requires --analyze\n";
return 1;
}
if (rulesExplicit && !analyze)
{
llvm::errs() << "--rules requires --analyze\n";
return 1;
}
if (verbose)
{
llvm::raw_ostream& stream =
(analyze && outputFormat != ctrace::concurrency::OutputFormat::Human) ? llvm::errs()
: llvm::outs();
printRequestSummary(request, analyze, analysisOptions, outputFormat, stream);
}
llvm::LLVMContext context;
ctrace::concurrency::InMemoryIRCompiler compiler;
ctrace::concurrency::CompileResult result = compiler.compile(request, context);
if (!analyze && !result.diagnostics.empty())
llvm::errs() << result.diagnostics;
if (!result.success)
{
if (analyze)
{
const ctrace::concurrency::DiagnosticReport report =
buildCompileFailureReport(request, result, compiler);
emitStructuredReport(report, makeRenderContext(request.inputFile), outputFormat);
return 1;
}
const std::string renderedError = formatCompileError(result.error);
if (!renderedError.empty())
llvm::errs() << renderedError << "\n";
else
llvm::errs() << "unknown_compile_failure\n";
return 1;
}
if (analyze)
{
const auto startedAt = std::chrono::steady_clock::now();
ctrace::concurrency::SingleTUConcurrencyAnalyzer analyzer(analysisOptions);
const ctrace::concurrency::DiagnosticReport report = analyzer.analyze(*result.module);
const auto finishedAt = std::chrono::steady_clock::now();
const auto duration =
std::chrono::duration_cast<std::chrono::milliseconds>(finishedAt - startedAt).count();
emitStructuredReport(report, makeRenderContext(request.inputFile, duration), outputFormat);
return gateExitCode(failOn, report.diagnosticsSummary);
}
const std::size_t payloadBytes = (request.format == ctrace::concurrency::IRFormat::BC)
? result.llvmBitcode.size()
: result.llvmIRText.size();
llvm::outs() << "IR compilation succeeded\n";
llvm::outs() << "format: " << ctrace::concurrency::toString(request.format) << "\n";
llvm::outs() << "payload-bytes: " << payloadBytes << "\n";
llvm::outs() << "defined-functions: " << countDefinedFunctions(*result.module) << "\n";
return 0;
}