-
Notifications
You must be signed in to change notification settings - Fork 85
/
LowerToLLVM.cpp
1615 lines (1417 loc) · 63.7 KB
/
LowerToLLVM.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
//====- LowerToLLVM.cpp - Lowering from CIR to LLVMIR ---------------------===//
//
// 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 lowering of CIR operations to LLVMIR.
//
//===----------------------------------------------------------------------===//
#include "mlir/Conversion/AffineToStandard/AffineToStandard.h"
#include "mlir/Conversion/ControlFlowToLLVM/ControlFlowToLLVM.h"
#include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h"
#include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVMPass.h"
#include "mlir/Conversion/LLVMCommon/ConversionTarget.h"
#include "mlir/Conversion/LLVMCommon/TypeConverter.h"
#include "mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h"
#include "mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
#include "mlir/Dialect/DLTI/DLTI.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/LLVMIR/LLVMAttrs.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/LLVMIR/LLVMTypes.h"
#include "mlir/Dialect/LLVMIR/Transforms/Passes.h"
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/Dialect/SCF/Transforms/Passes.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinAttributeInterfaces.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/BuiltinDialect.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/IRMapping.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/Value.h"
#include "mlir/IR/ValueRange.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Target/LLVMIR/Dialect/Builtin/BuiltinToLLVMIRTranslation.h"
#include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h"
#include "mlir/Target/LLVMIR/Export.h"
#include "mlir/Transforms/DialectConversion.h"
#include "clang/CIR/Dialect/IR/CIRAttrs.h"
#include "clang/CIR/Dialect/IR/CIRDialect.h"
#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
#include "clang/CIR/Dialect/IR/CIRTypes.h"
#include "clang/CIR/Passes.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ErrorHandling.h"
#include <cstdint>
#include <optional>
using namespace cir;
using namespace llvm;
namespace cir {
namespace direct {
mlir::LLVM::Linkage convertLinkage(mlir::cir::GlobalLinkageKind linkage) {
using CIR = mlir::cir::GlobalLinkageKind;
using LLVM = mlir::LLVM::Linkage;
switch (linkage) {
case CIR::AvailableExternallyLinkage:
return LLVM::AvailableExternally;
case CIR::CommonLinkage:
return LLVM::Common;
case CIR::ExternalLinkage:
return LLVM::External;
case CIR::ExternalWeakLinkage:
return LLVM::ExternWeak;
case CIR::InternalLinkage:
return LLVM::Internal;
case CIR::LinkOnceAnyLinkage:
return LLVM::Linkonce;
case CIR::LinkOnceODRLinkage:
return LLVM::LinkonceODR;
case CIR::PrivateLinkage:
return LLVM::Private;
case CIR::WeakAnyLinkage:
return LLVM::Weak;
case CIR::WeakODRLinkage:
return LLVM::WeakODR;
};
}
class CIRPtrStrideOpLowering
: public mlir::OpConversionPattern<mlir::cir::PtrStrideOp> {
public:
using mlir::OpConversionPattern<mlir::cir::PtrStrideOp>::OpConversionPattern;
mlir::LogicalResult
matchAndRewrite(mlir::cir::PtrStrideOp ptrStrideOp, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
auto *tc = getTypeConverter();
rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
ptrStrideOp, tc->convertType(ptrStrideOp.getType()), adaptor.getBase(),
adaptor.getStride());
return mlir::success();
}
};
class CIRLoopOpLowering : public mlir::OpConversionPattern<mlir::cir::LoopOp> {
public:
using mlir::OpConversionPattern<mlir::cir::LoopOp>::OpConversionPattern;
using LoopKind = mlir::cir::LoopOpKind;
mlir::LogicalResult
fetchCondRegionYields(mlir::Region &condRegion,
mlir::cir::YieldOp &yieldToBody,
mlir::cir::YieldOp &yieldToCont) const {
for (auto &bb : condRegion) {
if (auto yieldOp = dyn_cast<mlir::cir::YieldOp>(bb.getTerminator())) {
if (!yieldOp.getKind().has_value())
yieldToCont = yieldOp;
else if (yieldOp.getKind() == mlir::cir::YieldOpKind::Continue)
yieldToBody = yieldOp;
else
return mlir::failure();
}
}
// Succeed only if both yields are found.
if (!yieldToBody || !yieldToCont)
return mlir::failure();
return mlir::success();
}
mlir::LogicalResult
matchAndRewrite(mlir::cir::LoopOp loopOp, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
auto kind = loopOp.getKind();
auto *currentBlock = rewriter.getInsertionBlock();
auto *continueBlock =
rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
// Fetch required info from the condition region.
auto &condRegion = loopOp.getCond();
auto &condFrontBlock = condRegion.front();
mlir::cir::YieldOp yieldToBody, yieldToCont;
if (fetchCondRegionYields(condRegion, yieldToBody, yieldToCont).failed())
return loopOp.emitError("failed to fetch yields in cond region");
// Fetch required info from the body region.
auto &bodyRegion = loopOp.getBody();
auto &bodyFrontBlock = bodyRegion.front();
auto bodyYield =
dyn_cast<mlir::cir::YieldOp>(bodyRegion.back().getTerminator());
assert(bodyYield && "unstructured while loops are NYI");
// Fetch required info from the step region.
auto &stepRegion = loopOp.getStep();
auto &stepFrontBlock = stepRegion.front();
auto stepYield =
dyn_cast<mlir::cir::YieldOp>(stepRegion.back().getTerminator());
// Move loop op region contents to current CFG.
rewriter.inlineRegionBefore(condRegion, continueBlock);
rewriter.inlineRegionBefore(bodyRegion, continueBlock);
if (kind == LoopKind::For) // Ignore step if not a for-loop.
rewriter.inlineRegionBefore(stepRegion, continueBlock);
// Set loop entry point to condition or to body in do-while cases.
rewriter.setInsertionPointToEnd(currentBlock);
auto &entry = (kind != LoopKind::DoWhile ? condFrontBlock : bodyFrontBlock);
rewriter.create<mlir::cir::BrOp>(loopOp.getLoc(), &entry);
// Set loop exit point to continue block.
rewriter.setInsertionPoint(yieldToCont);
rewriter.replaceOpWithNewOp<mlir::cir::BrOp>(yieldToCont, continueBlock);
// Branch from condition to body.
rewriter.setInsertionPoint(yieldToBody);
rewriter.replaceOpWithNewOp<mlir::cir::BrOp>(yieldToBody, &bodyFrontBlock);
// Branch from body to condition or to step on for-loop cases.
rewriter.setInsertionPoint(bodyYield);
auto &bodyExit = (kind == LoopKind::For ? stepFrontBlock : condFrontBlock);
rewriter.replaceOpWithNewOp<mlir::cir::BrOp>(bodyYield, &bodyExit);
// Is a for loop: branch from step to condition.
if (kind == LoopKind::For) {
rewriter.setInsertionPoint(stepYield);
rewriter.replaceOpWithNewOp<mlir::cir::BrOp>(stepYield, &condFrontBlock);
}
// Remove the loop op.
rewriter.eraseOp(loopOp);
return mlir::success();
}
};
class CIRBrCondOpLowering
: public mlir::OpConversionPattern<mlir::cir::BrCondOp> {
public:
using mlir::OpConversionPattern<mlir::cir::BrCondOp>::OpConversionPattern;
mlir::LogicalResult
matchAndRewrite(mlir::cir::BrCondOp brOp, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
auto condition = adaptor.getCond();
auto i1Condition = rewriter.create<mlir::LLVM::TruncOp>(
brOp.getLoc(), rewriter.getI1Type(), condition);
rewriter.replaceOpWithNewOp<mlir::LLVM::CondBrOp>(
brOp, i1Condition.getResult(), brOp.getDestTrue(),
adaptor.getDestOperandsTrue(), brOp.getDestFalse(),
adaptor.getDestOperandsFalse());
return mlir::success();
}
};
class CIRCastOpLowering : public mlir::OpConversionPattern<mlir::cir::CastOp> {
public:
using mlir::OpConversionPattern<mlir::cir::CastOp>::OpConversionPattern;
mlir::LogicalResult
matchAndRewrite(mlir::cir::CastOp castOp, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
auto src = adaptor.getSrc();
switch (castOp.getKind()) {
case mlir::cir::CastKind::array_to_ptrdecay: {
auto sourceValue = adaptor.getOperands().front();
auto targetType =
getTypeConverter()->convertType(castOp->getResult(0).getType());
auto offset = llvm::SmallVector<mlir::LLVM::GEPArg>{0};
rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(castOp, targetType,
sourceValue, offset);
break;
}
case mlir::cir::CastKind::int_to_bool: {
auto zero = rewriter.create<mlir::cir::ConstantOp>(
src.getLoc(), castOp.getSrc().getType(),
mlir::cir::IntAttr::get(castOp.getSrc().getType(), 0));
rewriter.replaceOpWithNewOp<mlir::cir::CmpOp>(
castOp, mlir::cir::BoolType::get(getContext()),
mlir::cir::CmpOpKind::ne, castOp.getSrc(), zero);
break;
}
case mlir::cir::CastKind::integral: {
auto dstType = castOp.getResult().getType().cast<mlir::cir::IntType>();
auto srcType = castOp.getSrc().getType().dyn_cast<mlir::cir::IntType>();
auto llvmSrcVal = adaptor.getOperands().front();
auto llvmDstTy =
getTypeConverter()->convertType(dstType).cast<mlir::IntegerType>();
// Target integer is smaller: truncate source value.
if (dstType.getWidth() < srcType.getWidth()) {
rewriter.replaceOpWithNewOp<mlir::LLVM::TruncOp>(castOp, llvmDstTy,
llvmSrcVal);
}
// Target integer is larger: sign extend or zero extend.
else if (dstType.getWidth() > srcType.getWidth()) {
if (srcType.isUnsigned())
rewriter.replaceOpWithNewOp<mlir::LLVM::ZExtOp>(castOp, llvmDstTy,
llvmSrcVal);
else
rewriter.replaceOpWithNewOp<mlir::LLVM::SExtOp>(castOp, llvmDstTy,
llvmSrcVal);
} else { // Target integer is of the same size: do nothing.
rewriter.replaceOp(castOp, llvmSrcVal);
}
break;
}
case mlir::cir::CastKind::floating: {
auto dstTy = castOp.getResult().getType().cast<mlir::FloatType>();
auto srcTy = castOp.getSrc().getType();
auto llvmSrcVal = adaptor.getOperands().front();
if (auto fpSrcTy = srcTy.dyn_cast<mlir::FloatType>()) {
if (fpSrcTy.getWidth() > dstTy.getWidth())
rewriter.replaceOpWithNewOp<mlir::LLVM::FPTruncOp>(castOp, dstTy,
llvmSrcVal);
else
rewriter.replaceOpWithNewOp<mlir::LLVM::FPExtOp>(castOp, dstTy,
llvmSrcVal);
return mlir::success();
}
return castOp.emitError() << "NYI cast from " << srcTy << " to " << dstTy;
}
case mlir::cir::CastKind::int_to_ptr: {
auto dstTy = castOp.getType().cast<mlir::cir::PointerType>();
auto llvmSrcVal = adaptor.getOperands().front();
auto llvmDstTy = getTypeConverter()->convertType(dstTy);
rewriter.replaceOpWithNewOp<mlir::LLVM::IntToPtrOp>(castOp, llvmDstTy,
llvmSrcVal);
return mlir::success();
}
case mlir::cir::CastKind::ptr_to_int: {
auto dstTy = castOp.getType().cast<mlir::cir::IntType>();
auto llvmSrcVal = adaptor.getOperands().front();
auto llvmDstTy = getTypeConverter()->convertType(dstTy);
rewriter.replaceOpWithNewOp<mlir::LLVM::PtrToIntOp>(castOp, llvmDstTy,
llvmSrcVal);
return mlir::success();
}
case mlir::cir::CastKind::float_to_bool: {
auto dstTy = castOp.getType().cast<mlir::cir::BoolType>();
auto llvmSrcVal = adaptor.getOperands().front();
auto llvmDstTy = getTypeConverter()->convertType(dstTy);
auto kind = mlir::LLVM::FCmpPredicate::une;
// Check if float is not equal to zero.
auto zeroFloat = rewriter.create<mlir::LLVM::ConstantOp>(
castOp.getLoc(), llvmSrcVal.getType(),
mlir::FloatAttr::get(llvmSrcVal.getType(), 0.0));
// Extend comparison result to either bool (C++) or int (C).
mlir::Value cmpResult = rewriter.create<mlir::LLVM::FCmpOp>(
castOp.getLoc(), kind, llvmSrcVal, zeroFloat);
rewriter.replaceOpWithNewOp<mlir::LLVM::ZExtOp>(castOp, llvmDstTy,
cmpResult);
return mlir::success();
}
case mlir::cir::CastKind::bool_to_int: {
auto dstTy = castOp.getType().cast<mlir::cir::IntType>();
auto llvmSrcVal = adaptor.getOperands().front();
auto llvmDstTy = getTypeConverter()->convertType(dstTy);
rewriter.replaceOpWithNewOp<mlir::LLVM::ZExtOp>(castOp, llvmDstTy,
llvmSrcVal);
return mlir::success();
}
case mlir::cir::CastKind::int_to_float: {
auto dstTy = castOp.getType();
auto llvmSrcVal = adaptor.getOperands().front();
auto llvmDstTy = getTypeConverter()->convertType(dstTy);
if (castOp.getSrc().getType().cast<mlir::cir::IntType>().isSigned())
rewriter.replaceOpWithNewOp<mlir::LLVM::SIToFPOp>(castOp, llvmDstTy,
llvmSrcVal);
else
rewriter.replaceOpWithNewOp<mlir::LLVM::UIToFPOp>(castOp, llvmDstTy,
llvmSrcVal);
return mlir::success();
}
case mlir::cir::CastKind::float_to_int: {
auto dstTy = castOp.getType();
auto llvmSrcVal = adaptor.getOperands().front();
auto llvmDstTy = getTypeConverter()->convertType(dstTy);
if (castOp.getResult().getType().cast<mlir::cir::IntType>().isSigned())
rewriter.replaceOpWithNewOp<mlir::LLVM::FPToSIOp>(castOp, llvmDstTy,
llvmSrcVal);
else
rewriter.replaceOpWithNewOp<mlir::LLVM::FPToUIOp>(castOp, llvmDstTy,
llvmSrcVal);
return mlir::success();
}
case mlir::cir::CastKind::bitcast: {
auto dstTy = castOp.getType();
auto llvmSrcVal = adaptor.getOperands().front();
auto llvmDstTy = getTypeConverter()->convertType(dstTy);
rewriter.replaceOpWithNewOp<mlir::LLVM::BitcastOp>(castOp, llvmDstTy,
llvmSrcVal);
return mlir::success();
}
case mlir::cir::CastKind::ptr_to_bool: {
auto null = rewriter.create<mlir::cir::ConstantOp>(
src.getLoc(), castOp.getSrc().getType(),
mlir::cir::NullAttr::get(castOp.getSrc().getType()));
rewriter.replaceOpWithNewOp<mlir::cir::CmpOp>(
castOp, mlir::cir::BoolType::get(getContext()),
mlir::cir::CmpOpKind::ne, castOp.getSrc(), null);
break;
}
default:
llvm_unreachable("NYI");
}
return mlir::success();
}
};
class CIRIfLowering : public mlir::OpConversionPattern<mlir::cir::IfOp> {
public:
using mlir::OpConversionPattern<mlir::cir::IfOp>::OpConversionPattern;
mlir::LogicalResult
matchAndRewrite(mlir::cir::IfOp ifOp, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
mlir::OpBuilder::InsertionGuard guard(rewriter);
auto loc = ifOp.getLoc();
auto emptyElse = ifOp.getElseRegion().empty();
auto *currentBlock = rewriter.getInsertionBlock();
auto *remainingOpsBlock =
rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
mlir::Block *continueBlock;
if (ifOp->getResults().size() == 0)
continueBlock = remainingOpsBlock;
else
llvm_unreachable("NYI");
// Inline then region
auto *thenBeforeBody = &ifOp.getThenRegion().front();
auto *thenAfterBody = &ifOp.getThenRegion().back();
rewriter.inlineRegionBefore(ifOp.getThenRegion(), continueBlock);
rewriter.setInsertionPointToEnd(thenAfterBody);
if (auto thenYieldOp =
dyn_cast<mlir::cir::YieldOp>(thenAfterBody->getTerminator())) {
rewriter.replaceOpWithNewOp<mlir::cir::BrOp>(
thenYieldOp, thenYieldOp.getArgs(), continueBlock);
} else if (!dyn_cast<mlir::cir::ReturnOp>(thenAfterBody->getTerminator())) {
llvm_unreachable("what are we terminating with?");
}
rewriter.setInsertionPointToEnd(continueBlock);
// Has else region: inline it.
mlir::Block *elseBeforeBody = nullptr;
mlir::Block *elseAfterBody = nullptr;
if (!emptyElse) {
elseBeforeBody = &ifOp.getElseRegion().front();
elseAfterBody = &ifOp.getElseRegion().back();
rewriter.inlineRegionBefore(ifOp.getElseRegion(), thenAfterBody);
} else {
elseBeforeBody = elseAfterBody = continueBlock;
}
rewriter.setInsertionPointToEnd(currentBlock);
auto trunc = rewriter.create<mlir::LLVM::TruncOp>(loc, rewriter.getI1Type(),
adaptor.getCondition());
rewriter.create<mlir::LLVM::CondBrOp>(loc, trunc.getRes(), thenBeforeBody,
elseBeforeBody);
if (!emptyElse) {
rewriter.setInsertionPointToEnd(elseAfterBody);
if (auto elseYieldOp =
dyn_cast<mlir::cir::YieldOp>(elseAfterBody->getTerminator())) {
rewriter.replaceOpWithNewOp<mlir::cir::BrOp>(
elseYieldOp, elseYieldOp.getArgs(), continueBlock);
} else if (!dyn_cast<mlir::cir::ReturnOp>(
elseAfterBody->getTerminator())) {
llvm_unreachable("what are we terminating with?");
}
}
rewriter.replaceOp(ifOp, continueBlock->getArguments());
return mlir::success();
}
};
class CIRScopeOpLowering
: public mlir::OpConversionPattern<mlir::cir::ScopeOp> {
public:
using OpConversionPattern<mlir::cir::ScopeOp>::OpConversionPattern;
mlir::LogicalResult
matchAndRewrite(mlir::cir::ScopeOp scopeOp, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
mlir::OpBuilder::InsertionGuard guard(rewriter);
auto loc = scopeOp.getLoc();
// Empty scope: just remove it.
if (scopeOp.getRegion().empty()) {
rewriter.eraseOp(scopeOp);
return mlir::success();
}
// Split the current block before the ScopeOp to create the inlining point.
auto *currentBlock = rewriter.getInsertionBlock();
auto *remainingOpsBlock =
rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
mlir::Block *continueBlock;
if (scopeOp.getNumResults() == 0)
continueBlock = remainingOpsBlock;
else
llvm_unreachable("NYI");
// Inline body region.
auto *beforeBody = &scopeOp.getRegion().front();
auto *afterBody = &scopeOp.getRegion().back();
rewriter.inlineRegionBefore(scopeOp.getRegion(), continueBlock);
// Save stack and then branch into the body of the region.
rewriter.setInsertionPointToEnd(currentBlock);
// TODO(CIR): stackSaveOp
// auto stackSaveOp = rewriter.create<mlir::LLVM::StackSaveOp>(
// loc, mlir::LLVM::LLVMPointerType::get(
// mlir::IntegerType::get(scopeOp.getContext(), 8)));
rewriter.create<mlir::cir::BrOp>(loc, mlir::ValueRange(), beforeBody);
// Replace the scopeop return with a branch that jumps out of the body.
// Stack restore before leaving the body region.
rewriter.setInsertionPointToEnd(afterBody);
auto yieldOp = cast<mlir::cir::YieldOp>(afterBody->getTerminator());
auto branchOp = rewriter.replaceOpWithNewOp<mlir::cir::BrOp>(
yieldOp, yieldOp.getArgs(), continueBlock);
// // Insert stack restore before jumping out of the body of the region.
rewriter.setInsertionPoint(branchOp);
// TODO(CIR): stackrestore?
// rewriter.create<mlir::LLVM::StackRestoreOp>(loc, stackSaveOp);
// Replace the op with values return from the body region.
rewriter.replaceOp(scopeOp, continueBlock->getArguments());
return mlir::success();
}
};
class CIRReturnLowering
: public mlir::OpConversionPattern<mlir::cir::ReturnOp> {
public:
using OpConversionPattern<mlir::cir::ReturnOp>::OpConversionPattern;
mlir::LogicalResult
matchAndRewrite(mlir::cir::ReturnOp op, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
rewriter.replaceOpWithNewOp<mlir::func::ReturnOp>(op,
adaptor.getOperands());
return mlir::LogicalResult::success();
}
};
struct ConvertCIRToLLVMPass
: public mlir::PassWrapper<ConvertCIRToLLVMPass,
mlir::OperationPass<mlir::ModuleOp>> {
void getDependentDialects(mlir::DialectRegistry ®istry) const override {
registry.insert<mlir::BuiltinDialect, mlir::DLTIDialect,
mlir::LLVM::LLVMDialect, mlir::func::FuncDialect>();
}
void runOnOperation() final;
virtual StringRef getArgument() const override { return "cir-to-llvm"; }
};
class CIRCallLowering : public mlir::OpConversionPattern<mlir::cir::CallOp> {
public:
using OpConversionPattern<mlir::cir::CallOp>::OpConversionPattern;
mlir::LogicalResult
matchAndRewrite(mlir::cir::CallOp op, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
llvm::SmallVector<mlir::Type, 8> llvmResults;
auto cirResults = op.getResultTypes();
if (getTypeConverter()->convertTypes(cirResults, llvmResults).failed())
return mlir::failure();
rewriter.replaceOpWithNewOp<mlir::LLVM::CallOp>(
op, llvmResults, op.getCalleeAttr(), adaptor.getOperands());
return mlir::success();
}
};
class CIRAllocaLowering
: public mlir::OpConversionPattern<mlir::cir::AllocaOp> {
public:
using OpConversionPattern<mlir::cir::AllocaOp>::OpConversionPattern;
mlir::LogicalResult
matchAndRewrite(mlir::cir::AllocaOp op, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
auto type = op.getAllocaType();
auto llvmType = getTypeConverter()->convertType(type);
mlir::Value one = rewriter.create<mlir::LLVM::ConstantOp>(
op.getLoc(), typeConverter->convertType(rewriter.getIndexType()),
rewriter.getIntegerAttr(rewriter.getIndexType(), 1));
rewriter.replaceOpWithNewOp<mlir::LLVM::AllocaOp>(
op, mlir::LLVM::LLVMPointerType::get(llvmType), one,
op.getAlignmentAttr().getInt());
return mlir::LogicalResult::success();
}
};
class CIRLoadLowering : public mlir::OpConversionPattern<mlir::cir::LoadOp> {
public:
using OpConversionPattern<mlir::cir::LoadOp>::OpConversionPattern;
mlir::LogicalResult
matchAndRewrite(mlir::cir::LoadOp op, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
rewriter.replaceOpWithNewOp<mlir::LLVM::LoadOp>(op, adaptor.getAddr());
return mlir::LogicalResult::success();
}
};
class CIRStoreLowering : public mlir::OpConversionPattern<mlir::cir::StoreOp> {
public:
using OpConversionPattern<mlir::cir::StoreOp>::OpConversionPattern;
mlir::LogicalResult
matchAndRewrite(mlir::cir::StoreOp op, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
rewriter.replaceOpWithNewOp<mlir::LLVM::StoreOp>(op, adaptor.getValue(),
adaptor.getAddr());
return mlir::LogicalResult::success();
}
};
mlir::DenseElementsAttr
convertStringAttrToDenseElementsAttr(mlir::cir::ConstArrayAttr attr,
mlir::Type type) {
auto values = llvm::SmallVector<mlir::APInt, 8>{};
auto stringAttr = attr.getElts().dyn_cast<mlir::StringAttr>();
assert(stringAttr && "expected string attribute here");
for (auto element : stringAttr)
values.push_back({8, (uint64_t)element});
return mlir::DenseElementsAttr::get(
mlir::RankedTensorType::get({(int64_t)values.size()}, type),
llvm::ArrayRef(values));
}
template <typename AttrTy, typename StorageTy>
mlir::DenseElementsAttr
convertToDenseElementsAttr(mlir::cir::ConstArrayAttr attr, mlir::Type type) {
auto values = llvm::SmallVector<StorageTy, 8>{};
auto arrayAttr = attr.getElts().dyn_cast<mlir::ArrayAttr>();
assert(arrayAttr && "expected array here");
for (auto element : arrayAttr)
values.push_back(element.cast<AttrTy>().getValue());
return mlir::DenseElementsAttr::get(
mlir::RankedTensorType::get({(int64_t)values.size()}, type),
llvm::ArrayRef(values));
}
std::optional<mlir::Attribute>
lowerConstArrayAttr(mlir::cir::ConstArrayAttr constArr,
mlir::TypeConverter *converter) {
// Ensure ConstArrayAttr has a type.
auto typedConstArr = constArr.dyn_cast<mlir::TypedAttr>();
assert(typedConstArr && "cir::ConstArrayAttr is not a mlir::TypedAttr");
// Ensure ConstArrayAttr type is a ArrayType.
auto cirArrayType = typedConstArr.getType().dyn_cast<mlir::cir::ArrayType>();
assert(cirArrayType && "cir::ConstArrayAttr is not a cir::ArrayType");
// Is a ConstArrayAttr with an cir::ArrayType: fetch element type.
auto type = cirArrayType.getEltType();
// Convert array attr to LLVM compatible dense elements attr.
if (constArr.getElts().isa<mlir::StringAttr>())
return convertStringAttrToDenseElementsAttr(constArr,
converter->convertType(type));
if (type.isa<mlir::cir::IntType>())
return convertToDenseElementsAttr<mlir::cir::IntAttr, mlir::APInt>(
constArr, converter->convertType(type));
if (type.isa<mlir::FloatType>())
return convertToDenseElementsAttr<mlir::FloatAttr, mlir::APFloat>(
constArr, converter->convertType(type));
return std::nullopt;
}
class CIRConstantLowering
: public mlir::OpConversionPattern<mlir::cir::ConstantOp> {
public:
using OpConversionPattern<mlir::cir::ConstantOp>::OpConversionPattern;
mlir::LogicalResult
matchAndRewrite(mlir::cir::ConstantOp op, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
mlir::Attribute attr = op.getValue();
if (op.getType().isa<mlir::cir::BoolType>()) {
if (op.getValue() ==
mlir::cir::BoolAttr::get(
getContext(), ::mlir::cir::BoolType::get(getContext()), true))
attr = mlir::BoolAttr::get(getContext(), true);
else
attr = mlir::BoolAttr::get(getContext(), false);
} else if (op.getType().isa<mlir::cir::IntType>()) {
attr = rewriter.getIntegerAttr(
typeConverter->convertType(op.getType()),
op.getValue().cast<mlir::cir::IntAttr>().getValue());
} else if (op.getType().isa<mlir::FloatType>()) {
attr = op.getValue();
} else if (op.getType().isa<mlir::cir::PointerType>()) {
// Optimize with dedicated LLVM op for null pointers.
if (op.getValue().isa<mlir::cir::NullAttr>()) {
rewriter.replaceOpWithNewOp<mlir::LLVM::NullOp>(
op, typeConverter->convertType(op.getType()));
return mlir::success();
}
attr = op.getValue();
}
// TODO(cir): constant arrays are currently just pushed into the stack using
// the store instruction, instead of being stored as global variables and
// then memcopyied into the stack (as done in Clang).
else if (auto arrTy = op.getType().dyn_cast<mlir::cir::ArrayType>()) {
// Fetch operation constant array initializer.
auto constArr = op.getValue().dyn_cast<mlir::cir::ConstArrayAttr>();
if (!constArr)
return op.emitError() << "array does not have a constant initializer";
// Lower constant array initializer.
auto denseAttr = lowerConstArrayAttr(constArr, typeConverter);
if (!denseAttr.has_value()) {
op.emitError()
<< "unsupported lowering for #cir.const_array with element type "
<< arrTy.getEltType();
return mlir::failure();
}
attr = denseAttr.value();
} else
return op.emitError() << "unsupported constant type " << op.getType();
rewriter.replaceOpWithNewOp<mlir::LLVM::ConstantOp>(
op, getTypeConverter()->convertType(op.getType()), attr);
return mlir::success();
}
};
class CIRVAStartLowering
: public mlir::OpConversionPattern<mlir::cir::VAStartOp> {
public:
using OpConversionPattern<mlir::cir::VAStartOp>::OpConversionPattern;
mlir::LogicalResult
matchAndRewrite(mlir::cir::VAStartOp op, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
auto i8PtrTy = mlir::LLVM::LLVMPointerType::get(rewriter.getI8Type());
auto vaList = rewriter.create<mlir::LLVM::BitcastOp>(
op.getLoc(), i8PtrTy, adaptor.getOperands().front());
rewriter.replaceOpWithNewOp<mlir::LLVM::VaStartOp>(op, vaList);
return mlir::success();
}
};
class CIRVAEndLowering : public mlir::OpConversionPattern<mlir::cir::VAEndOp> {
public:
using OpConversionPattern<mlir::cir::VAEndOp>::OpConversionPattern;
mlir::LogicalResult
matchAndRewrite(mlir::cir::VAEndOp op, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
auto i8PtrTy = mlir::LLVM::LLVMPointerType::get(rewriter.getI8Type());
auto vaList = rewriter.create<mlir::LLVM::BitcastOp>(
op.getLoc(), i8PtrTy, adaptor.getOperands().front());
rewriter.replaceOpWithNewOp<mlir::LLVM::VaEndOp>(op, vaList);
return mlir::success();
}
};
class CIRVACopyLowering
: public mlir::OpConversionPattern<mlir::cir::VACopyOp> {
public:
using OpConversionPattern<mlir::cir::VACopyOp>::OpConversionPattern;
mlir::LogicalResult
matchAndRewrite(mlir::cir::VACopyOp op, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
auto i8PtrTy = mlir::LLVM::LLVMPointerType::get(rewriter.getI8Type());
auto dstList = rewriter.create<mlir::LLVM::BitcastOp>(
op.getLoc(), i8PtrTy, adaptor.getOperands().front());
auto srcList = rewriter.create<mlir::LLVM::BitcastOp>(
op.getLoc(), i8PtrTy, adaptor.getOperands().back());
rewriter.replaceOpWithNewOp<mlir::LLVM::VaCopyOp>(op, dstList, srcList);
return mlir::success();
}
};
class CIRVAArgLowering : public mlir::OpConversionPattern<mlir::cir::VAArgOp> {
public:
using OpConversionPattern<mlir::cir::VAArgOp>::OpConversionPattern;
mlir::LogicalResult
matchAndRewrite(mlir::cir::VAArgOp op, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
return op.emitError("cir.vaarg lowering is NYI");
}
};
class CIRFuncLowering : public mlir::OpConversionPattern<mlir::cir::FuncOp> {
public:
using OpConversionPattern<mlir::cir::FuncOp>::OpConversionPattern;
/// Returns the name used for the linkage attribute. This *must* correspond to
/// the name of the attribute in ODS.
static StringRef getLinkageAttrNameString() { return "linkage"; }
/// Only retain those attributes that are not constructed by
/// `LLVMFuncOp::build`. If `filterArgAttrs` is set, also filter out argument
/// attributes.
void
filterFuncAttributes(mlir::cir::FuncOp func, bool filterArgAndResAttrs,
SmallVectorImpl<mlir::NamedAttribute> &result) const {
for (auto attr : func->getAttrs()) {
if (attr.getName() == mlir::SymbolTable::getSymbolAttrName() ||
attr.getName() == func.getFunctionTypeAttrName() ||
attr.getName() == getLinkageAttrNameString() ||
(filterArgAndResAttrs &&
(attr.getName() == func.getArgAttrsAttrName() ||
attr.getName() == func.getResAttrsAttrName())))
continue;
// `CIRDialectLLVMIRTranslationInterface` requires "cir." prefix for
// dialect specific attributes, rename them.
if (attr.getName() == func.getExtraAttrsAttrName()) {
std::string cirName = "cir." + func.getExtraAttrsAttrName().str();
attr.setName(mlir::StringAttr::get(getContext(), cirName));
}
result.push_back(attr);
}
}
mlir::LogicalResult
matchAndRewrite(mlir::cir::FuncOp op, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
auto fnType = op.getFunctionType();
mlir::TypeConverter::SignatureConversion signatureConversion(
fnType.getNumInputs());
for (const auto &argType : enumerate(fnType.getInputs())) {
auto convertedType = typeConverter->convertType(argType.value());
if (!convertedType)
return mlir::failure();
signatureConversion.addInputs(argType.index(), convertedType);
}
mlir::Type resultType =
getTypeConverter()->convertType(fnType.getReturnType());
// Create the LLVM function operation.
auto llvmFnTy = mlir::LLVM::LLVMFunctionType::get(
resultType ? resultType : mlir::LLVM::LLVMVoidType::get(getContext()),
signatureConversion.getConvertedTypes(),
/*isVarArg=*/fnType.isVarArg());
// LLVMFuncOp expects a single FileLine Location instead of a fused
// location.
auto Loc = op.getLoc();
if (Loc.isa<mlir::FusedLoc>()) {
auto FusedLoc = Loc.cast<mlir::FusedLoc>();
Loc = FusedLoc.getLocations()[0];
}
assert(Loc.isa<mlir::FileLineColLoc>() && "expected single location here");
auto linkage = convertLinkage(op.getLinkage());
SmallVector<mlir::NamedAttribute, 4> attributes;
filterFuncAttributes(op, /*filterArgAndResAttrs=*/false, attributes);
auto fn = rewriter.create<mlir::LLVM::LLVMFuncOp>(
Loc, op.getName(), llvmFnTy, linkage, false, mlir::LLVM::CConv::C,
mlir::SymbolRefAttr(), attributes);
rewriter.inlineRegionBefore(op.getBody(), fn.getBody(), fn.end());
if (failed(rewriter.convertRegionTypes(&fn.getBody(), *typeConverter,
&signatureConversion)))
return mlir::failure();
rewriter.eraseOp(op);
return mlir::LogicalResult::success();
}
};
class CIRGetGlobalOpLowering
: public mlir::OpConversionPattern<mlir::cir::GetGlobalOp> {
public:
using OpConversionPattern<mlir::cir::GetGlobalOp>::OpConversionPattern;
mlir::LogicalResult
matchAndRewrite(mlir::cir::GetGlobalOp op, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
// FIXME(cir): Premature DCE to avoid lowering stuff we're not using. CIRGen
// should mitigate this and not emit the get_global.
if (op->getUses().empty()) {
rewriter.eraseOp(op);
return mlir::success();
}
auto type = getTypeConverter()->convertType(op.getType());
auto symbol = op.getName();
rewriter.replaceOpWithNewOp<mlir::LLVM::AddressOfOp>(op, type, symbol);
return mlir::success();
}
};
class CIRSwitchOpLowering
: public mlir::OpConversionPattern<mlir::cir::SwitchOp> {
public:
using OpConversionPattern<mlir::cir::SwitchOp>::OpConversionPattern;
inline void rewriteYieldOp(mlir::ConversionPatternRewriter &rewriter,
mlir::cir::YieldOp yieldOp,
mlir::Block *destination) const {
rewriter.setInsertionPoint(yieldOp);
rewriter.replaceOpWithNewOp<mlir::cir::BrOp>(yieldOp, yieldOp.getOperands(),
destination);
}
mlir::LogicalResult
matchAndRewrite(mlir::cir::SwitchOp op, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {
// Empty switch statement: just erase it.
if (!op.getCases().has_value() || op.getCases()->empty()) {
rewriter.eraseOp(op);
return mlir::success();
}
// Create exit block.
rewriter.setInsertionPointAfter(op);
auto *exitBlock =
rewriter.splitBlock(rewriter.getBlock(), rewriter.getInsertionPoint());
// Allocate required data structures (disconsider default case in vectors).
llvm::SmallVector<mlir::APInt, 8> caseValues;
llvm::SmallVector<mlir::Block *, 8> caseDestinations;
llvm::SmallVector<mlir::ValueRange, 8> caseOperands;
// Initialize default case as optional.
mlir::Block *defaultDestination = exitBlock;
mlir::ValueRange defaultOperands = exitBlock->getArguments();
// Track fallthrough between cases.
mlir::cir::YieldOp fallthroughYieldOp = nullptr;
// Digest the case statements values and bodies.
for (size_t i = 0; i < op.getCases()->size(); ++i) {
auto ®ion = op.getRegion(i);
auto caseAttr = op.getCases()->getValue()[i].cast<mlir::cir::CaseAttr>();
// Found default case: save destination and operands.
if (caseAttr.getKind().getValue() == mlir::cir::CaseOpKind::Default) {
defaultDestination = ®ion.front();
defaultOperands = region.getArguments();
} else {
// AnyOf cases kind can have multiple values, hence the loop below.
for (auto &value : caseAttr.getValue()) {
caseValues.push_back(value.cast<mlir::cir::IntAttr>().getValue());
caseOperands.push_back(region.getArguments());
caseDestinations.push_back(®ion.front());
}
}
// Previous case is a fallthrough: branch it to this case.
if (fallthroughYieldOp) {
rewriteYieldOp(rewriter, fallthroughYieldOp, ®ion.front());
fallthroughYieldOp = nullptr;
}
// TODO(cir): Handle multi-block case statements.
if (region.getBlocks().size() != 1)
return op->emitError("multi-block case statement is NYI");
// Handle switch-case yields.
auto *terminator = region.front().getTerminator();
if (auto yieldOp = dyn_cast<mlir::cir::YieldOp>(terminator)) {
// TODO(cir): Ensure every yield instead of dealing with optional
// values.
assert(yieldOp.getKind().has_value() && "switch yield has no kind");
switch (yieldOp.getKind().value()) {
// Fallthrough to next case: track it for the next case to handle.
case mlir::cir::YieldOpKind::Fallthrough:
fallthroughYieldOp = yieldOp;
break;
// Break out of switch: branch to exit block.
case mlir::cir::YieldOpKind::Break:
rewriteYieldOp(rewriter, yieldOp, exitBlock);
break;
default:
return op->emitError("invalid yield kind in case statement");
}
}
// Extract region contents before erasing the switch op.
rewriter.inlineRegionBefore(region, exitBlock);
}
// Last case is a fallthrough: branch it to exit.
if (fallthroughYieldOp) {
rewriteYieldOp(rewriter, fallthroughYieldOp, exitBlock);
fallthroughYieldOp = nullptr;
}
// Set switch op to branch to the newly created blocks.
rewriter.setInsertionPoint(op);
rewriter.replaceOpWithNewOp<mlir::LLVM::SwitchOp>(
op, adaptor.getCondition(), defaultDestination, defaultOperands,
caseValues, caseDestinations, caseOperands);
return mlir::success();
}
};
class CIRGlobalOpLowering
: public mlir::OpConversionPattern<mlir::cir::GlobalOp> {
public:
using OpConversionPattern<mlir::cir::GlobalOp>::OpConversionPattern;
mlir::LogicalResult