-
Notifications
You must be signed in to change notification settings - Fork 140
/
Copy pathCIRDialect.cpp
4069 lines (3487 loc) · 145 KB
/
CIRDialect.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
//===- CIRDialect.cpp - MLIR CIR ops implementation -----------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements the CIR dialect and its operations.
//
//===----------------------------------------------------------------------===//
#include "clang/CIR/Dialect/IR/CIRDialect.h"
#include "clang/AST/Attrs.inc"
#include "clang/CIR/Dialect/IR/CIRAttrs.h"
#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
#include "clang/CIR/Dialect/IR/CIRTypes.h"
#include "clang/CIR/Interfaces/CIRLoopOpInterface.h"
#include "clang/CIR/MissingFeatures.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#include <numeric>
#include <optional>
#include <set>
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/LLVMIR/LLVMTypes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/IR/DialectImplementation.h"
#include "mlir/IR/DialectInterface.h"
#include "mlir/IR/Location.h"
#include "mlir/IR/OpDefinition.h"
#include "mlir/IR/OpImplementation.h"
#include "mlir/IR/StorageUniquerSupport.h"
#include "mlir/IR/TypeUtilities.h"
#include "mlir/Interfaces/DataLayoutInterfaces.h"
#include "mlir/Interfaces/FunctionImplementation.h"
#include "mlir/Interfaces/InferTypeOpInterface.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Transforms/InliningUtils.h"
using namespace mlir;
#include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
#include "clang/CIR/Dialect/IR/CIROpsStructs.cpp.inc"
#include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
#include "clang/CIR/Interfaces/ASTAttrInterfaces.h"
#include "clang/CIR/Interfaces/CIROpInterfaces.h"
#include <clang/CIR/MissingFeatures.h>
//===----------------------------------------------------------------------===//
// CIR Dialect
//===----------------------------------------------------------------------===//
namespace {
struct CIROpAsmDialectInterface : public OpAsmDialectInterface {
using OpAsmDialectInterface::OpAsmDialectInterface;
AliasResult getAlias(Type type, raw_ostream &os) const final {
if (auto recordType = dyn_cast<cir::RecordType>(type)) {
StringAttr nameAttr = recordType.getName();
if (!nameAttr)
os << "ty_anon_" << recordType.getKindAsStr();
else
os << "ty_" << nameAttr.getValue();
return AliasResult::OverridableAlias;
}
if (auto intType = dyn_cast<cir::IntType>(type)) {
// We only provide alias for standard integer types (i.e. integer types
// whose width is divisible by 8).
if (intType.getWidth() % 8 != 0)
return AliasResult::NoAlias;
os << intType.getAlias();
return AliasResult::OverridableAlias;
}
if (auto voidType = dyn_cast<cir::VoidType>(type)) {
os << voidType.getAlias();
return AliasResult::OverridableAlias;
}
return AliasResult::NoAlias;
}
AliasResult getAlias(Attribute attr, raw_ostream &os) const final {
if (auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr)) {
os << (boolAttr.getValue() ? "true" : "false");
return AliasResult::FinalAlias;
}
if (auto bitfield = mlir::dyn_cast<cir::BitfieldInfoAttr>(attr)) {
os << "bfi_" << bitfield.getName().str();
return AliasResult::FinalAlias;
}
if (auto extraFuncAttr =
mlir::dyn_cast<cir::ExtraFuncAttributesAttr>(attr)) {
os << "fn_attr";
return AliasResult::FinalAlias;
}
if (auto cmpThreeWayInfoAttr =
mlir::dyn_cast<cir::CmpThreeWayInfoAttr>(attr)) {
os << cmpThreeWayInfoAttr.getAlias();
return AliasResult::FinalAlias;
}
if (auto dynCastInfoAttr = mlir::dyn_cast<cir::DynamicCastInfoAttr>(attr)) {
os << dynCastInfoAttr.getAlias();
return AliasResult::FinalAlias;
}
return TypeSwitch<Attribute, AliasResult>(attr)
.Case<cir::TBAAAttr, cir::TBAAOmnipotentCharAttr,
cir::TBAAVTablePointerAttr, cir::TBAAScalarAttr,
cir::TBAAStructAttr, cir::TBAATagAttr>([&](auto attr) {
os << decltype(attr)::getMnemonic();
return AliasResult::OverridableAlias;
})
.Default([](Attribute) { return AliasResult::NoAlias; });
}
};
// Minimal interface to inline region with only one block for now (not handling
// the terminator remapping), assuming everything is inlinable.
struct CIRInlinerInterface : DialectInlinerInterface {
using DialectInlinerInterface::DialectInlinerInterface;
// Always allows inlining.
bool isLegalToInline(Operation *call, Operation *callable,
bool wouldBeCloned) const final override {
return true;
}
// Always allows inlining.
bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
IRMapping &valueMapping) const final override {
return true;
}
// Always allows inlining.
bool isLegalToInline(Operation *op, Region *, bool wouldBeCloned,
IRMapping &) const final override {
return true;
}
// Handle the terminator in the case of a single block
void handleTerminator(Operation *op,
ValueRange valuesToReplace) const final override {
// Only handle cir.return for now
if (auto returnOp = dyn_cast<cir::ReturnOp>(op))
for (auto &&[value, operand] :
llvm::zip(valuesToReplace, returnOp.getOperands()))
value.replaceAllUsesWith(operand);
}
};
} // namespace
/// Dialect initialization, the instance will be owned by the context. This is
/// the point of registration of types and operations for the dialect.
void cir::CIRDialect::initialize() {
registerTypes();
registerAttributes();
addOperations<
#define GET_OP_LIST
#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
>();
addInterfaces<CIRInlinerInterface, CIROpAsmDialectInterface>();
}
Operation *cir::CIRDialect::materializeConstant(mlir::OpBuilder &builder,
mlir::Attribute value,
mlir::Type type,
mlir::Location loc) {
return builder.create<cir::ConstantOp>(loc, type,
mlir::cast<mlir::TypedAttr>(value));
}
//===----------------------------------------------------------------------===//
// Helpers
//===----------------------------------------------------------------------===//
// Parses one of the keywords provided in the list `keywords` and returns the
// position of the parsed keyword in the list. If none of the keywords from the
// list is parsed, returns -1.
static int parseOptionalKeywordAlternative(AsmParser &parser,
ArrayRef<llvm::StringRef> keywords) {
for (auto en : llvm::enumerate(keywords)) {
if (succeeded(parser.parseOptionalKeyword(en.value())))
return en.index();
}
return -1;
}
namespace {
template <typename Ty> struct EnumTraits {};
#define REGISTER_ENUM_TYPE(Ty) \
template <> struct EnumTraits<cir::Ty> { \
static llvm::StringRef stringify(cir::Ty value) { \
return stringify##Ty(value); \
} \
static unsigned getMaxEnumVal() { return cir::getMaxEnumValFor##Ty(); } \
}
#define REGISTER_ENUM_TYPE_WITH_NS(NS, Ty) \
template <> struct EnumTraits<NS::Ty> { \
static llvm::StringRef stringify(NS::Ty value) { \
return NS::stringify##Ty(value); \
} \
static unsigned getMaxEnumVal() { return NS::getMaxEnumValFor##Ty(); } \
}
REGISTER_ENUM_TYPE(GlobalLinkageKind);
REGISTER_ENUM_TYPE(VisibilityKind);
REGISTER_ENUM_TYPE(CallingConv);
REGISTER_ENUM_TYPE(SideEffect);
REGISTER_ENUM_TYPE_WITH_NS(cir::sob, SignedOverflowBehavior);
} // namespace
/// Parse an enum from the keyword, or default to the provided default value.
/// The return type is the enum type by default, unless overriden with the
/// second template argument.
template <typename EnumTy, typename RetTy = EnumTy>
static RetTy parseOptionalCIRKeyword(AsmParser &parser, EnumTy defaultValue) {
llvm::SmallVector<llvm::StringRef, 10> names;
for (unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
names.push_back(EnumTraits<EnumTy>::stringify(static_cast<EnumTy>(i)));
int index = parseOptionalKeywordAlternative(parser, names);
if (index == -1)
return static_cast<RetTy>(defaultValue);
return static_cast<RetTy>(index);
}
/// Parse an enum from the keyword, return failure if the keyword is not found.
template <typename EnumTy, typename RetTy = EnumTy>
static ParseResult parseCIRKeyword(AsmParser &parser, RetTy &result) {
llvm::SmallVector<llvm::StringRef, 10> names;
for (unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
names.push_back(EnumTraits<EnumTy>::stringify(static_cast<EnumTy>(i)));
int index = parseOptionalKeywordAlternative(parser, names);
if (index == -1)
return failure();
result = static_cast<RetTy>(index);
return success();
}
// Check if a region's termination omission is valid and, if so, creates and
// inserts the omitted terminator into the region.
LogicalResult ensureRegionTerm(OpAsmParser &parser, Region ®ion,
SMLoc errLoc) {
Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
OpBuilder builder(parser.getBuilder().getContext());
// Insert empty block in case the region is empty to ensure the terminator
// will be inserted
if (region.empty())
builder.createBlock(®ion);
Block &block = region.back();
// Region is properly terminated: nothing to do.
if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
return success();
// Check for invalid terminator omissions.
if (!region.hasOneBlock())
return parser.emitError(errLoc,
"multi-block region must not omit terminator");
// Terminator was omitted correctly: recreate it.
builder.setInsertionPointToEnd(&block);
builder.create<cir::YieldOp>(eLoc);
return success();
}
// True if the region's terminator should be omitted.
bool omitRegionTerm(mlir::Region &r) {
const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
const auto yieldsNothing = [&r]() {
auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
return y && y.getArgs().empty();
};
return singleNonEmptyBlock && yieldsNothing();
}
void printVisibilityAttr(OpAsmPrinter &printer,
cir::VisibilityAttr &visibility) {
switch (visibility.getValue()) {
case cir::VisibilityKind::Hidden:
printer << "hidden";
break;
case cir::VisibilityKind::Protected:
printer << "protected";
break;
default:
break;
}
}
void parseVisibilityAttr(OpAsmParser &parser, cir::VisibilityAttr &visibility) {
cir::VisibilityKind visibilityKind =
parseOptionalCIRKeyword(parser, cir::VisibilityKind::Default);
visibility = cir::VisibilityAttr::get(parser.getContext(), visibilityKind);
}
//===----------------------------------------------------------------------===//
// CIR Custom Parsers/Printers
//===----------------------------------------------------------------------===//
static mlir::ParseResult
parseOmittedTerminatorRegion(mlir::OpAsmParser &parser,
mlir::Region &scopeRegion,
mlir::Region &cleanupRegion) {
auto regionLoc = parser.getCurrentLocation();
if (parser.parseRegion(scopeRegion))
return failure();
if (ensureRegionTerm(parser, scopeRegion, regionLoc).failed())
return failure();
// Parse optional cleanup region.
if (parser.parseOptionalKeyword("cleanup").succeeded()) {
if (parser.parseRegion(cleanupRegion, /*arguments=*/{}, /*argTypes=*/{}))
return failure();
if (ensureRegionTerm(parser, cleanupRegion, regionLoc).failed())
return failure();
}
return success();
}
static void printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer,
cir::ScopeOp &op,
mlir::Region &scopeRegion,
mlir::Region &cleanupRegion) {
printer.printRegion(scopeRegion,
/*printEntryBlockArgs=*/false,
/*printBlockTerminators=*/!omitRegionTerm(scopeRegion));
if (!op.getCleanupRegion().empty()) {
printer << " cleanup ";
printer.printRegion(
cleanupRegion,
/*printEntryBlockArgs=*/false,
/*printBlockTerminators=*/!omitRegionTerm(cleanupRegion));
}
}
//===----------------------------------------------------------------------===//
// AllocaOp
//===----------------------------------------------------------------------===//
void cir::AllocaOp::build(::mlir::OpBuilder &odsBuilder,
::mlir::OperationState &odsState, ::mlir::Type addr,
::mlir::Type allocaType, ::llvm::StringRef name,
::mlir::IntegerAttr alignment) {
odsState.addAttribute(getAllocaTypeAttrName(odsState.name),
::mlir::TypeAttr::get(allocaType));
odsState.addAttribute(getNameAttrName(odsState.name),
odsBuilder.getStringAttr(name));
if (alignment) {
odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
}
odsState.addTypes(addr);
}
//===----------------------------------------------------------------------===//
// BreakOp
//===----------------------------------------------------------------------===//
LogicalResult cir::BreakOp::verify() {
if (!getOperation()->getParentOfType<LoopOpInterface>() &&
!getOperation()->getParentOfType<SwitchOp>())
return emitOpError("must be within a loop or switch");
return success();
}
//===----------------------------------------------------------------------===//
// ConditionOp
//===-----------------------------------------------------------------------===//
//===----------------------------------
// BranchOpTerminatorInterface Methods
void cir::ConditionOp::getSuccessorRegions(
ArrayRef<Attribute> operands, SmallVectorImpl<RegionSuccessor> ®ions) {
// TODO(cir): The condition value may be folded to a constant, narrowing
// down its list of possible successors.
// Parent is a loop: condition may branch to the body or to the parent op.
if (auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
regions.emplace_back(&loopOp.getBody(), loopOp.getBody().getArguments());
regions.emplace_back(loopOp->getResults());
}
// Parent is an await: condition may branch to resume or suspend regions.
auto await = cast<AwaitOp>(getOperation()->getParentOp());
regions.emplace_back(&await.getResume(), await.getResume().getArguments());
regions.emplace_back(&await.getSuspend(), await.getSuspend().getArguments());
}
MutableOperandRange
cir::ConditionOp::getMutableSuccessorOperands(RegionBranchPoint point) {
// No values are yielded to the successor region.
return MutableOperandRange(getOperation(), 0, 0);
}
LogicalResult cir::ConditionOp::verify() {
if (!isa<LoopOpInterface, AwaitOp>(getOperation()->getParentOp()))
return emitOpError("condition must be within a conditional region");
return success();
}
//===----------------------------------------------------------------------===//
// ConstantOp
//===----------------------------------------------------------------------===//
static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType,
mlir::Attribute attrType) {
if (isa<cir::ConstPtrAttr>(attrType)) {
if (::mlir::isa<cir::PointerType>(opType))
return success();
return op->emitOpError("nullptr expects pointer type");
}
if (isa<cir::DataMemberAttr, cir::MethodAttr>(attrType)) {
// More detailed type verifications are already done in
// DataMemberAttr::verify. Don't need to repeat here.
return success();
}
if (isa<cir::ZeroAttr>(attrType)) {
if (::mlir::isa<cir::RecordType, cir::ArrayType, cir::ComplexType,
cir::VectorType>(opType))
return success();
return op->emitOpError("zero expects record or array type");
}
if (isa<cir::UndefAttr>(attrType)) {
if (!::mlir::isa<cir::VoidType>(opType))
return success();
return op->emitOpError("undef expects non-void type");
}
if (isa<cir::PoisonAttr>(attrType)) {
if (!::mlir::isa<cir::VoidType>(opType))
return success();
return op->emitOpError("poison expects non-void type");
}
if (mlir::isa<cir::BoolAttr>(attrType)) {
if (!mlir::isa<cir::BoolType>(opType))
return op->emitOpError("result type (")
<< opType << ") must be '!cir.bool' for '" << attrType << "'";
return success();
}
if (mlir::isa<cir::IntAttr, cir::FPAttr, cir::ComplexAttr>(attrType)) {
auto at = cast<TypedAttr>(attrType);
if (at.getType() != opType) {
return op->emitOpError("result type (")
<< opType << ") does not match value type (" << at.getType()
<< ")";
}
return success();
}
if (isa<SymbolRefAttr>(attrType)) {
if (::mlir::isa<cir::PointerType>(opType))
return success();
return op->emitOpError("symbolref expects pointer type");
}
if (mlir::isa<cir::GlobalViewAttr>(attrType) ||
mlir::isa<cir::TypeInfoAttr>(attrType) ||
mlir::isa<cir::ConstArrayAttr>(attrType) ||
mlir::isa<cir::ConstVectorAttr>(attrType) ||
mlir::isa<cir::ConstRecordAttr>(attrType) ||
mlir::isa<cir::VTableAttr>(attrType))
return success();
if (mlir::isa<cir::IntAttr>(attrType))
return success();
assert(isa<TypedAttr>(attrType) && "What else could we be looking at here?");
return op->emitOpError("global with type ")
<< cast<TypedAttr>(attrType).getType() << " not supported";
}
LogicalResult cir::ConstantOp::verify() {
// ODS already generates checks to make sure the result type is valid. We just
// need to additionally check that the value's attribute type is consistent
// with the result type.
return checkConstantTypes(getOperation(), getType(), getValue());
}
OpFoldResult cir::ConstantOp::fold(FoldAdaptor /*adaptor*/) {
return getValue();
}
//===----------------------------------------------------------------------===//
// ContinueOp
//===----------------------------------------------------------------------===//
LogicalResult cir::ContinueOp::verify() {
if (!this->getOperation()->getParentOfType<LoopOpInterface>())
return emitOpError("must be within a loop");
return success();
}
//===----------------------------------------------------------------------===//
// AtomicXchg
//===----------------------------------------------------------------------===//
LogicalResult cir::AtomicXchg::verify() {
if (getPtr().getType().getPointee() != getVal().getType())
return emitOpError("ptr type and val type must match");
return success();
}
//===----------------------------------------------------------------------===//
// AtomicCmpXchg
//===----------------------------------------------------------------------===//
LogicalResult cir::AtomicCmpXchg::verify() {
auto pointeeType = getPtr().getType().getPointee();
if (pointeeType != getExpected().getType() or
pointeeType != getDesired().getType())
return emitOpError("ptr, expected and desired types must match");
return success();
}
//===----------------------------------------------------------------------===//
// CastOp
//===----------------------------------------------------------------------===//
LogicalResult cir::CastOp::verify() {
auto resType = getResult().getType();
auto srcType = getSrc().getType();
if (mlir::isa<cir::VectorType>(srcType) &&
mlir::isa<cir::VectorType>(resType)) {
// Use the element type of the vector to verify the cast kind. (Except for
// bitcast, see below.)
srcType = mlir::dyn_cast<cir::VectorType>(srcType).getEltType();
resType = mlir::dyn_cast<cir::VectorType>(resType).getEltType();
}
switch (getKind()) {
case cir::CastKind::int_to_bool: {
if (!mlir::isa<cir::BoolType>(resType))
return emitOpError() << "requires !cir.bool type for result";
if (!mlir::isa<cir::IntType>(srcType))
return emitOpError() << "requires !cir.int type for source";
return success();
}
case cir::CastKind::ptr_to_bool: {
if (!mlir::isa<cir::BoolType>(resType))
return emitOpError() << "requires !cir.bool type for result";
if (!mlir::isa<cir::PointerType>(srcType))
return emitOpError() << "requires !cir.ptr type for source";
return success();
}
case cir::CastKind::integral: {
if (!mlir::isa<cir::IntType>(resType))
return emitOpError() << "requires !cir.int type for result";
if (!mlir::isa<cir::IntType>(srcType))
return emitOpError() << "requires !cir.int type for source";
return success();
}
case cir::CastKind::array_to_ptrdecay: {
auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
if (!arrayPtrTy || !flatPtrTy)
return emitOpError() << "requires !cir.ptr type for source and result";
if (arrayPtrTy.getAddrSpace() != flatPtrTy.getAddrSpace()) {
return emitOpError()
<< "requires same address space for source and result";
}
auto arrayTy = mlir::dyn_cast<cir::ArrayType>(arrayPtrTy.getPointee());
if (!arrayTy)
return emitOpError() << "requires !cir.array pointee";
if (arrayTy.getEltType() != flatPtrTy.getPointee())
return emitOpError()
<< "requires same type for array element and pointee result";
return success();
}
case cir::CastKind::bitcast: {
// Allow bitcast of records for calling conventions.
if (isa<RecordType>(srcType) || isa<RecordType>(resType))
return success();
// Handle the pointer types first.
auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
if (srcPtrTy && resPtrTy) {
if (srcPtrTy.getAddrSpace() != resPtrTy.getAddrSpace()) {
return emitOpError() << "result type address space does not match the "
"address space of the operand";
}
return success();
}
// Handle the data member pointer types.
if (mlir::isa<cir::DataMemberType>(srcType) &&
mlir::isa<cir::DataMemberType>(resType))
return success();
// Handle the pointer to member function types.
if (mlir::isa<cir::MethodType>(srcType) &&
mlir::isa<cir::MethodType>(resType))
return success();
// This is the only cast kind where we don't want vector types to decay
// into the element type.
if ((!mlir::isa<cir::VectorType>(getSrc().getType()) ||
!mlir::isa<cir::VectorType>(getResult().getType())))
return emitOpError()
<< "requires !cir.ptr or !cir.vector type for source and result";
return success();
}
case cir::CastKind::floating: {
if (!mlir::isa<cir::CIRFPTypeInterface>(srcType) ||
!mlir::isa<cir::CIRFPTypeInterface>(resType))
return emitOpError() << "requires !cir.float type for source and result";
return success();
}
case cir::CastKind::float_to_int: {
if (!mlir::isa<cir::CIRFPTypeInterface>(srcType))
return emitOpError() << "requires !cir.float type for source";
if (!mlir::dyn_cast<cir::IntType>(resType))
return emitOpError() << "requires !cir.int type for result";
return success();
}
case cir::CastKind::int_to_ptr: {
if (!mlir::dyn_cast<cir::IntType>(srcType))
return emitOpError() << "requires !cir.int type for source";
if (!mlir::dyn_cast<cir::PointerType>(resType))
return emitOpError() << "requires !cir.ptr type for result";
return success();
}
case cir::CastKind::ptr_to_int: {
if (!mlir::dyn_cast<cir::PointerType>(srcType))
return emitOpError() << "requires !cir.ptr type for source";
if (!mlir::dyn_cast<cir::IntType>(resType))
return emitOpError() << "requires !cir.int type for result";
return success();
}
case cir::CastKind::float_to_bool: {
if (!mlir::isa<cir::CIRFPTypeInterface>(srcType))
return emitOpError() << "requires !cir.float type for source";
if (!mlir::isa<cir::BoolType>(resType))
return emitOpError() << "requires !cir.bool type for result";
return success();
}
case cir::CastKind::bool_to_int: {
if (!mlir::isa<cir::BoolType>(srcType))
return emitOpError() << "requires !cir.bool type for source";
if (!mlir::isa<cir::IntType>(resType))
return emitOpError() << "requires !cir.int type for result";
return success();
}
case cir::CastKind::int_to_float: {
if (!mlir::isa<cir::IntType>(srcType))
return emitOpError() << "requires !cir.int type for source";
if (!mlir::isa<cir::CIRFPTypeInterface>(resType))
return emitOpError() << "requires !cir.float type for result";
return success();
}
case cir::CastKind::bool_to_float: {
if (!mlir::isa<cir::BoolType>(srcType))
return emitOpError() << "requires !cir.bool type for source";
if (!mlir::isa<cir::CIRFPTypeInterface>(resType))
return emitOpError() << "requires !cir.float type for result";
return success();
}
case cir::CastKind::address_space: {
auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
if (!srcPtrTy || !resPtrTy)
return emitOpError() << "requires !cir.ptr type for source and result";
if (srcPtrTy.getPointee() != resPtrTy.getPointee())
return emitOpError() << "requires two types differ in addrspace only";
return success();
}
case cir::CastKind::float_to_complex: {
if (!mlir::isa<cir::CIRFPTypeInterface>(srcType))
return emitOpError() << "requires !cir.float type for source";
auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
if (!resComplexTy)
return emitOpError() << "requires !cir.complex type for result";
if (srcType != resComplexTy.getElementTy())
return emitOpError() << "requires source type match result element type";
return success();
}
case cir::CastKind::int_to_complex: {
if (!mlir::isa<cir::IntType>(srcType))
return emitOpError() << "requires !cir.int type for source";
auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
if (!resComplexTy)
return emitOpError() << "requires !cir.complex type for result";
if (srcType != resComplexTy.getElementTy())
return emitOpError() << "requires source type match result element type";
return success();
}
case cir::CastKind::float_complex_to_real: {
auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
if (!srcComplexTy)
return emitOpError() << "requires !cir.complex type for source";
if (!mlir::isa<cir::CIRFPTypeInterface>(resType))
return emitOpError() << "requires !cir.float type for result";
if (srcComplexTy.getElementTy() != resType)
return emitOpError() << "requires source element type match result type";
return success();
}
case cir::CastKind::int_complex_to_real: {
auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
if (!srcComplexTy)
return emitOpError() << "requires !cir.complex type for source";
if (!mlir::isa<cir::IntType>(resType))
return emitOpError() << "requires !cir.int type for result";
if (srcComplexTy.getElementTy() != resType)
return emitOpError() << "requires source element type match result type";
return success();
}
case cir::CastKind::float_complex_to_bool: {
auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
if (!srcComplexTy ||
!mlir::isa<cir::CIRFPTypeInterface>(srcComplexTy.getElementTy()))
return emitOpError()
<< "requires !cir.complex<!cir.float> type for source";
if (!mlir::isa<cir::BoolType>(resType))
return emitOpError() << "requires !cir.bool type for result";
return success();
}
case cir::CastKind::int_complex_to_bool: {
auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
if (!srcComplexTy || !mlir::isa<cir::IntType>(srcComplexTy.getElementTy()))
return emitOpError()
<< "requires !cir.complex<!cir.float> type for source";
if (!mlir::isa<cir::BoolType>(resType))
return emitOpError() << "requires !cir.bool type for result";
return success();
}
case cir::CastKind::float_complex: {
auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
if (!srcComplexTy ||
!mlir::isa<cir::CIRFPTypeInterface>(srcComplexTy.getElementTy()))
return emitOpError()
<< "requires !cir.complex<!cir.float> type for source";
auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
if (!resComplexTy ||
!mlir::isa<cir::CIRFPTypeInterface>(resComplexTy.getElementTy()))
return emitOpError()
<< "requires !cir.complex<!cir.float> type for result";
return success();
}
case cir::CastKind::float_complex_to_int_complex: {
auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
if (!srcComplexTy ||
!mlir::isa<cir::CIRFPTypeInterface>(srcComplexTy.getElementTy()))
return emitOpError()
<< "requires !cir.complex<!cir.float> type for source";
auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
if (!resComplexTy || !mlir::isa<cir::IntType>(resComplexTy.getElementTy()))
return emitOpError() << "requires !cir.complex<!cir.int> type for result";
return success();
}
case cir::CastKind::int_complex: {
auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
if (!srcComplexTy || !mlir::isa<cir::IntType>(srcComplexTy.getElementTy()))
return emitOpError() << "requires !cir.complex<!cir.int> type for source";
auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
if (!resComplexTy || !mlir::isa<cir::IntType>(resComplexTy.getElementTy()))
return emitOpError() << "requires !cir.complex<!cir.int> type for result";
return success();
}
case cir::CastKind::int_complex_to_float_complex: {
auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
if (!srcComplexTy || !mlir::isa<cir::IntType>(srcComplexTy.getElementTy()))
return emitOpError() << "requires !cir.complex<!cir.int> type for source";
auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
if (!resComplexTy ||
!mlir::isa<cir::CIRFPTypeInterface>(resComplexTy.getElementTy()))
return emitOpError()
<< "requires !cir.complex<!cir.float> type for result";
return success();
}
case cir::CastKind::member_ptr_to_bool: {
if (!mlir::isa<cir::DataMemberType, cir::MethodType>(srcType))
return emitOpError()
<< "requires !cir.data_member or !cir.method type for source";
if (!mlir::isa<cir::BoolType>(resType))
return emitOpError() << "requires !cir.bool type for result";
return success();
}
}
llvm_unreachable("Unknown CastOp kind?");
}
bool isIntOrBoolCast(cir::CastOp op) {
auto kind = op.getKind();
return kind == cir::CastKind::bool_to_int ||
kind == cir::CastKind::int_to_bool || kind == cir::CastKind::integral;
}
Value tryFoldCastChain(cir::CastOp op) {
cir::CastOp head = op, tail = op;
while (op) {
if (!isIntOrBoolCast(op))
break;
head = op;
op = dyn_cast_or_null<cir::CastOp>(head.getSrc().getDefiningOp());
}
if (head == tail)
return {};
// if bool_to_int -> ... -> int_to_bool: take the bool
// as we had it was before all casts
if (head.getKind() == cir::CastKind::bool_to_int &&
tail.getKind() == cir::CastKind::int_to_bool)
return head.getSrc();
// if int_to_bool -> ... -> int_to_bool: take the result
// of the first one, as no other casts (and ext casts as well)
// don't change the first result
if (head.getKind() == cir::CastKind::int_to_bool &&
tail.getKind() == cir::CastKind::int_to_bool)
return head.getResult();
return {};
}
OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
if (getSrc().getType() == getResult().getType()) {
switch (getKind()) {
case cir::CastKind::integral: {
// TODO: for sign differences, it's possible in certain conditions to
// create a new attribute that's capable of representing the source.
llvm::SmallVector<mlir::OpFoldResult, 1> foldResults;
auto foldOrder = getSrc().getDefiningOp()->fold(foldResults);
if (foldOrder.succeeded() && mlir::isa<mlir::Attribute>(foldResults[0]))
return mlir::cast<mlir::Attribute>(foldResults[0]);
return {};
}
case cir::CastKind::bitcast:
case cir::CastKind::address_space:
case cir::CastKind::float_complex:
case cir::CastKind::int_complex: {
return getSrc();
}
default:
return {};
}
}
return tryFoldCastChain(*this);
}
static bool isBoolNot(cir::UnaryOp op) {
return isa<cir::BoolType>(op.getInput().getType()) &&
op.getKind() == cir::UnaryOpKind::Not;
}
// This folder simplifies the sequential boolean not operations.
// For instance, the next two unary operations will be eliminated:
//
// ```mlir
// %1 = cir.unary(not, %0) : !cir.bool, !cir.bool
// %2 = cir.unary(not, %1) : !cir.bool, !cir.bool
// ```
//
// and the argument of the first one (%0) will be used instead.
OpFoldResult cir::UnaryOp::fold(FoldAdaptor adaptor) {
if (isBoolNot(*this))
if (auto previous = dyn_cast_or_null<UnaryOp>(getInput().getDefiningOp()))
if (isBoolNot(previous))
return previous.getInput();
return {};
}
//===----------------------------------------------------------------------===//
// DynamicCastOp
//===----------------------------------------------------------------------===//
LogicalResult cir::DynamicCastOp::verify() {
auto resultPointeeTy = mlir::cast<cir::PointerType>(getType()).getPointee();
if (!mlir::isa<cir::VoidType, cir::RecordType>(resultPointeeTy))
return emitOpError()
<< "cir.dyn_cast must produce a void ptr or record ptr";
return mlir::success();
}
//===----------------------------------------------------------------------===//
// BaseDataMemberOp & DerivedDataMemberOp
//===----------------------------------------------------------------------===//
static LogicalResult verifyMemberPtrCast(Operation *op, mlir::Value src,
mlir::Type resultTy) {
// Let the operand type be T1 C1::*, let the result type be T2 C2::*.
// Verify that T1 and T2 are the same type.
mlir::Type inputMemberTy;
mlir::Type resultMemberTy;
if (mlir::isa<cir::DataMemberType>(src.getType())) {
inputMemberTy =
mlir::cast<cir::DataMemberType>(src.getType()).getMemberTy();
resultMemberTy = mlir::cast<cir::DataMemberType>(resultTy).getMemberTy();
} else {
inputMemberTy =
mlir::cast<cir::MethodType>(src.getType()).getMemberFuncTy();
resultMemberTy = mlir::cast<cir::MethodType>(resultTy).getMemberFuncTy();
}
if (inputMemberTy != resultMemberTy)
return op->emitOpError()
<< "member types of the operand and the result do not match";
return mlir::success();
}
LogicalResult cir::BaseDataMemberOp::verify() {
return verifyMemberPtrCast(getOperation(), getSrc(), getType());
}
LogicalResult cir::DerivedDataMemberOp::verify() {
return verifyMemberPtrCast(getOperation(), getSrc(), getType());
}
//===----------------------------------------------------------------------===//
// BaseMethodOp & DerivedMethodOp
//===----------------------------------------------------------------------===//
LogicalResult cir::BaseMethodOp::verify() {
return verifyMemberPtrCast(getOperation(), getSrc(), getType());
}
LogicalResult cir::DerivedMethodOp::verify() {
return verifyMemberPtrCast(getOperation(), getSrc(), getType());
}
//===----------------------------------------------------------------------===//
// ComplexCreateOp
//===----------------------------------------------------------------------===//
LogicalResult cir::ComplexCreateOp::verify() {
if (getType().getElementTy() != getReal().getType()) {
emitOpError()
<< "operand type of cir.complex.create does not match its result type";
return failure();
}
return success();
}
OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
auto real = adaptor.getReal();
auto imag = adaptor.getImag();
if (!real || !imag)
return nullptr;
// When both of real and imag are constants, we can fold the operation into an
// `cir.const #cir.complex` operation.
auto realAttr = mlir::cast<mlir::TypedAttr>(real);
auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
assert(realAttr.getType() == imagAttr.getType() &&
"real part and imag part should be of the same type");
auto complexTy = cir::ComplexType::get(getContext(), realAttr.getType());
return cir::ComplexAttr::get(complexTy, realAttr, imagAttr);
}
//===----------------------------------------------------------------------===//
// ComplexRealOp and ComplexImagOp
//===----------------------------------------------------------------------===//
LogicalResult cir::ComplexRealOp::verify() {
if (getType() != getOperand().getType().getElementTy()) {
emitOpError() << "cir.complex.real result type does not match operand type";
return failure();
}
return success();
}
OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
auto input = mlir::cast_if_present<cir::ComplexAttr>(adaptor.getOperand());
if (input)
return input.getReal();
return nullptr;
}
LogicalResult cir::ComplexImagOp::verify() {
if (getType() != getOperand().getType().getElementTy()) {
emitOpError() << "cir.complex.imag result type does not match operand type";
return failure();