-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Expand file tree
/
Copy pathCIRGenExprScalar.cpp
More file actions
2757 lines (2384 loc) · 106 KB
/
Copy pathCIRGenExprScalar.cpp
File metadata and controls
2757 lines (2384 loc) · 106 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
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Emit Expr nodes with scalar CIR types as CIR code.
//
//===----------------------------------------------------------------------===//
#include "CIRGenConstantEmitter.h"
#include "CIRGenFunction.h"
#include "CIRGenValue.h"
#include "clang/AST/Expr.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/CIR/Dialect/IR/CIRTypes.h"
#include "clang/CIR/MissingFeatures.h"
#include "mlir/IR/Location.h"
#include "mlir/IR/Value.h"
#include <cassert>
#include <utility>
using namespace clang;
using namespace clang::CIRGen;
namespace {
struct BinOpInfo {
mlir::Value lhs;
mlir::Value rhs;
SourceRange loc;
QualType fullType; // Type of operands and result
QualType compType; // Type used for computations. Element type
// for vectors, otherwise same as FullType.
BinaryOperator::Opcode opcode; // Opcode of BinOp to perform
FPOptions fpfeatures;
const Expr *e; // Entire expr, for error unsupported. May not be binop.
/// Check if the binop computes a division or a remainder.
bool isDivRemOp() const {
return opcode == BO_Div || opcode == BO_Rem || opcode == BO_DivAssign ||
opcode == BO_RemAssign;
}
/// Check if the binop can result in integer overflow.
bool mayHaveIntegerOverflow() const {
// Without constant input, we can't rule out overflow.
auto lhsci = lhs.getDefiningOp<cir::ConstantOp>();
auto rhsci = rhs.getDefiningOp<cir::ConstantOp>();
if (!lhsci || !rhsci)
return true;
assert(!cir::MissingFeatures::mayHaveIntegerOverflow());
// TODO(cir): For now we just assume that we might overflow
return true;
}
/// Check if at least one operand is a fixed point type. In such cases,
/// this operation did not follow usual arithmetic conversion and both
/// operands might not be of the same type.
bool isFixedPointOp() const {
// We cannot simply check the result type since comparison operations
// return an int.
if (const auto *binOp = llvm::dyn_cast<BinaryOperator>(e)) {
QualType lhstype = binOp->getLHS()->getType();
QualType rhstype = binOp->getRHS()->getType();
return lhstype->isFixedPointType() || rhstype->isFixedPointType();
}
if (const auto *unop = llvm::dyn_cast<UnaryOperator>(e))
return unop->getSubExpr()->getType()->isFixedPointType();
return false;
}
};
class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
CIRGenFunction &cgf;
CIRGenBuilderTy &builder;
// Unlike classic codegen we set this to false or use std::exchange to read
// the value instead of calling TestAndClearIgnoreResultAssign to make it
// explicit when the value is used
bool ignoreResultAssign;
public:
ScalarExprEmitter(CIRGenFunction &cgf, CIRGenBuilderTy &builder,
bool ignoreResultAssign = false)
: cgf(cgf), builder(builder), ignoreResultAssign(ignoreResultAssign) {}
//===--------------------------------------------------------------------===//
// Utilities
//===--------------------------------------------------------------------===//
mlir::Type convertType(QualType ty) { return cgf.convertType(ty); }
mlir::Value emitComplexToScalarConversion(mlir::Location loc,
mlir::Value value, CastKind kind,
QualType destTy);
mlir::Value emitNullValue(QualType ty, mlir::Location loc) {
return cgf.cgm.emitNullConstant(ty, loc);
}
mlir::Value emitPromotedValue(mlir::Value result, QualType promotionType) {
return builder.createFloatingCast(result, cgf.convertType(promotionType));
}
mlir::Value emitUnPromotedValue(mlir::Value result, QualType exprType) {
return builder.createFloatingCast(result, cgf.convertType(exprType));
}
mlir::Value emitPromoted(const Expr *e, QualType promotionType);
mlir::Value maybePromoteBoolResult(mlir::Value value,
mlir::Type dstTy) const {
if (mlir::isa<cir::IntType>(dstTy))
return builder.createBoolToInt(value, dstTy);
if (mlir::isa<cir::BoolType>(dstTy))
return value;
llvm_unreachable("Can only promote integer or boolean types");
}
//===--------------------------------------------------------------------===//
// Visitor Methods
//===--------------------------------------------------------------------===//
mlir::Value Visit(Expr *e) {
return StmtVisitor<ScalarExprEmitter, mlir::Value>::Visit(e);
}
mlir::Value VisitStmt(Stmt *s) {
llvm_unreachable("Statement passed to ScalarExprEmitter");
}
mlir::Value VisitExpr(Expr *e) {
cgf.getCIRGenModule().errorNYI(
e->getSourceRange(), "scalar expression kind: ", e->getStmtClassName());
return {};
}
mlir::Value VisitConstantExpr(ConstantExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: constant expr");
return {};
}
mlir::Value VisitPackIndexingExpr(PackIndexingExpr *e) {
return Visit(e->getSelectedExpr());
}
mlir::Value VisitParenExpr(ParenExpr *pe) { return Visit(pe->getSubExpr()); }
mlir::Value VisitGenericSelectionExpr(GenericSelectionExpr *ge) {
return Visit(ge->getResultExpr());
}
/// Emits the address of the l-value, then loads and returns the result.
mlir::Value emitLoadOfLValue(const Expr *e) {
LValue lv = cgf.emitLValue(e);
// FIXME: add some akin to EmitLValueAlignmentAssumption(E, V);
return cgf.emitLoadOfLValue(lv, e->getExprLoc()).getValue();
}
mlir::Value VisitCoawaitExpr(CoawaitExpr *s) {
return cgf.emitCoawaitExpr(*s).getValue();
}
mlir::Value VisitCoyieldExpr(CoyieldExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: coyield");
return {};
}
mlir::Value VisitUnaryCoawait(const UnaryOperator *e) {
cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: unary coawait");
return {};
}
mlir::Value emitLoadOfLValue(LValue lv, SourceLocation loc) {
return cgf.emitLoadOfLValue(lv, loc).getValue();
}
// l-values
mlir::Value VisitDeclRefExpr(DeclRefExpr *e) {
if (CIRGenFunction::ConstantEmission constant = cgf.tryEmitAsConstant(e))
return cgf.emitScalarConstant(constant, e);
return emitLoadOfLValue(e);
}
mlir::Value VisitAddrLabelExpr(const AddrLabelExpr *e) {
auto func = cast<cir::FuncOp>(cgf.curFn);
cir::BlockAddrInfoAttr blockInfoAttr = cir::BlockAddrInfoAttr::get(
&cgf.getMLIRContext(), func.getSymName(), e->getLabel()->getName());
cir::BlockAddressOp blockAddressOp = cir::BlockAddressOp::create(
builder, cgf.getLoc(e->getSourceRange()), cgf.convertType(e->getType()),
blockInfoAttr);
cir::LabelOp resolvedLabel = cgf.cgm.lookupBlockAddressInfo(blockInfoAttr);
if (!resolvedLabel) {
cgf.cgm.mapUnresolvedBlockAddress(blockAddressOp);
// Still add the op to maintain insertion order it will be resolved in
// resolveBlockAddresses
cgf.cgm.mapResolvedBlockAddress(blockAddressOp, nullptr);
} else {
cgf.cgm.mapResolvedBlockAddress(blockAddressOp, resolvedLabel);
}
cgf.instantiateIndirectGotoBlock();
return blockAddressOp;
}
mlir::Value VisitIntegerLiteral(const IntegerLiteral *e) {
mlir::Type type = cgf.convertType(e->getType());
return cir::ConstantOp::create(builder, cgf.getLoc(e->getExprLoc()),
cir::IntAttr::get(type, e->getValue()));
}
mlir::Value VisitFixedPointLiteral(const FixedPointLiteral *e) {
cgf.cgm.errorNYI(e->getSourceRange(),
"ScalarExprEmitter: fixed point literal");
return {};
}
mlir::Value VisitFloatingLiteral(const FloatingLiteral *e) {
mlir::Type type = cgf.convertType(e->getType());
assert(mlir::isa<cir::FPTypeInterface>(type) &&
"expect floating-point type");
return cir::ConstantOp::create(builder, cgf.getLoc(e->getExprLoc()),
cir::FPAttr::get(type, e->getValue()));
}
mlir::Value VisitCharacterLiteral(const CharacterLiteral *e) {
mlir::Type ty = cgf.convertType(e->getType());
auto init = cir::IntAttr::get(ty, e->getValue());
return cir::ConstantOp::create(builder, cgf.getLoc(e->getExprLoc()), init);
}
mlir::Value VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *e) {
return builder.getBool(e->getValue(), cgf.getLoc(e->getExprLoc()));
}
mlir::Value VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *e) {
if (e->getType()->isVoidType())
return {};
return emitNullValue(e->getType(), cgf.getLoc(e->getSourceRange()));
}
mlir::Value VisitGNUNullExpr(const GNUNullExpr *e) {
return emitNullValue(e->getType(), cgf.getLoc(e->getSourceRange()));
}
mlir::Value VisitOffsetOfExpr(OffsetOfExpr *e);
mlir::Value VisitSizeOfPackExpr(SizeOfPackExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: size of pack");
return {};
}
mlir::Value VisitPseudoObjectExpr(PseudoObjectExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: pseudo object");
return {};
}
mlir::Value VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(),
"ScalarExprEmitter: sycl unique stable name");
return {};
}
mlir::Value VisitEmbedExpr(EmbedExpr *e) {
assert(e->getDataElementCount() == 1);
auto it = e->begin();
llvm::APInt value = (*it)->getValue();
return builder.getConstInt(cgf.getLoc(e->getExprLoc()), value,
e->getType()->isUnsignedIntegerType());
}
mlir::Value VisitOpaqueValueExpr(OpaqueValueExpr *e) {
if (e->isGLValue())
return emitLoadOfLValue(cgf.getOrCreateOpaqueLValueMapping(e),
e->getExprLoc());
// Otherwise, assume the mapping is the scalar directly.
return cgf.getOrCreateOpaqueRValueMapping(e).getValue();
}
mlir::Value VisitObjCSelectorExpr(ObjCSelectorExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc selector");
return {};
}
mlir::Value VisitObjCProtocolExpr(ObjCProtocolExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc protocol");
return {};
}
mlir::Value VisitObjCIVarRefExpr(ObjCIvarRefExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc ivar ref");
return {};
}
mlir::Value VisitObjCMessageExpr(ObjCMessageExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc message");
return {};
}
mlir::Value VisitObjCIsaExpr(ObjCIsaExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc isa");
return {};
}
mlir::Value VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(),
"ScalarExprEmitter: objc availability check");
return {};
}
mlir::Value VisitMatrixSubscriptExpr(MatrixSubscriptExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(),
"ScalarExprEmitter: matrix subscript");
return {};
}
mlir::Value VisitCastExpr(CastExpr *e);
mlir::Value VisitCallExpr(const CallExpr *e);
mlir::Value VisitStmtExpr(StmtExpr *e) {
CIRGenFunction::StmtExprEvaluation eval(cgf);
if (e->getType()->isVoidType()) {
(void)cgf.emitCompoundStmt(*e->getSubStmt());
return {};
}
Address retAlloca =
cgf.createMemTemp(e->getType(), cgf.getLoc(e->getSourceRange()));
(void)cgf.emitCompoundStmt(*e->getSubStmt(), &retAlloca);
return cgf.emitLoadOfScalar(cgf.makeAddrLValue(retAlloca, e->getType()),
e->getExprLoc());
}
mlir::Value VisitArraySubscriptExpr(ArraySubscriptExpr *e) {
ignoreResultAssign = false;
if (e->getBase()->getType()->isVectorType()) {
assert(!cir::MissingFeatures::scalableVectors());
const mlir::Location loc = cgf.getLoc(e->getSourceRange());
const mlir::Value vecValue = Visit(e->getBase());
const mlir::Value indexValue = Visit(e->getIdx());
return cir::VecExtractOp::create(cgf.builder, loc, vecValue, indexValue);
}
// Just load the lvalue formed by the subscript expression.
return emitLoadOfLValue(e);
}
mlir::Value VisitShuffleVectorExpr(ShuffleVectorExpr *e) {
if (e->getNumSubExprs() == 2) {
// The undocumented form of __builtin_shufflevector.
mlir::Value inputVec = Visit(e->getExpr(0));
mlir::Value indexVec = Visit(e->getExpr(1));
return cir::VecShuffleDynamicOp::create(
cgf.builder, cgf.getLoc(e->getSourceRange()), inputVec, indexVec);
}
mlir::Value vec1 = Visit(e->getExpr(0));
mlir::Value vec2 = Visit(e->getExpr(1));
// The documented form of __builtin_shufflevector, where the indices are
// a variable number of integer constants. The constants will be stored
// in an ArrayAttr.
SmallVector<mlir::Attribute, 8> indices;
for (unsigned i = 2; i < e->getNumSubExprs(); ++i) {
indices.push_back(
cir::IntAttr::get(cgf.builder.getSInt64Ty(),
e->getExpr(i)
->EvaluateKnownConstInt(cgf.getContext())
.getSExtValue()));
}
return cir::VecShuffleOp::create(cgf.builder,
cgf.getLoc(e->getSourceRange()),
cgf.convertType(e->getType()), vec1, vec2,
cgf.builder.getArrayAttr(indices));
}
mlir::Value VisitConvertVectorExpr(ConvertVectorExpr *e) {
// __builtin_convertvector is an element-wise cast, and is implemented as a
// regular cast. The back end handles casts of vectors correctly.
return emitScalarConversion(Visit(e->getSrcExpr()),
e->getSrcExpr()->getType(), e->getType(),
e->getSourceRange().getBegin());
}
mlir::Value VisitExtVectorElementExpr(Expr *e) { return emitLoadOfLValue(e); }
mlir::Value VisitMemberExpr(MemberExpr *e);
mlir::Value VisitCompoundLiteralExpr(CompoundLiteralExpr *e) {
return emitLoadOfLValue(e);
}
mlir::Value VisitInitListExpr(InitListExpr *e);
mlir::Value VisitArrayInitIndexExpr(ArrayInitIndexExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(),
"ScalarExprEmitter: array init index");
return {};
}
mlir::Value VisitImplicitValueInitExpr(const ImplicitValueInitExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(),
"ScalarExprEmitter: implicit value init");
return {};
}
mlir::Value VisitExplicitCastExpr(ExplicitCastExpr *e) {
return VisitCastExpr(e);
}
mlir::Value VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *e) {
return cgf.cgm.emitNullConstant(e->getType(),
cgf.getLoc(e->getSourceRange()));
}
/// Perform a pointer to boolean conversion.
mlir::Value emitPointerToBoolConversion(mlir::Value v, QualType qt) {
// TODO(cir): comparing the ptr to null is done when lowering CIR to LLVM.
// We might want to have a separate pass for these types of conversions.
return cgf.getBuilder().createPtrToBoolCast(v);
}
mlir::Value emitFloatToBoolConversion(mlir::Value src, mlir::Location loc) {
cir::BoolType boolTy = builder.getBoolTy();
return cir::CastOp::create(builder, loc, boolTy,
cir::CastKind::float_to_bool, src);
}
mlir::Value emitIntToBoolConversion(mlir::Value srcVal, mlir::Location loc) {
// Because of the type rules of C, we often end up computing a
// logical value, then zero extending it to int, then wanting it
// as a logical value again.
// TODO: optimize this common case here or leave it for later
// CIR passes?
cir::BoolType boolTy = builder.getBoolTy();
return cir::CastOp::create(builder, loc, boolTy, cir::CastKind::int_to_bool,
srcVal);
}
/// Convert the specified expression value to a boolean (!cir.bool) truth
/// value. This is equivalent to "Val != 0".
mlir::Value emitConversionToBool(mlir::Value src, QualType srcType,
mlir::Location loc) {
assert(srcType.isCanonical() && "EmitScalarConversion strips typedefs");
if (srcType->isRealFloatingType())
return emitFloatToBoolConversion(src, loc);
if (llvm::isa<MemberPointerType>(srcType)) {
cgf.getCIRGenModule().errorNYI(loc, "member pointer to bool conversion");
return builder.getFalse(loc);
}
if (srcType->isIntegerType())
return emitIntToBoolConversion(src, loc);
assert(::mlir::isa<cir::PointerType>(src.getType()));
return emitPointerToBoolConversion(src, srcType);
}
// Emit a conversion from the specified type to the specified destination
// type, both of which are CIR scalar types.
struct ScalarConversionOpts {
bool treatBooleanAsSigned;
bool emitImplicitIntegerTruncationChecks;
bool emitImplicitIntegerSignChangeChecks;
ScalarConversionOpts()
: treatBooleanAsSigned(false),
emitImplicitIntegerTruncationChecks(false),
emitImplicitIntegerSignChangeChecks(false) {}
ScalarConversionOpts(clang::SanitizerSet sanOpts)
: treatBooleanAsSigned(false),
emitImplicitIntegerTruncationChecks(
sanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
emitImplicitIntegerSignChangeChecks(
sanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
};
// Conversion from bool, integral, or floating-point to integral or
// floating-point. Conversions involving other types are handled elsewhere.
// Conversion to bool is handled elsewhere because that's a comparison against
// zero, not a simple cast. This handles both individual scalars and vectors.
mlir::Value emitScalarCast(mlir::Value src, QualType srcType,
QualType dstType, mlir::Type srcTy,
mlir::Type dstTy, ScalarConversionOpts opts) {
assert(!srcType->isMatrixType() && !dstType->isMatrixType() &&
"Internal error: matrix types not handled by this function.");
assert(!(mlir::isa<mlir::IntegerType>(srcTy) ||
mlir::isa<mlir::IntegerType>(dstTy)) &&
"Obsolete code. Don't use mlir::IntegerType with CIR.");
mlir::Type fullDstTy = dstTy;
if (mlir::isa<cir::VectorType>(srcTy) &&
mlir::isa<cir::VectorType>(dstTy)) {
// Use the element types of the vectors to figure out the CastKind.
srcTy = mlir::dyn_cast<cir::VectorType>(srcTy).getElementType();
dstTy = mlir::dyn_cast<cir::VectorType>(dstTy).getElementType();
}
std::optional<cir::CastKind> castKind;
if (mlir::isa<cir::BoolType>(srcTy)) {
if (opts.treatBooleanAsSigned)
cgf.getCIRGenModule().errorNYI("signed bool");
if (cgf.getBuilder().isInt(dstTy))
castKind = cir::CastKind::bool_to_int;
else if (mlir::isa<cir::FPTypeInterface>(dstTy))
castKind = cir::CastKind::bool_to_float;
else
llvm_unreachable("Internal error: Cast to unexpected type");
} else if (cgf.getBuilder().isInt(srcTy)) {
if (cgf.getBuilder().isInt(dstTy))
castKind = cir::CastKind::integral;
else if (mlir::isa<cir::FPTypeInterface>(dstTy))
castKind = cir::CastKind::int_to_float;
else
llvm_unreachable("Internal error: Cast to unexpected type");
} else if (mlir::isa<cir::FPTypeInterface>(srcTy)) {
if (cgf.getBuilder().isInt(dstTy)) {
// If we can't recognize overflow as undefined behavior, assume that
// overflow saturates. This protects against normal optimizations if we
// are compiling with non-standard FP semantics.
if (!cgf.cgm.getCodeGenOpts().StrictFloatCastOverflow)
cgf.getCIRGenModule().errorNYI("strict float cast overflow");
assert(!cir::MissingFeatures::fpConstraints());
castKind = cir::CastKind::float_to_int;
} else if (mlir::isa<cir::FPTypeInterface>(dstTy)) {
// TODO: split this to createFPExt/createFPTrunc
return builder.createFloatingCast(src, fullDstTy);
} else {
llvm_unreachable("Internal error: Cast to unexpected type");
}
} else {
llvm_unreachable("Internal error: Cast from unexpected type");
}
assert(castKind.has_value() && "Internal error: CastKind not set.");
return cir::CastOp::create(builder, src.getLoc(), fullDstTy, *castKind,
src);
}
mlir::Value
VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *e) {
return Visit(e->getReplacement());
}
mlir::Value VisitVAArgExpr(VAArgExpr *ve) {
QualType ty = ve->getType();
if (ty->isVariablyModifiedType()) {
cgf.cgm.errorNYI(ve->getSourceRange(),
"variably modified types in varargs");
}
return cgf.emitVAArg(ve);
}
mlir::Value VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *e) {
return Visit(e->getSemanticForm());
}
mlir::Value VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *e);
mlir::Value
VisitAbstractConditionalOperator(const AbstractConditionalOperator *e);
// Unary Operators.
mlir::Value VisitUnaryPostDec(const UnaryOperator *e) {
LValue lv = cgf.emitLValue(e->getSubExpr());
return emitScalarPrePostIncDec(e, lv, cir::UnaryOpKind::Dec, false);
}
mlir::Value VisitUnaryPostInc(const UnaryOperator *e) {
LValue lv = cgf.emitLValue(e->getSubExpr());
return emitScalarPrePostIncDec(e, lv, cir::UnaryOpKind::Inc, false);
}
mlir::Value VisitUnaryPreDec(const UnaryOperator *e) {
LValue lv = cgf.emitLValue(e->getSubExpr());
return emitScalarPrePostIncDec(e, lv, cir::UnaryOpKind::Dec, true);
}
mlir::Value VisitUnaryPreInc(const UnaryOperator *e) {
LValue lv = cgf.emitLValue(e->getSubExpr());
return emitScalarPrePostIncDec(e, lv, cir::UnaryOpKind::Inc, true);
}
mlir::Value emitScalarPrePostIncDec(const UnaryOperator *e, LValue lv,
cir::UnaryOpKind kind, bool isPre) {
if (cgf.getLangOpts().OpenMP)
cgf.cgm.errorNYI(e->getSourceRange(), "inc/dec OpenMP");
QualType type = e->getSubExpr()->getType();
mlir::Value value;
mlir::Value input;
if (type->getAs<AtomicType>()) {
cgf.cgm.errorNYI(e->getSourceRange(), "Atomic inc/dec");
// TODO(cir): This is not correct, but it will produce reasonable code
// until atomic operations are implemented.
value = cgf.emitLoadOfLValue(lv, e->getExprLoc()).getValue();
input = value;
} else {
value = cgf.emitLoadOfLValue(lv, e->getExprLoc()).getValue();
input = value;
}
// NOTE: When possible, more frequent cases are handled first.
// Special case of integer increment that we have to check first: bool++.
// Due to promotion rules, we get:
// bool++ -> bool = bool + 1
// -> bool = (int)bool + 1
// -> bool = ((int)bool + 1 != 0)
// An interesting aspect of this is that increment is always true.
// Decrement does not have this property.
if (kind == cir::UnaryOpKind::Inc && type->isBooleanType()) {
value = builder.getTrue(cgf.getLoc(e->getExprLoc()));
} else if (type->isIntegerType()) {
QualType promotedType;
[[maybe_unused]] bool canPerformLossyDemotionCheck = false;
if (cgf.getContext().isPromotableIntegerType(type)) {
promotedType = cgf.getContext().getPromotedIntegerType(type);
assert(promotedType != type && "Shouldn't promote to the same type.");
canPerformLossyDemotionCheck = true;
canPerformLossyDemotionCheck &=
cgf.getContext().getCanonicalType(type) !=
cgf.getContext().getCanonicalType(promotedType);
canPerformLossyDemotionCheck &=
type->isIntegerType() && promotedType->isIntegerType();
// TODO(cir): Currently, we store bitwidths in CIR types only for
// integers. This might also be required for other types.
assert(
(!canPerformLossyDemotionCheck ||
type->isSignedIntegerOrEnumerationType() ||
promotedType->isSignedIntegerOrEnumerationType() ||
mlir::cast<cir::IntType>(cgf.convertType(type)).getWidth() ==
mlir::cast<cir::IntType>(cgf.convertType(type)).getWidth()) &&
"The following check expects that if we do promotion to different "
"underlying canonical type, at least one of the types (either "
"base or promoted) will be signed, or the bitwidths will match.");
}
assert(!cir::MissingFeatures::sanitizers());
if (e->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
value = emitIncDecConsiderOverflowBehavior(e, value, kind);
} else {
cir::UnaryOpKind kind =
e->isIncrementOp() ? cir::UnaryOpKind::Inc : cir::UnaryOpKind::Dec;
// NOTE(CIR): clang calls CreateAdd but folds this to a unary op
value = emitUnaryOp(e, kind, input, /*nsw=*/false);
}
} else if (const PointerType *ptr = type->getAs<PointerType>()) {
QualType type = ptr->getPointeeType();
if (cgf.getContext().getAsVariableArrayType(type)) {
// VLA types don't have constant size.
cgf.cgm.errorNYI(e->getSourceRange(), "Pointer arithmetic on VLA");
return {};
} else if (type->isFunctionType()) {
// Arithmetic on function pointers (!) is just +-1.
cgf.cgm.errorNYI(e->getSourceRange(),
"Pointer arithmetic on function pointer");
return {};
} else {
// For everything else, we can just do a simple increment.
mlir::Location loc = cgf.getLoc(e->getSourceRange());
CIRGenBuilderTy &builder = cgf.getBuilder();
int amount = kind == cir::UnaryOpKind::Inc ? 1 : -1;
mlir::Value amt = builder.getSInt32(amount, loc);
assert(!cir::MissingFeatures::sanitizers());
value = builder.createPtrStride(loc, value, amt);
}
} else if (type->isVectorType()) {
cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec vector");
return {};
} else if (type->isRealFloatingType()) {
assert(!cir::MissingFeatures::cgFPOptionsRAII());
if (type->isHalfType() &&
!cgf.getContext().getLangOpts().NativeHalfType) {
cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec half");
return {};
}
if (mlir::isa<cir::SingleType, cir::DoubleType>(value.getType())) {
// Create the inc/dec operation.
// NOTE(CIR): clang calls CreateAdd but folds this to a unary op
assert(kind == cir::UnaryOpKind::Inc ||
kind == cir::UnaryOpKind::Dec && "Invalid UnaryOp kind");
value = emitUnaryOp(e, kind, value);
} else {
cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec other fp type");
return {};
}
} else if (type->isFixedPointType()) {
cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec other fixed point");
return {};
} else {
assert(type->castAs<ObjCObjectPointerType>());
cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec ObjectiveC pointer");
return {};
}
CIRGenFunction::SourceLocRAIIObject sourceloc{
cgf, cgf.getLoc(e->getSourceRange())};
// Store the updated result through the lvalue
if (lv.isBitField())
return cgf.emitStoreThroughBitfieldLValue(RValue::get(value), lv);
else
cgf.emitStoreThroughLValue(RValue::get(value), lv);
// If this is a postinc, return the value read from memory, otherwise use
// the updated value.
return isPre ? value : input;
}
mlir::Value emitIncDecConsiderOverflowBehavior(const UnaryOperator *e,
mlir::Value inVal,
cir::UnaryOpKind kind) {
assert(kind == cir::UnaryOpKind::Inc ||
kind == cir::UnaryOpKind::Dec && "Invalid UnaryOp kind");
switch (cgf.getLangOpts().getSignedOverflowBehavior()) {
case LangOptions::SOB_Defined:
return emitUnaryOp(e, kind, inVal, /*nsw=*/false);
case LangOptions::SOB_Undefined:
assert(!cir::MissingFeatures::sanitizers());
return emitUnaryOp(e, kind, inVal, /*nsw=*/true);
case LangOptions::SOB_Trapping:
if (!e->canOverflow())
return emitUnaryOp(e, kind, inVal, /*nsw=*/true);
cgf.cgm.errorNYI(e->getSourceRange(), "inc/def overflow SOB_Trapping");
return {};
}
llvm_unreachable("Unexpected signed overflow behavior kind");
}
mlir::Value VisitUnaryAddrOf(const UnaryOperator *e) {
if (llvm::isa<MemberPointerType>(e->getType()))
return cgf.cgm.emitMemberPointerConstant(e);
return cgf.emitLValue(e->getSubExpr()).getPointer();
}
mlir::Value VisitUnaryDeref(const UnaryOperator *e) {
if (e->getType()->isVoidType())
return Visit(e->getSubExpr()); // the actual value should be unused
return emitLoadOfLValue(e);
}
mlir::Value VisitUnaryPlus(const UnaryOperator *e) {
QualType promotionType = getPromotionType(e->getSubExpr()->getType());
mlir::Value result =
emitUnaryPlusOrMinus(e, cir::UnaryOpKind::Plus, promotionType);
if (result && !promotionType.isNull())
return emitUnPromotedValue(result, e->getType());
return result;
}
mlir::Value VisitUnaryMinus(const UnaryOperator *e) {
QualType promotionType = getPromotionType(e->getSubExpr()->getType());
mlir::Value result =
emitUnaryPlusOrMinus(e, cir::UnaryOpKind::Minus, promotionType);
if (result && !promotionType.isNull())
return emitUnPromotedValue(result, e->getType());
return result;
}
mlir::Value emitUnaryPlusOrMinus(const UnaryOperator *e,
cir::UnaryOpKind kind,
QualType promotionType) {
ignoreResultAssign = false;
mlir::Value operand;
if (!promotionType.isNull())
operand = cgf.emitPromotedScalarExpr(e->getSubExpr(), promotionType);
else
operand = Visit(e->getSubExpr());
bool nsw =
kind == cir::UnaryOpKind::Minus && e->getType()->isSignedIntegerType();
// NOTE: LLVM codegen will lower this directly to either a FNeg
// or a Sub instruction. In CIR this will be handled later in LowerToLLVM.
return emitUnaryOp(e, kind, operand, nsw);
}
mlir::Value emitUnaryOp(const UnaryOperator *e, cir::UnaryOpKind kind,
mlir::Value input, bool nsw = false) {
return cir::UnaryOp::create(builder,
cgf.getLoc(e->getSourceRange().getBegin()),
input.getType(), kind, input, nsw);
}
mlir::Value VisitUnaryNot(const UnaryOperator *e) {
ignoreResultAssign = false;
mlir::Value op = Visit(e->getSubExpr());
return emitUnaryOp(e, cir::UnaryOpKind::Not, op);
}
mlir::Value VisitUnaryLNot(const UnaryOperator *e);
mlir::Value VisitUnaryReal(const UnaryOperator *e);
mlir::Value VisitUnaryImag(const UnaryOperator *e);
mlir::Value VisitRealImag(const UnaryOperator *e,
QualType promotionType = QualType());
mlir::Value VisitUnaryExtension(const UnaryOperator *e) {
return Visit(e->getSubExpr());
}
// C++
mlir::Value VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(),
"ScalarExprEmitter: materialize temporary");
return {};
}
mlir::Value VisitSourceLocExpr(SourceLocExpr *e) {
ASTContext &ctx = cgf.getContext();
APValue evaluated =
e->EvaluateInContext(ctx, cgf.curSourceLocExprScope.getDefaultExpr());
mlir::Attribute attribute = ConstantEmitter(cgf).emitAbstract(
e->getLocation(), evaluated, e->getType());
mlir::TypedAttr typedAttr = mlir::cast<mlir::TypedAttr>(attribute);
return cir::ConstantOp::create(builder, cgf.getLoc(e->getExprLoc()),
typedAttr);
}
mlir::Value VisitCXXDefaultArgExpr(CXXDefaultArgExpr *dae) {
CIRGenFunction::CXXDefaultArgExprScope scope(cgf, dae);
return Visit(dae->getExpr());
}
mlir::Value VisitCXXDefaultInitExpr(CXXDefaultInitExpr *die) {
CIRGenFunction::CXXDefaultInitExprScope scope(cgf, die);
return Visit(die->getExpr());
}
mlir::Value VisitCXXThisExpr(CXXThisExpr *te) { return cgf.loadCXXThis(); }
mlir::Value VisitExprWithCleanups(ExprWithCleanups *e);
mlir::Value VisitCXXNewExpr(const CXXNewExpr *e) {
return cgf.emitCXXNewExpr(e);
}
mlir::Value VisitCXXDeleteExpr(const CXXDeleteExpr *e) {
cgf.emitCXXDeleteExpr(e);
return {};
}
mlir::Value VisitTypeTraitExpr(const TypeTraitExpr *e) {
mlir::Location loc = cgf.getLoc(e->getExprLoc());
if (e->isStoredAsBoolean())
return builder.getBool(e->getBoolValue(), loc);
cgf.cgm.errorNYI(e->getSourceRange(),
"ScalarExprEmitter: TypeTraitExpr stored as int");
return {};
}
mlir::Value
VisitConceptSpecializationExpr(const ConceptSpecializationExpr *e) {
return builder.getBool(e->isSatisfied(), cgf.getLoc(e->getExprLoc()));
}
mlir::Value VisitRequiresExpr(const RequiresExpr *e) {
return builder.getBool(e->isSatisfied(), cgf.getLoc(e->getExprLoc()));
}
mlir::Value VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *e) {
mlir::Type type = cgf.convertType(e->getType());
mlir::Location loc = cgf.getLoc(e->getExprLoc());
return builder.getConstInt(loc, type, e->getValue());
}
mlir::Value VisitExpressionTraitExpr(const ExpressionTraitExpr *e) {
return builder.getBool(e->getValue(), cgf.getLoc(e->getExprLoc()));
}
mlir::Value VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *e) {
cgf.cgm.errorNYI(e->getSourceRange(),
"ScalarExprEmitter: cxx pseudo destructor");
return {};
}
mlir::Value VisitCXXThrowExpr(const CXXThrowExpr *e) {
cgf.emitCXXThrowExpr(e);
return {};
}
mlir::Value VisitCXXNoexceptExpr(CXXNoexceptExpr *e) {
return builder.getBool(e->getValue(), cgf.getLoc(e->getExprLoc()));
}
/// Emit a conversion from the specified type to the specified destination
/// type, both of which are CIR scalar types.
/// TODO: do we need ScalarConversionOpts here? Should be done in another
/// pass.
mlir::Value
emitScalarConversion(mlir::Value src, QualType srcType, QualType dstType,
SourceLocation loc,
ScalarConversionOpts opts = ScalarConversionOpts()) {
// All conversions involving fixed point types should be handled by the
// emitFixedPoint family functions. This is done to prevent bloating up
// this function more, and although fixed point numbers are represented by
// integers, we do not want to follow any logic that assumes they should be
// treated as integers.
// TODO(leonardchan): When necessary, add another if statement checking for
// conversions to fixed point types from other types.
// conversions to fixed point types from other types.
if (srcType->isFixedPointType() || dstType->isFixedPointType()) {
cgf.getCIRGenModule().errorNYI(loc, "fixed point conversions");
return {};
}
srcType = srcType.getCanonicalType();
dstType = dstType.getCanonicalType();
if (srcType == dstType) {
if (opts.emitImplicitIntegerSignChangeChecks)
cgf.getCIRGenModule().errorNYI(loc,
"implicit integer sign change checks");
return src;
}
if (dstType->isVoidType())
return {};
mlir::Type mlirSrcType = src.getType();
// Handle conversions to bool first, they are special: comparisons against
// 0.
if (dstType->isBooleanType())
return emitConversionToBool(src, srcType, cgf.getLoc(loc));
mlir::Type mlirDstType = cgf.convertType(dstType);
if (srcType->isHalfType() &&
!cgf.getContext().getLangOpts().NativeHalfType) {
// Cast to FP using the intrinsic if the half type itself isn't supported.
if (!mlir::isa<cir::FPTypeInterface>(mlirDstType)) {
// Cast to other types through float, using FPExt, depending on whether
// the half type itself is supported (as opposed to operations on half,
// available with NativeHalfType). FIXME(cir): For now lets pretend we
// shouldn't use the conversion intrinsics and insert a cast here
// unconditionally.
src = builder.createCast(cgf.getLoc(loc), cir::CastKind::floating, src,
cgf.floatTy);
srcType = cgf.getContext().FloatTy;
mlirSrcType = cgf.floatTy;
}
}
// TODO(cir): LLVM codegen ignore conversions like int -> uint,
// is there anything to be done for CIR here?
if (mlirSrcType == mlirDstType) {
if (opts.emitImplicitIntegerSignChangeChecks)
cgf.getCIRGenModule().errorNYI(loc,
"implicit integer sign change checks");
return src;
}
// Handle pointer conversions next: pointers can only be converted to/from
// other pointers and integers. Check for pointer types in terms of LLVM, as
// some native types (like Obj-C id) may map to a pointer type.
if (auto dstPT = dyn_cast<cir::PointerType>(mlirDstType)) {
cgf.getCIRGenModule().errorNYI(loc, "pointer casts");
return builder.getNullPtr(dstPT, src.getLoc());
}
if (isa<cir::PointerType>(mlirSrcType)) {
// Must be an ptr to int cast.
assert(isa<cir::IntType>(mlirDstType) && "not ptr->int?");
return builder.createPtrToInt(src, mlirDstType);
}
// A scalar can be splatted to an extended vector of the same element type
if (dstType->isExtVectorType() && !srcType->isVectorType()) {
// Sema should add casts to make sure that the source expression's type
// is the same as the vector's element type (sans qualifiers)
assert(dstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
srcType.getTypePtr() &&
"Splatted expr doesn't match with vector element type?");
cgf.getCIRGenModule().errorNYI(loc, "vector splatting");
return {};
}
if (srcType->isMatrixType() && dstType->isMatrixType()) {
cgf.getCIRGenModule().errorNYI(loc,
"matrix type to matrix type conversion");
return {};
}
assert(!srcType->isMatrixType() && !dstType->isMatrixType() &&
"Internal error: conversion between matrix type and scalar type");
// Finally, we have the arithmetic types or vectors of arithmetic types.
mlir::Value res = nullptr;
mlir::Type resTy = mlirDstType;
res = emitScalarCast(src, srcType, dstType, mlirSrcType, mlirDstType, opts);
if (mlirDstType != resTy) {
res = builder.createCast(cgf.getLoc(loc), cir::CastKind::floating, res,
resTy);
}
if (opts.emitImplicitIntegerTruncationChecks)
cgf.getCIRGenModule().errorNYI(loc, "implicit integer truncation checks");
if (opts.emitImplicitIntegerSignChangeChecks)
cgf.getCIRGenModule().errorNYI(loc,
"implicit integer sign change checks");