-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathAsmParser.cpp
More file actions
1423 lines (1266 loc) · 45.8 KB
/
AsmParser.cpp
File metadata and controls
1423 lines (1266 loc) · 45.8 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
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
//===------------------------- AsmParser.cpp --------------------*- C++ -*-===//
//
// 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 "AsmParser.h"
#include "AsmIdentifierTable.h"
#include "AsmLexer.h"
#include "AsmToken.h"
#include "AsmTokenKinds.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/Type.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Sema/Ownership.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include <cassert>
#include <cstdint>
using namespace llvm;
using namespace clang::dpct;
// clang-format off
asm_precedence::Level getBinOpPrec(asmtok::TokenKind Kind) {
switch (Kind) {
default: return asm_precedence::Unknown;
case asmtok::question: return asm_precedence::Conditional;
case asmtok::pipepipe: return asm_precedence::LogicalOr;
case asmtok::ampamp: return asm_precedence::LogicalAnd;
case asmtok::pipe: return asm_precedence::InclusiveOr;
case asmtok::caret: return asm_precedence::ExclusiveOr;
case asmtok::amp: return asm_precedence::And;
case asmtok::exclaimequal:
case asmtok::equalequal: return asm_precedence::Equality;
case asmtok::lessequal:
case asmtok::less:
case asmtok::greater:
case asmtok::greaterequal: return asm_precedence::Relational;
case asmtok::greatergreater:
case asmtok::lessless: return asm_precedence::Shift;
case asmtok::plus:
case asmtok::minus: return asm_precedence::Additive;
case asmtok::percent:
case asmtok::slash:
case asmtok::star: return asm_precedence::Multiplicative;
}
}
// clang-format on
InlineAsmVarDecl *
InlineAsmScope::lookupDecl(InlineAsmIdentifierInfo *II) const {
if (!II)
return nullptr;
for (const auto &S : decls()) {
if (S->getDeclName() == II)
return S;
}
if (hasParent()) {
return getParent()->lookupDecl(II);
}
return nullptr;
}
InlineAsmVarDecl *
InlineAsmScope::lookupParameterizedNameDecl(InlineAsmIdentifierInfo *II,
unsigned &Idx) const {
if (!II)
return nullptr;
StringRef Name = II->getName().take_while(
[](char C) -> bool { return isAlpha(C) || C == '_'; });
StringRef Count = II->getName().drop_until(isDigit);
if (Name.empty() || Count.empty() || Count.getAsInteger(10, Idx))
return nullptr;
InlineAsmIdentifierInfo *RealII = Parser.getLexer().getIdentifierInfo(Name);
if (!RealII)
return nullptr;
InlineAsmVarDecl *D = lookupDecl(RealII);
if (D && D->isParameterizedNameDecl() && Idx < D->getNumParameterizedNames())
return D;
return nullptr;
}
void InlineAsmParser::addBuiltinIdentifier() {
#define SPECIAL_REG(X, Y, Z) \
getCurScope()->addDecl(::new (Context) InlineAsmVarDecl( \
getLexer().getIdentifierInfo(Y), AsmStateSpace::S_sreg, \
Context.getBuiltinTypeFromTokenKind(asmtok::kw_##Z)));
#include "AsmTokenKinds.def"
}
InlineAsmBuiltinType *
InlineAsmContext::getBuiltinType(InlineAsmBuiltinType::TypeKind Kind) {
assert(Kind >= 0 && Kind < InlineAsmBuiltinType::NUM_TYPES && "Unknown Kind");
if (AsmBuiltinTypes[Kind])
return AsmBuiltinTypes[Kind];
InlineAsmBuiltinType *NewType = ::new (*this) InlineAsmBuiltinType(Kind);
AsmBuiltinTypes[Kind] = NewType;
return NewType;
}
InlineAsmBuiltinType *
InlineAsmContext::getBuiltinTypeFromTokenKind(asmtok::TokenKind Kind) {
switch (Kind) {
#define BUILTIN_TYPE(X, Y) \
case asmtok::kw_##X: \
return getBuiltinType(InlineAsmBuiltinType::X);
#include "AsmTokenKinds.def"
default:
break;
}
return nullptr;
}
InlineAsmDiscardType *InlineAsmContext::getDiscardType() {
if (!DiscardType)
DiscardType = ::new (*this) InlineAsmDiscardType;
return DiscardType;
}
InlineAsmBuiltinType *
InlineAsmContext::getTypeFromConstraint(StringRef Constraint) {
if (Constraint.size() != 1) {
StringRef AllowedConstraint = "hrlfd";
Constraint = Constraint.drop_until(
[&](char C) -> bool { return AllowedConstraint.contains(C); });
if (Constraint.empty())
return nullptr;
}
switch (Constraint[0]) {
case 'h':
return getBuiltinType(InlineAsmBuiltinType::u16);
case 'r':
return getBuiltinType(InlineAsmBuiltinType::u32);
case 'l':
return getBuiltinType(InlineAsmBuiltinType::u64);
case 'f':
return getBuiltinType(InlineAsmBuiltinType::f32);
case 'd':
return getBuiltinType(InlineAsmBuiltinType::f64);
default:
break;
}
return nullptr;
}
InlineAsmBuiltinType *InlineAsmContext::getTypeFromClangType(const Type *T) {
if (T->isBuiltinType()) {
auto *BT = T->getAs<clang::BuiltinType>();
switch (BT->getKind()) {
case BuiltinType::SChar:
return getBuiltinType(InlineAsmBuiltinType::s8);
case BuiltinType::UChar:
return getBuiltinType(InlineAsmBuiltinType::u8);
case BuiltinType::Char_S:
return getBuiltinType(InlineAsmBuiltinType::s8);
case BuiltinType::Char_U:
return getBuiltinType(InlineAsmBuiltinType::u8);
case BuiltinType::Char8:
return getBuiltinType(InlineAsmBuiltinType::u8);
case BuiltinType::Char16:
return getBuiltinType(InlineAsmBuiltinType::u16);
case BuiltinType::Char32:
return getBuiltinType(InlineAsmBuiltinType::u32);
case BuiltinType::WChar_S:
return getBuiltinType(InlineAsmBuiltinType::s32);
case BuiltinType::WChar_U:
return getBuiltinType(InlineAsmBuiltinType::u32);
case BuiltinType::Short:
return getBuiltinType(InlineAsmBuiltinType::s16);
case BuiltinType::UShort:
return getBuiltinType(InlineAsmBuiltinType::u16);
case BuiltinType::UInt:
return getBuiltinType(InlineAsmBuiltinType::u32);
case BuiltinType::ULong:
return getBuiltinType(InlineAsmBuiltinType::u64);
case BuiltinType::ULongLong:
return getBuiltinType(InlineAsmBuiltinType::u64);
case BuiltinType::Int:
return getBuiltinType(InlineAsmBuiltinType::s32);
case BuiltinType::Long:
return getBuiltinType(InlineAsmBuiltinType::s64);
case BuiltinType::LongLong:
return getBuiltinType(InlineAsmBuiltinType::s64);
case BuiltinType::Float:
return getBuiltinType(InlineAsmBuiltinType::f32);
case BuiltinType::Double:
return getBuiltinType(InlineAsmBuiltinType::f64);
case BuiltinType::NullPtr:
return getBuiltinType(InlineAsmBuiltinType::u64);
case BuiltinType::Float16:
return getBuiltinType(InlineAsmBuiltinType::f16);
default:
break;
}
}
// print raw typename without 'struct' prefix
PrintingPolicy Policy(LangOptions{});
Policy.adjustForCPlusPlus();
std::string TypeName = T->getCanonicalTypeInternal().getAsString(Policy);
return llvm::StringSwitch<InlineAsmBuiltinType *>(TypeName)
.Case("__half", getBuiltinType(InlineAsmBuiltinType::f16))
.Case("__half2", getBuiltinType(InlineAsmBuiltinType::f16x2))
.Case("__half_raw", getBuiltinType(InlineAsmBuiltinType::f16))
.Case("__half_raw2", getBuiltinType(InlineAsmBuiltinType::f16x2))
.Case("__nv_bfloat16", getBuiltinType(InlineAsmBuiltinType::bf16))
.Case("__nv_bfloat162", getBuiltinType(InlineAsmBuiltinType::bf16x2))
.Case("__nv_bfloat16_raw", getBuiltinType(InlineAsmBuiltinType::bf16))
.Case("__nv_bfloat162_raw", getBuiltinType(InlineAsmBuiltinType::bf16x2))
.Default(nullptr);
}
InlineAsmDeclResult
InlineAsmParser::addInlineAsmOperands(const Expr *E, StringRef Operand,
StringRef Constraint) {
unsigned Index = Context.addInlineAsmOperand(Operand);
InlineAsmIdentifierInfo *II = Context.get(Index);
InlineAsmType *Type = Context.getTypeFromClangType(E->getType().getTypePtr());
if (!Type)
Type = Context.getTypeFromConstraint(Constraint);
if (!Type)
return AsmDeclError();
InlineAsmVarDecl *VD =
::new (Context) InlineAsmVarDecl(II, AsmStateSpace::S_reg, Type);
VD->setInlineAsmOp(E);
getCurScope()->addDecl(VD);
return VD;
}
InlineAsmStmtResult InlineAsmParser::ParseStatement() {
switch (Tok.getKind()) {
case asmtok::l_brace:
return ParseCompoundStatement();
case asmtok::at:
return ParseConditionalInstruction();
#define STATE_SPACE(X, Y) \
case asmtok::kw_##X: \
return ParseDeclarationStatement();
#include "AsmTokenKinds.def"
#define INSTRUCTION(X) \
case asmtok::op_##X: \
return ParseInstruction();
#include "AsmTokenKinds.def"
default:
break;
}
return AsmStmtError();
}
InlineAsmStmtResult InlineAsmParser::ParseCompoundStatement() {
ConsumeToken();
ParseScope BlockScope(this);
SmallVector<InlineAsmStmt *, 4> Stmts;
while (Tok.isNot(asmtok::r_brace) && Tok.isNot(asmtok::eof)) {
InlineAsmStmtResult Result = ParseStatement();
if (Result.isInvalid())
return AsmStmtError();
Stmts.push_back(Result.get());
}
if (!TryConsumeToken(asmtok::r_brace))
return AsmStmtError();
return ::new (Context) InlineAsmCompoundStmt(Stmts);
}
InlineAsmStmtResult InlineAsmParser::ParseConditionalInstruction() {
if (!TryConsumeToken(asmtok::at))
return AsmStmtError();
bool isNeg = false;
if (TryConsumeToken(asmtok::exclaim)) {
isNeg = true;
}
InlineAsmExprResult Pred = ParseExpression();
if (Pred.isInvalid())
return AsmStmtError();
InlineAsmStmtResult SubInst = ParseInstruction();
if (SubInst.isInvalid())
return AsmStmtError();
return ::new (Context) InlineAsmConditionalInstruction(
isNeg, Pred.get(), SubInst.getAs<InlineAsmInstruction>());
}
static inline InstAttr ConvertToInstAttr(asmtok::TokenKind Kind) {
switch (Kind) {
#define MODIFIER(X, Y) \
case asmtok::kw_##X: \
return InstAttr::X;
#include "AsmTokenKinds.def"
default:
llvm_unreachable("Kind is not an instruction attribute");
}
}
static inline AsmStateSpace ConvertToStateSpace(asmtok::TokenKind Kind) {
switch (Kind) {
#define STATE_SPACE(X, Y) \
case asmtok::kw_##X: \
return AsmStateSpace::S_##X;
#include "AsmTokenKinds.def"
default:
llvm_unreachable("Kind is not a state space");
}
}
InlineAsmStmtResult InlineAsmParser::ParseInstruction() {
if (!Tok.getIdentifier() || !Tok.getIdentifier()->isInstruction())
return AsmStmtError();
InlineAsmIdentifierInfo *Opcode = Tok.getIdentifier();
ConsumeToken();
SmallVector<InstAttr, 4> Attrs;
SmallVector<InlineAsmType *, 4> Types;
SmallVector<InlineAsmExpr *, 4> Ops;
SmallVector<AsmStateSpace, 4> StateSpaces;
while (Tok.startOfDot()) {
switch (Tok.getIdentifier()->getFlags()) {
case InlineAsmIdentifierInfo::BuiltinType:
Types.push_back(Context.getBuiltinTypeFromTokenKind(Tok.getKind()));
break;
case InlineAsmIdentifierInfo::Modifier:
Attrs.push_back(ConvertToInstAttr(Tok.getKind()));
break;
case InlineAsmIdentifierInfo::StateSpace:
StateSpaces.push_back(ConvertToStateSpace(Tok.getKind()));
break;
default:
return AsmStmtError();
}
ConsumeToken(); // consume instruction attribute
}
InlineAsmExprResult Pred, Out;
if ((Out = ParseExpression()).isInvalid())
return AsmStmtError();
if (TryConsumeToken(asmtok::pipe) && (Pred = ParseExpression()).isInvalid())
return AsmStmtError();
while (TryConsumeToken(asmtok::comma)) {
InlineAsmExprResult E = ParseExpression();
if (E.isInvalid())
return AsmStmtError();
Ops.push_back(E.get());
}
if (!TryConsumeToken(asmtok::semi))
return AsmStmtError();
// bar.warp.sync only has one input operand.
if (Opcode->getTokenID() == asmtok::op_bar) {
Ops.push_back(Out.get());
Out = nullptr;
}
// prefetch{.state}.{level} [%0] has only one input operand and no type.
if (Opcode->getTokenID() == asmtok::op_prefetch) {
Ops.push_back(Out.get());
Out = nullptr;
Types.push_back(Context.getBuiltinType(InlineAsmBuiltinType::byte));
}
if (Opcode->getTokenID() == asmtok::op_cp) {
Ops.push_back(Out.get());
Out = nullptr;
Types.push_back(Context.getBuiltinType(InlineAsmBuiltinType::u32));
}
return ::new (Context) InlineAsmInstruction(Opcode, StateSpaces, Attrs, Types,
Out.get(), Pred.get(), Ops);
}
InlineAsmExprResult InlineAsmParser::ParseExpression() {
return ParseAssignmentExpression();
}
InlineAsmExprResult InlineAsmParser::ParseAssignmentExpression() {
InlineAsmExprResult LHS = ParseCastExpression();
return ParseRHSOfBinaryExpression(LHS, asm_precedence::Assignment);
}
InlineAsmExprResult
InlineAsmParser::ParseRHSOfBinaryExpression(InlineAsmExprResult LHS,
asm_precedence::Level MinPrec) {
asm_precedence::Level NextTokPrec = getBinOpPrec(Tok.getKind());
while (true) {
if (NextTokPrec < MinPrec)
return LHS;
InlineAsmToken OpTok = Tok;
ConsumeToken();
// Special case handling for the ternary operator.
bool isCondOp = false;
InlineAsmExprResult TernaryMiddle(true);
if (NextTokPrec == asm_precedence::Conditional) {
isCondOp = true;
if (Tok.isNot(asmtok::colon)) {
TernaryMiddle = ParseExpression();
if (TernaryMiddle.isInvalid())
return AsmExprError();
} else {
return AsmExprError();
}
if (!TryConsumeToken(asmtok::colon)) {
return AsmExprError();
}
}
InlineAsmExprResult RHS = ParseCastExpression();
if (RHS.isInvalid())
return AsmExprError();
asm_precedence::Level ThisPrec = NextTokPrec;
NextTokPrec = getBinOpPrec(Tok.getKind());
bool isRightAssoc = ThisPrec == asm_precedence::Conditional ||
ThisPrec == asm_precedence::Assignment;
if (ThisPrec < NextTokPrec || (ThisPrec == NextTokPrec && isRightAssoc)) {
RHS = ParseRHSOfBinaryExpression(
RHS, static_cast<asm_precedence::Level>(ThisPrec + !isRightAssoc));
if (RHS.isInvalid())
return AsmExprError();
}
NextTokPrec = getBinOpPrec(Tok.getKind());
if (isCondOp) {
LHS = ActOnConditionalOp(LHS.get(), TernaryMiddle.get(), RHS.get());
} else {
LHS = ActOnBinaryOp(OpTok.getKind(), LHS.get(), RHS.get());
}
if (LHS.isInvalid())
return AsmExprError();
}
}
InlineAsmExprResult InlineAsmParser::ParseCastExpression() {
InlineAsmExprResult Res;
auto SavedKind = Tok.getKind();
switch (SavedKind) {
case asmtok::semi:
break;
case asmtok::l_paren:
ConsumeToken();
if (Tok.isOneOf(asmtok::kw_s64, asmtok::kw_u64)) {
InlineAsmBuiltinType *CastTy =
Tok.is(asmtok::kw_s64) ? Context.getS64Type() : Context.getU64Type();
if (!TryConsumeToken(asmtok::r_paren))
return AsmExprError();
InlineAsmExprResult SubExpr = ParseCastExpression();
if (SubExpr.isInvalid())
return AsmExprError();
Res = ActOnTypeCast(CastTy, SubExpr.get());
} else {
InlineAsmExprResult SubExpr = ParseExpression();
if (SubExpr.isInvalid())
return AsmExprError();
if (!TryConsumeToken(asmtok::r_paren))
return AsmExprError();
Res = ActOnParenExpr(SubExpr.get());
}
break;
case asmtok::l_square:
ConsumeToken();
Res = ParseExpression();
if (Res.isInvalid())
return AsmExprError();
if (!TryConsumeToken(asmtok::r_square))
return AsmExprError();
Res = ActOnAddressExpr(Res.get());
break;
case asmtok::l_brace: {
ConsumeToken();
SmallVector<InlineAsmExpr *, 4> Tuple;
while (true) {
Res = ParseExpression();
if (Res.isInvalid())
return AsmExprError();
Tuple.push_back(Res.get());
if (!TryConsumeToken(asmtok::comma))
break;
}
if (!TryConsumeToken(asmtok::r_brace))
return AsmExprError();
Res = ActOnVectorExpr(Tuple);
break;
}
case asmtok::underscore:
Res = ActOnDiscardExpr();
ConsumeToken();
break;
case asmtok::numeric_constant:
Res = ActOnNumericConstant(Tok);
ConsumeToken();
break;
case asmtok::identifier:
#define SPECIAL_REG(X, Y, Z) case asmtok::bi_##X:
#include "AsmTokenKinds.def"
Res = ActOnIdExpr(Tok.getIdentifier());
ConsumeToken();
break;
case asmtok::plus: // unary-expression: '+' cast-expression
case asmtok::minus: // unary-expression: '-' cast-expression
case asmtok::tilde: // unary-expression: '~' cast-expression
case asmtok::exclaim: // unary-expression: '!' cast-expression
ConsumeToken();
Res = ParseCastExpression();
if (Res.isInvalid())
return AsmExprError();
Res = ActOnUnaryOp(SavedKind, Res.get());
break;
default:
return AsmExprError();
}
return Res;
}
InlineAsmStmtResult InlineAsmParser::ParseDeclarationStatement() {
InlineAsmDeclarationSpecifier DeclSpec;
InlineAsmTypeResult Type = ParseDeclarationSpecifier(DeclSpec);
if (Type.isInvalid())
return AsmStmtError();
SmallVector<InlineAsmDecl *, 4> Decls;
while (true) {
InlineAsmDeclResult DeclRes = ParseDeclarator(DeclSpec);
if (DeclRes.isInvalid())
return AsmStmtError();
Decls.push_back(DeclRes.get());
if (!TryConsumeToken(asmtok::comma))
break;
}
if (!TryConsumeToken(asmtok::semi))
return AsmStmtError();
return ::new (Context) InlineAsmDeclStmt(DeclSpec, Decls);
}
InlineAsmTypeResult InlineAsmParser::ParseDeclarationSpecifier(
InlineAsmDeclarationSpecifier &DeclSpec) {
// Only support register variable
DeclSpec.StateSpace = Tok.getKind();
switch (Tok.getKind()) {
case asmtok::kw_reg:
case asmtok::kw_sreg:
ConsumeToken();
break;
case asmtok::kw_const:
case asmtok::kw_global:
case asmtok::kw_local:
case asmtok::kw_shared:
case asmtok::kw_param:
case asmtok::kw_tex:
default:
return AsmTypeError();
}
if (TryConsumeToken(asmtok::kw_align)) {
InlineAsmExprResult AlignmentRes = ParseExpression();
if (AlignmentRes.isInvalid())
return AsmTypeError();
AlignmentRes = ActOnAlignment(AlignmentRes.get());
if (AlignmentRes.isInvalid())
return AsmTypeError();
DeclSpec.Alignment = cast<InlineAsmIntegerLiteral>(AlignmentRes.get());
}
if (Tok.isOneOf(asmtok::kw_v2, asmtok::kw_v4)) {
DeclSpec.VectorTypeKind = Tok.getKind();
ConsumeToken();
}
switch (Tok.getKind()) {
#define BUILTIN_TYPE(X, Y) \
case asmtok::kw_##X: \
DeclSpec.BaseType = Context.getBuiltinType(InlineAsmBuiltinType::X); \
ConsumeToken(); \
break;
#include "AsmTokenKinds.def"
default:
return AsmTypeError();
}
switch (DeclSpec.VectorTypeKind) {
case asmtok::unknown:
DeclSpec.Type = DeclSpec.BaseType;
break;
case asmtok::kw_v2:
DeclSpec.Type = ::new (Context)
InlineAsmVectorType(InlineAsmVectorType::v2, DeclSpec.BaseType);
break;
case asmtok::kw_v4:
DeclSpec.Type = ::new (Context)
InlineAsmVectorType(InlineAsmVectorType::v4, DeclSpec.BaseType);
break;
default:
assert(0 && "unexpected vector type");
}
return DeclSpec.Type;
}
InlineAsmDeclResult InlineAsmParser::ParseDeclarator(
const InlineAsmDeclarationSpecifier &DeclSpec) {
if (Tok.isNot(asmtok::identifier))
return AsmDeclError();
auto *Name = Tok.getIdentifier();
ConsumeToken();
auto VarRes = ActOnVariableDecl(
Name, ConvertToStateSpace(DeclSpec.StateSpace), DeclSpec.Type);
if (VarRes.isInvalid())
return AsmDeclError();
InlineAsmVarDecl *Decl = VarRes.getAs<InlineAsmVarDecl>();
if (DeclSpec.Alignment) {
Decl->setAlign(DeclSpec.Alignment->getValue().getZExtValue());
}
switch (Tok.getKind()) {
case asmtok::less: { // Parameterized variable declaration
ConsumeToken();
if (Tok.isNot(asmtok::numeric_constant))
return AsmDeclError();
InlineAsmExprResult NumRes = ActOnNumericConstant(Tok);
ConsumeToken();
if (!TryConsumeToken(asmtok::greater))
return AsmDeclError();
if (NumRes.isInvalid())
return AsmDeclError();
if (const auto *Int = dyn_cast<InlineAsmIntegerLiteral>(NumRes.get())) {
unsigned Num = Int->getValue().getZExtValue();
Decl->setNumParameterizedNames(Num);
// Parameterized variable declaration dosen't support for arrays and init.
return Decl;
}
return AsmDeclError();
}
case asmtok::l_square:
/// FIXME: Support array declaration
break;
default:
break;
}
if (Tok.is(asmtok::equal)) {
/// FIXME: Support assignment and initializer init.
}
return Decl;
}
InlineAsmExprResult InlineAsmParser::ActOnDiscardExpr() {
return ::new (Context) InlineAsmDiscardExpr(Context.getDiscardType());
}
InlineAsmExprResult InlineAsmParser::ActOnAddressExpr(InlineAsmExpr *SubExpr) {
InlineAsmAddressExpr::MemOpKind Kind;
InlineAsmDeclRefExpr *SymbolRef = nullptr;
InlineAsmIntegerLiteral *ImmAddr = nullptr;
auto IsReg = [](const InlineAsmDeclRefExpr *DRE) {
auto *VD = dyn_cast_or_null<InlineAsmVarDecl>(&DRE->getDecl());
return VD && VD->getStorageClass() == AsmStateSpace::S_reg;
};
switch (SubExpr->getStmtClass()) {
case InlineAsmStmt::IntegerLiteralClass:
Kind = InlineAsmAddressExpr::Imm;
ImmAddr = dyn_cast<InlineAsmIntegerLiteral>(SubExpr);
break;
case InlineAsmStmt::DeclRefExprClass:
SymbolRef = dyn_cast<InlineAsmDeclRefExpr>(SubExpr);
Kind = IsReg(SymbolRef) ? InlineAsmAddressExpr::Reg
: InlineAsmAddressExpr::Var;
break;
case InlineAsmStmt::BinaryOperatorClass: {
auto *BinOp = dyn_cast<InlineAsmBinaryOperator>(SubExpr);
if (auto *LHS = dyn_cast<InlineAsmDeclRefExpr>(BinOp->getLHS()))
SymbolRef = LHS;
if (auto *RHS = dyn_cast<InlineAsmIntegerLiteral>(BinOp->getRHS()))
ImmAddr = RHS;
if (!SymbolRef || !ImmAddr)
return AsmExprError();
Kind = IsReg(SymbolRef) ? InlineAsmAddressExpr::RegImm
: InlineAsmAddressExpr::VarImm;
break;
}
default:
return AsmExprError();
}
return ::new (Context)
InlineAsmAddressExpr(Context.getS64Type(), Kind, SymbolRef, ImmAddr);
}
InlineAsmExprResult InlineAsmParser::ActOnIdExpr(InlineAsmIdentifierInfo *II) {
if (auto *D = getCurScope()->lookupDecl(II)) {
return ::new (Context) InlineAsmDeclRefExpr(D);
}
unsigned ParameterizedNameIdx;
// Maybe this identifier is a parameterized variable name
if (auto *D = getCurScope()->lookupParameterizedNameDecl(
II, ParameterizedNameIdx)) {
return ::new (Context) InlineAsmDeclRefExpr(D, ParameterizedNameIdx);
}
return AsmExprError();
}
InlineAsmExprResult InlineAsmParser::ActOnParenExpr(InlineAsmExpr *SubExpr) {
return ::new (Context) InlineAsmParenExpr(SubExpr);
}
InlineAsmExprResult
InlineAsmParser::ActOnVectorExpr(ArrayRef<InlineAsmExpr *> Vec) {
// Vector size must be 2, 4, or 8.
InlineAsmVectorType::VecKind Kind;
switch (Vec.size()) {
case 1:
Kind = InlineAsmVectorType::v1;
break;
case 2:
Kind = InlineAsmVectorType::v2;
break;
case 4:
Kind = InlineAsmVectorType::v4;
break;
case 8:
Kind = InlineAsmVectorType::v8;
break;
default:
return AsmExprError();
}
InlineAsmBuiltinType *ElementType = nullptr;
// The type of each element must have the same non-predicate builtin type.
for (auto *E : Vec) {
if (isa<InlineAsmDiscardExpr>(E))
continue;
if (auto *T = dyn_cast<InlineAsmBuiltinType>(E->getType())) {
if (T->getKind() == InlineAsmBuiltinType::pred)
return AsmExprError();
if (ElementType && ElementType->getKind() != T->getKind())
return AsmExprError();
if (!ElementType)
ElementType = T;
} else {
return AsmExprError();
}
}
InlineAsmVectorType *Type =
::new (Context) InlineAsmVectorType(Kind, ElementType);
return ::new (Context) InlineAsmVectorExpr(Type, Vec);
}
InlineAsmExprResult InlineAsmParser::ActOnTypeCast(InlineAsmBuiltinType *CastTy,
InlineAsmExpr *SubExpr) {
return ::new (Context) InlineAsmCastExpr(CastTy, SubExpr);
}
InlineAsmExprResult InlineAsmParser::ActOnUnaryOp(asmtok::TokenKind OpTok,
InlineAsmExpr *SubExpr) {
InlineAsmUnaryOperator::Opcode Opcode;
switch (OpTok) {
case asmtok::plus:
Opcode = InlineAsmUnaryOperator::Plus;
break;
case asmtok::minus:
Opcode = InlineAsmUnaryOperator::Minus;
break;
case asmtok::tilde:
Opcode = InlineAsmUnaryOperator::Not;
break;
case asmtok::exclaim:
Opcode = InlineAsmUnaryOperator::LNot;
break;
default:
assert(0 && "unexpected op token");
}
return ::new (Context)
InlineAsmUnaryOperator(Opcode, SubExpr, SubExpr->getType());
}
// clang-format off
static InlineAsmBinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(asmtok::TokenKind Kind) {
InlineAsmBinaryOperator::Opcode Opc;
switch (Kind) {
default: assert(0 && "Unknown binop!");
case asmtok::star: Opc = InlineAsmBinaryOperator::Mul; break;
case asmtok::slash: Opc = InlineAsmBinaryOperator::Div; break;
case asmtok::percent: Opc = InlineAsmBinaryOperator::Rem; break;
case asmtok::plus: Opc = InlineAsmBinaryOperator::Add; break;
case asmtok::minus: Opc = InlineAsmBinaryOperator::Sub; break;
case asmtok::lessless: Opc = InlineAsmBinaryOperator::Shl; break;
case asmtok::greatergreater: Opc = InlineAsmBinaryOperator::Shr; break;
case asmtok::lessequal: Opc = InlineAsmBinaryOperator::LE; break;
case asmtok::less: Opc = InlineAsmBinaryOperator::LT; break;
case asmtok::greaterequal: Opc = InlineAsmBinaryOperator::GE; break;
case asmtok::greater: Opc = InlineAsmBinaryOperator::GT; break;
case asmtok::exclaimequal: Opc = InlineAsmBinaryOperator::NE; break;
case asmtok::equalequal: Opc = InlineAsmBinaryOperator::EQ; break;
case asmtok::amp: Opc = InlineAsmBinaryOperator::And; break;
case asmtok::caret: Opc = InlineAsmBinaryOperator::Xor; break;
case asmtok::pipe: Opc = InlineAsmBinaryOperator::Or; break;
case asmtok::ampamp: Opc = InlineAsmBinaryOperator::LAnd; break;
case asmtok::pipepipe: Opc = InlineAsmBinaryOperator::LOr; break;
case asmtok::equal: Opc = InlineAsmBinaryOperator::Assign; break;
}
return Opc;
}
// clang-format on
InlineAsmExprResult InlineAsmParser::ActOnBinaryOp(asmtok::TokenKind OpTok,
InlineAsmExpr *LHS,
InlineAsmExpr *RHS) {
InlineAsmBinaryOperator::Opcode Opcode =
ConvertTokenKindToBinaryOpcode(OpTok);
/// TODO: Compute the type of binary operator
return ::new (Context)
InlineAsmBinaryOperator(Opcode, LHS, RHS, LHS->getType());
}
InlineAsmExprResult InlineAsmParser::ActOnConditionalOp(InlineAsmExpr *Cond,
InlineAsmExpr *LHS,
InlineAsmExpr *RHS) {
/// TODO: Compute the type of conditional operator
return ::new (Context)
InlineAsmConditionalOperator(Cond, LHS, RHS, LHS->getType());
}
namespace {
/// AsmNumericLiteralParser - This performs strict semantic analysis of the
/// content of a ppnumber, classifying it as either integer, floating, or
/// erroneous, determines the radix of the value and can convert it to a useful
/// value.
class AsmNumericLiteralParser {
const char *const ThisTokBegin;
const char *const ThisTokEnd;
const char *DigitsBegin = nullptr, *SuffixBegin = nullptr; // markers
const char *s = nullptr; // cursor
unsigned radix = 0;
bool saw_exponent = false, saw_period = false;
public:
AsmNumericLiteralParser(StringRef TokSpelling);
bool hadError : 1;
bool isUnsigned : 1;
bool isFloat : 1; // 1.0f
bool isExactMachineFloat : 1; // 0[fF]{hexdigit}{8}
bool isExactMachineDouble : 1; // 0[dD]{hexdigit}{16}
bool isIntegerLiteral() const {
return !saw_period && !saw_exponent && !isExactMachineFloat ||
isExactMachineDouble;
}
bool isFloatingLiteral() const {
return (saw_period || saw_exponent || isExactMachineFloat ||
isExactMachineDouble);
}
unsigned getRadix() const { return radix; }
/// GetIntegerValue - Convert this numeric literal value to an APInt that
/// matches Val's input width. If there is an overflow (i.e., if the unsigned
/// value read is larger than the APInt's bits will hold), set Val to the low
/// bits of the result and return true. Otherwise, return false.
bool GetIntegerValue(llvm::APInt &Val);
/// GetFloatValue - Convert this numeric literal to a floating value, using
/// the specified APFloat fltSemantics (specifying float, double, etc).
/// The optional bool isExact (passed-by-reference) has its value
/// set to true if the returned APFloat can represent the number in the
/// literal exactly, and false otherwise.
llvm::APFloat::opStatus GetFloatValue(llvm::APFloat &Result);
/// Get the digits that comprise the literal. This excludes any prefix or
/// suffix associated with the literal.
StringRef getLiteralDigits() const {
assert(!hadError && "cannot reliably get the literal digits with an error");
return StringRef(DigitsBegin, SuffixBegin - DigitsBegin);
}
/// Get the digits that comprise the literal. This excludes any prefix or
/// suffix associated with the literal.
StringRef getExactMachineFloatingHexLiteralDigits() const {
assert(!hadError && (isExactMachineFloat || isExactMachineDouble) &&
"cannot reliably get the literal digits with an error");
return StringRef(DigitsBegin, SuffixBegin - DigitsBegin);
}
private:
void ParseNumberStartingWithZero();
void ParseDecimalOrOctalCommon();
/// Determine whether the sequence of characters [Start, End) contains
/// any real digits (not digit separators).
bool containsDigits(const char *Start, const char *End) {
return Start != End;
}
enum CheckSeparatorKind { CSK_BeforeDigits, CSK_AfterDigits };
/// SkipHexDigits - Read and skip over any hex digits, up to End.
/// Return a pointer to the first non-hex digit or End.
const char *SkipHexDigits(const char *ptr) {
while (ptr != ThisTokEnd && (isHexDigit(*ptr)))
ptr++;
return ptr;
}
/// SkipOctalDigits - Read and skip over any octal digits, up to End.
/// Return a pointer to the first non-hex digit or End.
const char *SkipOctalDigits(const char *ptr) {
while (ptr != ThisTokEnd && ((*ptr >= '0' && *ptr <= '7')))
ptr++;
return ptr;
}
/// SkipDigits - Read and skip over any digits, up to End.
/// Return a pointer to the first non-hex digit or End.
const char *SkipDigits(const char *ptr) {
while (ptr != ThisTokEnd && (isDigit(*ptr)))
ptr++;
return ptr;
}
/// SkipBinaryDigits - Read and skip over any binary digits, up to End.
/// Return a pointer to the first non-binary digit or End.
const char *SkipBinaryDigits(const char *ptr) {
while (ptr != ThisTokEnd && (*ptr == '0' || *ptr == '1'))
ptr++;
return ptr;
}
};
/// integer-constant: [C99 6.4.4.1]
/// decimal-constant integer-suffix
/// octal-constant integer-suffix
/// hexadecimal-constant integer-suffix
/// binary-literal integer-suffix [GNU, C++1y]
/// user-defined-integer-literal: [C++11 lex.ext]
/// decimal-literal ud-suffix
/// octal-literal ud-suffix
/// hexadecimal-literal ud-suffix
/// binary-literal ud-suffix [GNU, C++1y]
/// decimal-constant:
/// nonzero-digit
/// decimal-constant digit
/// octal-constant:
/// 0
/// octal-constant octal-digit
/// hexadecimal-constant:
/// hexadecimal-prefix hexadecimal-digit
/// hexadecimal-constant hexadecimal-digit
/// hexadecimal-prefix: one of
/// 0x 0X
/// binary-literal:
/// 0b binary-digit
/// 0B binary-digit
/// binary-literal binary-digit
/// integer-suffix:
/// unsigned-suffix [long-suffix]
/// unsigned-suffix [long-long-suffix]
/// long-suffix [unsigned-suffix]
/// long-long-suffix [unsigned-sufix]
/// nonzero-digit:
/// 1 2 3 4 5 6 7 8 9
/// octal-digit:
/// 0 1 2 3 4 5 6 7
/// hexadecimal-digit:
/// 0 1 2 3 4 5 6 7 8 9
/// a b c d e f
/// A B C D E F