-
Notifications
You must be signed in to change notification settings - Fork 12.5k
/
Copy pathCompilerInvocation.cpp
4822 lines (4174 loc) · 185 KB
/
CompilerInvocation.cpp
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- CompilerInvocation.cpp ---------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/CompilerInvocation.h"
#include "TestModuleFileExtension.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/CommentOptions.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticDriver.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/LangStandard.h"
#include "clang/Basic/ObjCRuntime.h"
#include "clang/Basic/Sanitizers.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/Version.h"
#include "clang/Basic/Visibility.h"
#include "clang/Basic/XRayInstr.h"
#include "clang/Config/config.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "clang/Frontend/CommandLineSourceLoc.h"
#include "clang/Frontend/DependencyOutputOptions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/FrontendOptions.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/Frontend/MigratorOptions.h"
#include "clang/Frontend/PreprocessorOutputOptions.h"
#include "clang/Frontend/TextDiagnosticBuffer.h"
#include "clang/Frontend/Utils.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Sema/CodeCompleteOptions.h"
#include "clang/Serialization/ASTBitCodes.h"
#include "clang/Serialization/ModuleFileExtension.h"
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/CachedHashString.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/FloatingPointMode.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/Frontend/Debug/Options.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/Linker/Linker.h"
#include "llvm/MC/MCTargetOptions.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/OptSpecifier.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"
#include "llvm/ProfileData/InstrProfReader.h"
#include "llvm/Remarks/HotnessThresholdParser.h"
#include "llvm/Support/CodeGen.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/HashBuilder.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/VersionTuple.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/TargetParser/Host.h"
#include "llvm/TargetParser/Triple.h"
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cstddef>
#include <cstring>
#include <ctime>
#include <fstream>
#include <limits>
#include <memory>
#include <optional>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
using namespace clang;
using namespace driver;
using namespace options;
using namespace llvm::opt;
//===----------------------------------------------------------------------===//
// Helpers.
//===----------------------------------------------------------------------===//
// Parse misexpect tolerance argument value.
// Valid option values are integers in the range [0, 100)
static Expected<std::optional<uint32_t>> parseToleranceOption(StringRef Arg) {
uint32_t Val;
if (Arg.getAsInteger(10, Val))
return llvm::createStringError(llvm::inconvertibleErrorCode(),
"Not an integer: %s", Arg.data());
return Val;
}
//===----------------------------------------------------------------------===//
// Initialization.
//===----------------------------------------------------------------------===//
namespace {
template <class T> std::shared_ptr<T> make_shared_copy(const T &X) {
return std::make_shared<T>(X);
}
template <class T>
llvm::IntrusiveRefCntPtr<T> makeIntrusiveRefCntCopy(const T &X) {
return llvm::makeIntrusiveRefCnt<T>(X);
}
} // namespace
CompilerInvocationBase::CompilerInvocationBase()
: LangOpts(std::make_shared<LangOptions>()),
TargetOpts(std::make_shared<TargetOptions>()),
DiagnosticOpts(llvm::makeIntrusiveRefCnt<DiagnosticOptions>()),
HSOpts(std::make_shared<HeaderSearchOptions>()),
PPOpts(std::make_shared<PreprocessorOptions>()),
AnalyzerOpts(llvm::makeIntrusiveRefCnt<AnalyzerOptions>()),
MigratorOpts(std::make_shared<MigratorOptions>()),
CodeGenOpts(std::make_shared<CodeGenOptions>()),
FSOpts(std::make_shared<FileSystemOptions>()),
FrontendOpts(std::make_shared<FrontendOptions>()),
DependencyOutputOpts(std::make_shared<DependencyOutputOptions>()),
PreprocessorOutputOpts(std::make_shared<PreprocessorOutputOptions>()) {}
CompilerInvocationBase &
CompilerInvocationBase::deep_copy_assign(const CompilerInvocationBase &X) {
if (this != &X) {
LangOpts = make_shared_copy(X.getLangOpts());
TargetOpts = make_shared_copy(X.getTargetOpts());
DiagnosticOpts = makeIntrusiveRefCntCopy(X.getDiagnosticOpts());
HSOpts = make_shared_copy(X.getHeaderSearchOpts());
PPOpts = make_shared_copy(X.getPreprocessorOpts());
AnalyzerOpts = makeIntrusiveRefCntCopy(X.getAnalyzerOpts());
MigratorOpts = make_shared_copy(X.getMigratorOpts());
CodeGenOpts = make_shared_copy(X.getCodeGenOpts());
FSOpts = make_shared_copy(X.getFileSystemOpts());
FrontendOpts = make_shared_copy(X.getFrontendOpts());
DependencyOutputOpts = make_shared_copy(X.getDependencyOutputOpts());
PreprocessorOutputOpts = make_shared_copy(X.getPreprocessorOutputOpts());
}
return *this;
}
CompilerInvocationBase &
CompilerInvocationBase::shallow_copy_assign(const CompilerInvocationBase &X) {
if (this != &X) {
LangOpts = X.LangOpts;
TargetOpts = X.TargetOpts;
DiagnosticOpts = X.DiagnosticOpts;
HSOpts = X.HSOpts;
PPOpts = X.PPOpts;
AnalyzerOpts = X.AnalyzerOpts;
MigratorOpts = X.MigratorOpts;
CodeGenOpts = X.CodeGenOpts;
FSOpts = X.FSOpts;
FrontendOpts = X.FrontendOpts;
DependencyOutputOpts = X.DependencyOutputOpts;
PreprocessorOutputOpts = X.PreprocessorOutputOpts;
}
return *this;
}
namespace {
template <typename T>
T &ensureOwned(std::shared_ptr<T> &Storage) {
if (Storage.use_count() > 1)
Storage = std::make_shared<T>(*Storage);
return *Storage;
}
template <typename T>
T &ensureOwned(llvm::IntrusiveRefCntPtr<T> &Storage) {
if (Storage.useCount() > 1)
Storage = llvm::makeIntrusiveRefCnt<T>(*Storage);
return *Storage;
}
} // namespace
LangOptions &CowCompilerInvocation::getMutLangOpts() {
return ensureOwned(LangOpts);
}
TargetOptions &CowCompilerInvocation::getMutTargetOpts() {
return ensureOwned(TargetOpts);
}
DiagnosticOptions &CowCompilerInvocation::getMutDiagnosticOpts() {
return ensureOwned(DiagnosticOpts);
}
HeaderSearchOptions &CowCompilerInvocation::getMutHeaderSearchOpts() {
return ensureOwned(HSOpts);
}
PreprocessorOptions &CowCompilerInvocation::getMutPreprocessorOpts() {
return ensureOwned(PPOpts);
}
AnalyzerOptions &CowCompilerInvocation::getMutAnalyzerOpts() {
return ensureOwned(AnalyzerOpts);
}
MigratorOptions &CowCompilerInvocation::getMutMigratorOpts() {
return ensureOwned(MigratorOpts);
}
CodeGenOptions &CowCompilerInvocation::getMutCodeGenOpts() {
return ensureOwned(CodeGenOpts);
}
FileSystemOptions &CowCompilerInvocation::getMutFileSystemOpts() {
return ensureOwned(FSOpts);
}
FrontendOptions &CowCompilerInvocation::getMutFrontendOpts() {
return ensureOwned(FrontendOpts);
}
DependencyOutputOptions &CowCompilerInvocation::getMutDependencyOutputOpts() {
return ensureOwned(DependencyOutputOpts);
}
PreprocessorOutputOptions &
CowCompilerInvocation::getMutPreprocessorOutputOpts() {
return ensureOwned(PreprocessorOutputOpts);
}
//===----------------------------------------------------------------------===//
// Normalizers
//===----------------------------------------------------------------------===//
using ArgumentConsumer = CompilerInvocation::ArgumentConsumer;
#define SIMPLE_ENUM_VALUE_TABLE
#include "clang/Driver/Options.inc"
#undef SIMPLE_ENUM_VALUE_TABLE
static std::optional<bool> normalizeSimpleFlag(OptSpecifier Opt,
unsigned TableIndex,
const ArgList &Args,
DiagnosticsEngine &Diags) {
if (Args.hasArg(Opt))
return true;
return std::nullopt;
}
static std::optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt,
unsigned,
const ArgList &Args,
DiagnosticsEngine &) {
if (Args.hasArg(Opt))
return false;
return std::nullopt;
}
/// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but
/// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with
/// unnecessary template instantiations and just ignore it with a variadic
/// argument.
static void denormalizeSimpleFlag(ArgumentConsumer Consumer,
const Twine &Spelling, Option::OptionClass,
unsigned, /*T*/...) {
Consumer(Spelling);
}
template <typename T> static constexpr bool is_uint64_t_convertible() {
return !std::is_same_v<T, uint64_t> && llvm::is_integral_or_enum<T>::value;
}
template <typename T,
std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false>
static auto makeFlagToValueNormalizer(T Value) {
return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
DiagnosticsEngine &) -> std::optional<T> {
if (Args.hasArg(Opt))
return Value;
return std::nullopt;
};
}
template <typename T,
std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false>
static auto makeFlagToValueNormalizer(T Value) {
return makeFlagToValueNormalizer(uint64_t(Value));
}
static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
OptSpecifier OtherOpt) {
return [Value, OtherValue,
OtherOpt](OptSpecifier Opt, unsigned, const ArgList &Args,
DiagnosticsEngine &) -> std::optional<bool> {
if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
return A->getOption().matches(Opt) ? Value : OtherValue;
}
return std::nullopt;
};
}
static auto makeBooleanOptionDenormalizer(bool Value) {
return [Value](ArgumentConsumer Consumer, const Twine &Spelling,
Option::OptionClass, unsigned, bool KeyPath) {
if (KeyPath == Value)
Consumer(Spelling);
};
}
static void denormalizeStringImpl(ArgumentConsumer Consumer,
const Twine &Spelling,
Option::OptionClass OptClass, unsigned,
const Twine &Value) {
switch (OptClass) {
case Option::SeparateClass:
case Option::JoinedOrSeparateClass:
case Option::JoinedAndSeparateClass:
Consumer(Spelling);
Consumer(Value);
break;
case Option::JoinedClass:
case Option::CommaJoinedClass:
Consumer(Spelling + Value);
break;
default:
llvm_unreachable("Cannot denormalize an option with option class "
"incompatible with string denormalization.");
}
}
template <typename T>
static void denormalizeString(ArgumentConsumer Consumer, const Twine &Spelling,
Option::OptionClass OptClass, unsigned TableIndex,
T Value) {
denormalizeStringImpl(Consumer, Spelling, OptClass, TableIndex, Twine(Value));
}
static std::optional<SimpleEnumValue>
findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) {
for (int I = 0, E = Table.Size; I != E; ++I)
if (Name == Table.Table[I].Name)
return Table.Table[I];
return std::nullopt;
}
static std::optional<SimpleEnumValue>
findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) {
for (int I = 0, E = Table.Size; I != E; ++I)
if (Value == Table.Table[I].Value)
return Table.Table[I];
return std::nullopt;
}
static std::optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt,
unsigned TableIndex,
const ArgList &Args,
DiagnosticsEngine &Diags) {
assert(TableIndex < SimpleEnumValueTablesSize);
const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
auto *Arg = Args.getLastArg(Opt);
if (!Arg)
return std::nullopt;
StringRef ArgValue = Arg->getValue();
if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue))
return MaybeEnumVal->Value;
Diags.Report(diag::err_drv_invalid_value)
<< Arg->getAsString(Args) << ArgValue;
return std::nullopt;
}
static void denormalizeSimpleEnumImpl(ArgumentConsumer Consumer,
const Twine &Spelling,
Option::OptionClass OptClass,
unsigned TableIndex, unsigned Value) {
assert(TableIndex < SimpleEnumValueTablesSize);
const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
denormalizeString(Consumer, Spelling, OptClass, TableIndex,
MaybeEnumVal->Name);
} else {
llvm_unreachable("The simple enum value was not correctly defined in "
"the tablegen option description");
}
}
template <typename T>
static void denormalizeSimpleEnum(ArgumentConsumer Consumer,
const Twine &Spelling,
Option::OptionClass OptClass,
unsigned TableIndex, T Value) {
return denormalizeSimpleEnumImpl(Consumer, Spelling, OptClass, TableIndex,
static_cast<unsigned>(Value));
}
static std::optional<std::string> normalizeString(OptSpecifier Opt,
int TableIndex,
const ArgList &Args,
DiagnosticsEngine &Diags) {
auto *Arg = Args.getLastArg(Opt);
if (!Arg)
return std::nullopt;
return std::string(Arg->getValue());
}
template <typename IntTy>
static std::optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int,
const ArgList &Args,
DiagnosticsEngine &Diags) {
auto *Arg = Args.getLastArg(Opt);
if (!Arg)
return std::nullopt;
IntTy Res;
if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
Diags.Report(diag::err_drv_invalid_int_value)
<< Arg->getAsString(Args) << Arg->getValue();
return std::nullopt;
}
return Res;
}
static std::optional<std::vector<std::string>>
normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
DiagnosticsEngine &) {
return Args.getAllArgValues(Opt);
}
static void denormalizeStringVector(ArgumentConsumer Consumer,
const Twine &Spelling,
Option::OptionClass OptClass,
unsigned TableIndex,
const std::vector<std::string> &Values) {
switch (OptClass) {
case Option::CommaJoinedClass: {
std::string CommaJoinedValue;
if (!Values.empty()) {
CommaJoinedValue.append(Values.front());
for (const std::string &Value : llvm::drop_begin(Values, 1)) {
CommaJoinedValue.append(",");
CommaJoinedValue.append(Value);
}
}
denormalizeString(Consumer, Spelling, Option::OptionClass::JoinedClass,
TableIndex, CommaJoinedValue);
break;
}
case Option::JoinedClass:
case Option::SeparateClass:
case Option::JoinedOrSeparateClass:
for (const std::string &Value : Values)
denormalizeString(Consumer, Spelling, OptClass, TableIndex, Value);
break;
default:
llvm_unreachable("Cannot denormalize an option with option class "
"incompatible with string vector denormalization.");
}
}
static std::optional<std::string> normalizeTriple(OptSpecifier Opt,
int TableIndex,
const ArgList &Args,
DiagnosticsEngine &Diags) {
auto *Arg = Args.getLastArg(Opt);
if (!Arg)
return std::nullopt;
return llvm::Triple::normalize(Arg->getValue());
}
template <typename T, typename U>
static T mergeForwardValue(T KeyPath, U Value) {
return static_cast<T>(Value);
}
template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) {
return KeyPath | Value;
}
template <typename T> static T extractForwardValue(T KeyPath) {
return KeyPath;
}
template <typename T, typename U, U Value>
static T extractMaskValue(T KeyPath) {
return ((KeyPath & Value) == Value) ? static_cast<T>(Value) : T();
}
#define PARSE_OPTION_WITH_MARSHALLING( \
ARGS, DIAGS, PREFIX_TYPE, SPELLING, ID, KIND, GROUP, ALIAS, ALIASARGS, \
FLAGS, VISIBILITY, PARAM, HELPTEXT, METAVAR, VALUES, SHOULD_PARSE, \
ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, \
NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX) \
if ((VISIBILITY)&options::CC1Option) { \
KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE); \
if (IMPLIED_CHECK) \
KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE); \
if (SHOULD_PARSE) \
if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS)) \
KEYPATH = \
MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue)); \
}
// Capture the extracted value as a lambda argument to avoid potential issues
// with lifetime extension of the reference.
#define GENERATE_OPTION_WITH_MARSHALLING( \
CONSUMER, PREFIX_TYPE, SPELLING, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, \
VISIBILITY, PARAM, HELPTEXT, METAVAR, VALUES, SHOULD_PARSE, ALWAYS_EMIT, \
KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \
DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX) \
if ((VISIBILITY)&options::CC1Option) { \
[&](const auto &Extracted) { \
if (ALWAYS_EMIT || \
(Extracted != \
static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE) \
: (DEFAULT_VALUE)))) \
DENORMALIZER(CONSUMER, SPELLING, Option::KIND##Class, TABLE_INDEX, \
Extracted); \
}(EXTRACTOR(KEYPATH)); \
}
static StringRef GetInputKindName(InputKind IK);
static bool FixupInvocation(CompilerInvocation &Invocation,
DiagnosticsEngine &Diags, const ArgList &Args,
InputKind IK) {
unsigned NumErrorsBefore = Diags.getNumErrors();
LangOptions &LangOpts = Invocation.getLangOpts();
CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
TargetOptions &TargetOpts = Invocation.getTargetOpts();
FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
if (FrontendOpts.ShowStats)
CodeGenOpts.ClearASTBeforeBackend = false;
LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
LangOpts.CurrentModule = LangOpts.ModuleName;
llvm::Triple T(TargetOpts.Triple);
llvm::Triple::ArchType Arch = T.getArch();
CodeGenOpts.CodeModel = TargetOpts.CodeModel;
CodeGenOpts.LargeDataThreshold = TargetOpts.LargeDataThreshold;
if (LangOpts.getExceptionHandling() !=
LangOptions::ExceptionHandlingKind::None &&
T.isWindowsMSVCEnvironment())
Diags.Report(diag::err_fe_invalid_exception_model)
<< static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str();
if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
Diags.Report(diag::warn_c_kext);
if (LangOpts.NewAlignOverride &&
!llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
Diags.Report(diag::err_fe_invalid_alignment)
<< A->getAsString(Args) << A->getValue();
LangOpts.NewAlignOverride = 0;
}
// Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host.
if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost)
Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device"
<< "-fsycl-is-host";
if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus)
Diags.Report(diag::err_drv_argument_not_allowed_with)
<< "-fgnu89-inline" << GetInputKindName(IK);
if (Args.hasArg(OPT_hlsl_entrypoint) && !LangOpts.HLSL)
Diags.Report(diag::err_drv_argument_not_allowed_with)
<< "-hlsl-entry" << GetInputKindName(IK);
if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP)
Diags.Report(diag::warn_ignored_hip_only_option)
<< Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP)
Diags.Report(diag::warn_ignored_hip_only_option)
<< Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
// When these options are used, the compiler is allowed to apply
// optimizations that may affect the final result. For example
// (x+y)+z is transformed to x+(y+z) but may not give the same
// final result; it's not value safe.
// Another example can be to simplify x/x to 1.0 but x could be 0.0, INF
// or NaN. Final result may then differ. An error is issued when the eval
// method is set with one of these options.
if (Args.hasArg(OPT_ffp_eval_method_EQ)) {
if (LangOpts.ApproxFunc)
Diags.Report(diag::err_incompatible_fp_eval_method_options) << 0;
if (LangOpts.AllowFPReassoc)
Diags.Report(diag::err_incompatible_fp_eval_method_options) << 1;
if (LangOpts.AllowRecip)
Diags.Report(diag::err_incompatible_fp_eval_method_options) << 2;
}
// -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
// This option should be deprecated for CL > 1.0 because
// this option was added for compatibility with OpenCL 1.0.
if (Args.getLastArg(OPT_cl_strict_aliasing) &&
(LangOpts.getOpenCLCompatibleVersion() > 100))
Diags.Report(diag::warn_option_invalid_ocl_version)
<< LangOpts.getOpenCLVersionString()
<< Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
auto DefaultCC = LangOpts.getDefaultCallingConv();
bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
DefaultCC == LangOptions::DCC_StdCall) &&
Arch != llvm::Triple::x86;
emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
DefaultCC == LangOptions::DCC_RegCall) &&
!T.isX86();
emitError |= DefaultCC == LangOptions::DCC_RtdCall && Arch != llvm::Triple::m68k;
if (emitError)
Diags.Report(diag::err_drv_argument_not_allowed_with)
<< A->getSpelling() << T.getTriple();
}
return Diags.getNumErrors() == NumErrorsBefore;
}
//===----------------------------------------------------------------------===//
// Deserialization (from args)
//===----------------------------------------------------------------------===//
static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
DiagnosticsEngine &Diags) {
unsigned DefaultOpt = 0;
if ((IK.getLanguage() == Language::OpenCL ||
IK.getLanguage() == Language::OpenCLCXX) &&
!Args.hasArg(OPT_cl_opt_disable))
DefaultOpt = 2;
if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
if (A->getOption().matches(options::OPT_O0))
return 0;
if (A->getOption().matches(options::OPT_Ofast))
return 3;
assert(A->getOption().matches(options::OPT_O));
StringRef S(A->getValue());
if (S == "s" || S == "z")
return 2;
if (S == "g")
return 1;
return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
}
return DefaultOpt;
}
static unsigned getOptimizationLevelSize(ArgList &Args) {
if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
if (A->getOption().matches(options::OPT_O)) {
switch (A->getValue()[0]) {
default:
return 0;
case 's':
return 1;
case 'z':
return 2;
}
}
}
return 0;
}
static void GenerateArg(ArgumentConsumer Consumer,
llvm::opt::OptSpecifier OptSpecifier) {
Option Opt = getDriverOptTable().getOption(OptSpecifier);
denormalizeSimpleFlag(Consumer, Opt.getPrefixedName(),
Option::OptionClass::FlagClass, 0);
}
static void GenerateArg(ArgumentConsumer Consumer,
llvm::opt::OptSpecifier OptSpecifier,
const Twine &Value) {
Option Opt = getDriverOptTable().getOption(OptSpecifier);
denormalizeString(Consumer, Opt.getPrefixedName(), Opt.getKind(), 0, Value);
}
// Parse command line arguments into CompilerInvocation.
using ParseFn =
llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>,
DiagnosticsEngine &, const char *)>;
// Generate command line arguments from CompilerInvocation.
using GenerateFn = llvm::function_ref<void(
CompilerInvocation &, SmallVectorImpl<const char *> &,
CompilerInvocation::StringAllocator)>;
/// May perform round-trip of command line arguments. By default, the round-trip
/// is enabled in assert builds. This can be overwritten at run-time via the
/// "-round-trip-args" and "-no-round-trip-args" command line flags, or via the
/// ForceRoundTrip parameter.
///
/// During round-trip, the command line arguments are parsed into a dummy
/// CompilerInvocation, which is used to generate the command line arguments
/// again. The real CompilerInvocation is then created by parsing the generated
/// arguments, not the original ones. This (in combination with tests covering
/// argument behavior) ensures the generated command line is complete (doesn't
/// drop/mangle any arguments).
///
/// Finally, we check the command line that was used to create the real
/// CompilerInvocation instance. By default, we compare it to the command line
/// the real CompilerInvocation generates. This checks whether the generator is
/// deterministic. If \p CheckAgainstOriginalInvocation is enabled, we instead
/// compare it to the original command line to verify the original command-line
/// was canonical and can round-trip exactly.
static bool RoundTrip(ParseFn Parse, GenerateFn Generate,
CompilerInvocation &RealInvocation,
CompilerInvocation &DummyInvocation,
ArrayRef<const char *> CommandLineArgs,
DiagnosticsEngine &Diags, const char *Argv0,
bool CheckAgainstOriginalInvocation = false,
bool ForceRoundTrip = false) {
#ifndef NDEBUG
bool DoRoundTripDefault = true;
#else
bool DoRoundTripDefault = false;
#endif
bool DoRoundTrip = DoRoundTripDefault;
if (ForceRoundTrip) {
DoRoundTrip = true;
} else {
for (const auto *Arg : CommandLineArgs) {
if (Arg == StringRef("-round-trip-args"))
DoRoundTrip = true;
if (Arg == StringRef("-no-round-trip-args"))
DoRoundTrip = false;
}
}
// If round-trip was not requested, simply run the parser with the real
// invocation diagnostics.
if (!DoRoundTrip)
return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
// Serializes quoted (and potentially escaped) arguments.
auto SerializeArgs = [](ArrayRef<const char *> Args) {
std::string Buffer;
llvm::raw_string_ostream OS(Buffer);
for (const char *Arg : Args) {
llvm::sys::printArg(OS, Arg, /*Quote=*/true);
OS << ' ';
}
OS.flush();
return Buffer;
};
// Setup a dummy DiagnosticsEngine.
DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions());
DummyDiags.setClient(new TextDiagnosticBuffer());
// Run the first parse on the original arguments with the dummy invocation and
// diagnostics.
if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
DummyDiags.getNumWarnings() != 0) {
// If the first parse did not succeed, it must be user mistake (invalid
// command line arguments). We won't be able to generate arguments that
// would reproduce the same result. Let's fail again with the real
// invocation and diagnostics, so all side-effects of parsing are visible.
unsigned NumWarningsBefore = Diags.getNumWarnings();
auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
return Success;
// Parse with original options and diagnostics succeeded even though it
// shouldn't have. Something is off.
Diags.Report(diag::err_cc1_round_trip_fail_then_ok);
Diags.Report(diag::note_cc1_round_trip_original)
<< SerializeArgs(CommandLineArgs);
return false;
}
// Setup string allocator.
llvm::BumpPtrAllocator Alloc;
llvm::StringSaver StringPool(Alloc);
auto SA = [&StringPool](const Twine &Arg) {
return StringPool.save(Arg).data();
};
// Generate arguments from the dummy invocation. If Generate is the
// inverse of Parse, the newly generated arguments must have the same
// semantics as the original.
SmallVector<const char *> GeneratedArgs;
Generate(DummyInvocation, GeneratedArgs, SA);
// Run the second parse, now on the generated arguments, and with the real
// invocation and diagnostics. The result is what we will end up using for the
// rest of compilation, so if Generate is not inverse of Parse, something down
// the line will break.
bool Success2 = Parse(RealInvocation, GeneratedArgs, Diags, Argv0);
// The first parse on original arguments succeeded, but second parse of
// generated arguments failed. Something must be wrong with the generator.
if (!Success2) {
Diags.Report(diag::err_cc1_round_trip_ok_then_fail);
Diags.Report(diag::note_cc1_round_trip_generated)
<< 1 << SerializeArgs(GeneratedArgs);
return false;
}
SmallVector<const char *> ComparisonArgs;
if (CheckAgainstOriginalInvocation)
// Compare against original arguments.
ComparisonArgs.assign(CommandLineArgs.begin(), CommandLineArgs.end());
else
// Generate arguments again, this time from the options we will end up using
// for the rest of the compilation.
Generate(RealInvocation, ComparisonArgs, SA);
// Compares two lists of arguments.
auto Equal = [](const ArrayRef<const char *> A,
const ArrayRef<const char *> B) {
return std::equal(A.begin(), A.end(), B.begin(), B.end(),
[](const char *AElem, const char *BElem) {
return StringRef(AElem) == StringRef(BElem);
});
};
// If we generated different arguments from what we assume are two
// semantically equivalent CompilerInvocations, the Generate function may
// be non-deterministic.
if (!Equal(GeneratedArgs, ComparisonArgs)) {
Diags.Report(diag::err_cc1_round_trip_mismatch);
Diags.Report(diag::note_cc1_round_trip_generated)
<< 1 << SerializeArgs(GeneratedArgs);
Diags.Report(diag::note_cc1_round_trip_generated)
<< 2 << SerializeArgs(ComparisonArgs);
return false;
}
Diags.Report(diag::remark_cc1_round_trip_generated)
<< 1 << SerializeArgs(GeneratedArgs);
Diags.Report(diag::remark_cc1_round_trip_generated)
<< 2 << SerializeArgs(ComparisonArgs);
return Success2;
}
bool CompilerInvocation::checkCC1RoundTrip(ArrayRef<const char *> Args,
DiagnosticsEngine &Diags,
const char *Argv0) {
CompilerInvocation DummyInvocation1, DummyInvocation2;
return RoundTrip(
[](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
DiagnosticsEngine &Diags, const char *Argv0) {
return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
},
[](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
StringAllocator SA) {
Args.push_back("-cc1");
Invocation.generateCC1CommandLine(Args, SA);
},
DummyInvocation1, DummyInvocation2, Args, Diags, Argv0,
/*CheckAgainstOriginalInvocation=*/true, /*ForceRoundTrip=*/true);
}
static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
OptSpecifier GroupWithValue,
std::vector<std::string> &Diagnostics) {
for (auto *A : Args.filtered(Group)) {
if (A->getOption().getKind() == Option::FlagClass) {
// The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
// its name (minus the "W" or "R" at the beginning) to the diagnostics.
Diagnostics.push_back(
std::string(A->getOption().getName().drop_front(1)));
} else if (A->getOption().matches(GroupWithValue)) {
// This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic
// group. Add only the group name to the diagnostics.
Diagnostics.push_back(
std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
} else {
// Otherwise, add its value (for OPT_W_Joined and similar).
Diagnostics.push_back(A->getValue());
}
}
}
// Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
// it won't verify the input.
static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
DiagnosticsEngine *Diags);
static void getAllNoBuiltinFuncValues(ArgList &Args,
std::vector<std::string> &Funcs) {
std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_);
auto BuiltinEnd = llvm::partition(Values, Builtin::Context::isBuiltinFunc);
Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
}
static void GenerateAnalyzerArgs(const AnalyzerOptions &Opts,
ArgumentConsumer Consumer) {
const AnalyzerOptions *AnalyzerOpts = &Opts;
#define ANALYZER_OPTION_WITH_MARSHALLING(...) \
GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
#include "clang/Driver/Options.inc"
#undef ANALYZER_OPTION_WITH_MARSHALLING
if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) {
switch (Opts.AnalysisConstraintsOpt) {
#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
case NAME##Model: \
GenerateArg(Consumer, OPT_analyzer_constraints, CMDFLAG); \
break;
#include "clang/StaticAnalyzer/Core/Analyses.def"
default:
llvm_unreachable("Tried to generate unknown analysis constraint.");
}
}
if (Opts.AnalysisDiagOpt != PD_HTML) {
switch (Opts.AnalysisDiagOpt) {
#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
case PD_##NAME: \
GenerateArg(Consumer, OPT_analyzer_output, CMDFLAG); \
break;
#include "clang/StaticAnalyzer/Core/Analyses.def"
default:
llvm_unreachable("Tried to generate unknown analysis diagnostic client.");
}
}
if (Opts.AnalysisPurgeOpt != PurgeStmt) {
switch (Opts.AnalysisPurgeOpt) {
#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
case NAME: \
GenerateArg(Consumer, OPT_analyzer_purge, CMDFLAG); \
break;
#include "clang/StaticAnalyzer/Core/Analyses.def"
default:
llvm_unreachable("Tried to generate unknown analysis purge mode.");
}
}
if (Opts.InliningMode != NoRedundancy) {
switch (Opts.InliningMode) {
#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
case NAME: \
GenerateArg(Consumer, OPT_analyzer_inlining_mode, CMDFLAG); \
break;
#include "clang/StaticAnalyzer/Core/Analyses.def"
default:
llvm_unreachable("Tried to generate unknown analysis inlining mode.");
}
}
for (const auto &CP : Opts.CheckersAndPackages) {
OptSpecifier Opt =
CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker;
GenerateArg(Consumer, Opt, CP.first);
}
AnalyzerOptions ConfigOpts;
parseAnalyzerConfigs(ConfigOpts, nullptr);