-
Notifications
You must be signed in to change notification settings - Fork 103
/
CIRGenStmt.cpp
1159 lines (1013 loc) · 42.6 KB
/
CIRGenStmt.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
//===--- CIRGenStmt.cpp - Emit CIR Code from Statements -------------------===//
//
// 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 contains code to emit Stmt nodes as CIR code.
//
//===----------------------------------------------------------------------===//
#include "Address.h"
#include "CIRGenBuilder.h"
#include "CIRGenFunction.h"
#include "mlir/IR/Value.h"
#include "clang/AST/CharUnits.h"
#include "clang/AST/Stmt.h"
#include "clang/CIR/Dialect/IR/CIRDialect.h"
#include "clang/CIR/Dialect/IR/CIRTypes.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang;
using namespace clang::CIRGen;
using namespace cir;
Address CIRGenFunction::emitCompoundStmtWithoutScope(const CompoundStmt &S,
bool getLast,
AggValueSlot slot) {
const Stmt *ExprResult = S.getStmtExprResult();
assert((!getLast || (getLast && ExprResult)) &&
"If getLast is true then the CompoundStmt must have a StmtExprResult");
Address retAlloca = Address::invalid();
for (auto *CurStmt : S.body()) {
if (getLast && ExprResult == CurStmt) {
while (!isa<Expr>(ExprResult)) {
if (const auto *LS = dyn_cast<LabelStmt>(ExprResult))
llvm_unreachable("labels are NYI");
else if (const auto *AS = dyn_cast<AttributedStmt>(ExprResult))
llvm_unreachable("statement attributes are NYI");
else
llvm_unreachable("Unknown value statement");
}
const Expr *E = cast<Expr>(ExprResult);
QualType exprTy = E->getType();
if (hasAggregateEvaluationKind(exprTy)) {
emitAggExpr(E, slot);
} else {
// We can't return an RValue here because there might be cleanups at
// the end of the StmtExpr. Because of that, we have to emit the result
// here into a temporary alloca.
retAlloca = CreateMemTemp(exprTy, getLoc(E->getSourceRange()));
emitAnyExprToMem(E, retAlloca, Qualifiers(),
/*IsInit*/ false);
}
} else {
if (emitStmt(CurStmt, /*useCurrentScope=*/false).failed())
llvm_unreachable("failed to build statement");
}
}
return retAlloca;
}
Address CIRGenFunction::emitCompoundStmt(const CompoundStmt &S, bool getLast,
AggValueSlot slot) {
Address retAlloca = Address::invalid();
// Add local scope to track new declared variables.
SymTableScopeTy varScope(symbolTable);
auto scopeLoc = getLoc(S.getSourceRange());
builder.create<cir::ScopeOp>(
scopeLoc, /*scopeBuilder=*/
[&](mlir::OpBuilder &b, mlir::Type &type, mlir::Location loc) {
LexicalScope lexScope{*this, loc, builder.getInsertionBlock()};
retAlloca = emitCompoundStmtWithoutScope(S, getLast, slot);
});
return retAlloca;
}
void CIRGenFunction::emitStopPoint(const Stmt *S) {
assert(!cir::MissingFeatures::generateDebugInfo());
}
// Build CIR for a statement. useCurrentScope should be true if no
// new scopes need be created when finding a compound statement.
mlir::LogicalResult CIRGenFunction::emitStmt(const Stmt *S,
bool useCurrentScope,
ArrayRef<const Attr *> Attrs) {
if (mlir::succeeded(emitSimpleStmt(S, useCurrentScope)))
return mlir::success();
if (getContext().getLangOpts().OpenMP &&
getContext().getLangOpts().OpenMPSimd)
assert(0 && "not implemented");
switch (S->getStmtClass()) {
case Stmt::OMPScopeDirectiveClass:
llvm_unreachable("NYI");
case Stmt::OpenACCCombinedConstructClass:
case Stmt::OpenACCComputeConstructClass:
case Stmt::OpenACCLoopConstructClass:
case Stmt::OMPErrorDirectiveClass:
case Stmt::NoStmtClass:
case Stmt::CXXCatchStmtClass:
case Stmt::SEHExceptStmtClass:
case Stmt::SEHFinallyStmtClass:
case Stmt::MSDependentExistsStmtClass:
llvm_unreachable("invalid statement class to emit generically");
case Stmt::NullStmtClass:
case Stmt::CompoundStmtClass:
case Stmt::DeclStmtClass:
case Stmt::LabelStmtClass:
case Stmt::AttributedStmtClass:
case Stmt::GotoStmtClass:
case Stmt::BreakStmtClass:
case Stmt::ContinueStmtClass:
case Stmt::DefaultStmtClass:
case Stmt::CaseStmtClass:
case Stmt::SEHLeaveStmtClass:
llvm_unreachable("should have emitted these statements as simple");
#define STMT(Type, Base)
#define ABSTRACT_STMT(Op)
#define EXPR(Type, Base) case Stmt::Type##Class:
#include "clang/AST/StmtNodes.inc"
{
// Remember the block we came in on.
mlir::Block *incoming = builder.getInsertionBlock();
assert(incoming && "expression emission must have an insertion point");
emitIgnoredExpr(cast<Expr>(S));
mlir::Block *outgoing = builder.getInsertionBlock();
assert(outgoing && "expression emission cleared block!");
break;
}
case Stmt::IfStmtClass:
if (emitIfStmt(cast<IfStmt>(*S)).failed())
return mlir::failure();
break;
case Stmt::SwitchStmtClass:
if (emitSwitchStmt(cast<SwitchStmt>(*S)).failed())
return mlir::failure();
break;
case Stmt::ForStmtClass:
if (emitForStmt(cast<ForStmt>(*S)).failed())
return mlir::failure();
break;
case Stmt::WhileStmtClass:
if (emitWhileStmt(cast<WhileStmt>(*S)).failed())
return mlir::failure();
break;
case Stmt::DoStmtClass:
if (emitDoStmt(cast<DoStmt>(*S)).failed())
return mlir::failure();
break;
case Stmt::CoroutineBodyStmtClass:
return emitCoroutineBody(cast<CoroutineBodyStmt>(*S));
case Stmt::CoreturnStmtClass:
return emitCoreturnStmt(cast<CoreturnStmt>(*S));
case Stmt::CXXTryStmtClass:
return emitCXXTryStmt(cast<CXXTryStmt>(*S));
case Stmt::CXXForRangeStmtClass:
return emitCXXForRangeStmt(cast<CXXForRangeStmt>(*S), Attrs);
case Stmt::IndirectGotoStmtClass:
case Stmt::ReturnStmtClass:
// When implemented, GCCAsmStmtClass should fall-through to MSAsmStmtClass.
case Stmt::GCCAsmStmtClass:
case Stmt::MSAsmStmtClass:
return emitAsmStmt(cast<AsmStmt>(*S));
// OMP directives:
case Stmt::OMPParallelDirectiveClass:
return emitOMPParallelDirective(cast<OMPParallelDirective>(*S));
case Stmt::OMPTaskwaitDirectiveClass:
return emitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S));
case Stmt::OMPTaskyieldDirectiveClass:
return emitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S));
case Stmt::OMPBarrierDirectiveClass:
return emitOMPBarrierDirective(cast<OMPBarrierDirective>(*S));
// Unsupported AST nodes:
case Stmt::CapturedStmtClass:
case Stmt::ObjCAtTryStmtClass:
case Stmt::ObjCAtThrowStmtClass:
case Stmt::ObjCAtSynchronizedStmtClass:
case Stmt::ObjCForCollectionStmtClass:
case Stmt::ObjCAutoreleasePoolStmtClass:
case Stmt::SEHTryStmtClass:
case Stmt::OMPMetaDirectiveClass:
case Stmt::OMPCanonicalLoopClass:
case Stmt::OMPSimdDirectiveClass:
case Stmt::OMPTileDirectiveClass:
case Stmt::OMPUnrollDirectiveClass:
case Stmt::OMPForDirectiveClass:
case Stmt::OMPForSimdDirectiveClass:
case Stmt::OMPSectionsDirectiveClass:
case Stmt::OMPSectionDirectiveClass:
case Stmt::OMPSingleDirectiveClass:
case Stmt::OMPMasterDirectiveClass:
case Stmt::OMPCriticalDirectiveClass:
case Stmt::OMPParallelForDirectiveClass:
case Stmt::OMPParallelForSimdDirectiveClass:
case Stmt::OMPParallelMasterDirectiveClass:
case Stmt::OMPParallelSectionsDirectiveClass:
case Stmt::OMPTaskDirectiveClass:
case Stmt::OMPTaskgroupDirectiveClass:
case Stmt::OMPFlushDirectiveClass:
case Stmt::OMPDepobjDirectiveClass:
case Stmt::OMPScanDirectiveClass:
case Stmt::OMPOrderedDirectiveClass:
case Stmt::OMPAtomicDirectiveClass:
case Stmt::OMPTargetDirectiveClass:
case Stmt::OMPTeamsDirectiveClass:
case Stmt::OMPCancellationPointDirectiveClass:
case Stmt::OMPCancelDirectiveClass:
case Stmt::OMPTargetDataDirectiveClass:
case Stmt::OMPTargetEnterDataDirectiveClass:
case Stmt::OMPTargetExitDataDirectiveClass:
case Stmt::OMPTargetParallelDirectiveClass:
case Stmt::OMPTargetParallelForDirectiveClass:
case Stmt::OMPTaskLoopDirectiveClass:
case Stmt::OMPTaskLoopSimdDirectiveClass:
case Stmt::OMPMaskedTaskLoopDirectiveClass:
case Stmt::OMPMaskedTaskLoopSimdDirectiveClass:
case Stmt::OMPMasterTaskLoopDirectiveClass:
case Stmt::OMPMasterTaskLoopSimdDirectiveClass:
case Stmt::OMPParallelGenericLoopDirectiveClass:
case Stmt::OMPParallelMaskedDirectiveClass:
case Stmt::OMPParallelMaskedTaskLoopDirectiveClass:
case Stmt::OMPParallelMaskedTaskLoopSimdDirectiveClass:
case Stmt::OMPParallelMasterTaskLoopDirectiveClass:
case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass:
case Stmt::OMPDistributeDirectiveClass:
case Stmt::OMPDistributeParallelForDirectiveClass:
case Stmt::OMPDistributeParallelForSimdDirectiveClass:
case Stmt::OMPDistributeSimdDirectiveClass:
case Stmt::OMPTargetParallelGenericLoopDirectiveClass:
case Stmt::OMPTargetParallelForSimdDirectiveClass:
case Stmt::OMPTargetSimdDirectiveClass:
case Stmt::OMPTargetTeamsGenericLoopDirectiveClass:
case Stmt::OMPTargetUpdateDirectiveClass:
case Stmt::OMPTeamsDistributeDirectiveClass:
case Stmt::OMPTeamsDistributeSimdDirectiveClass:
case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
case Stmt::OMPTeamsGenericLoopDirectiveClass:
case Stmt::OMPTargetTeamsDirectiveClass:
case Stmt::OMPTargetTeamsDistributeDirectiveClass:
case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
case Stmt::OMPInteropDirectiveClass:
case Stmt::OMPDispatchDirectiveClass:
case Stmt::OMPGenericLoopDirectiveClass:
case Stmt::OMPReverseDirectiveClass:
case Stmt::OMPInterchangeDirectiveClass:
case Stmt::OMPAssumeDirectiveClass:
case Stmt::OMPMaskedDirectiveClass: {
llvm::errs() << "CIR codegen for '" << S->getStmtClassName()
<< "' not implemented\n";
assert(0 && "not implemented");
break;
}
case Stmt::ObjCAtCatchStmtClass:
llvm_unreachable(
"@catch statements should be handled by EmitObjCAtTryStmt");
case Stmt::ObjCAtFinallyStmtClass:
llvm_unreachable(
"@finally statements should be handled by EmitObjCAtTryStmt");
}
return mlir::success();
}
mlir::LogicalResult CIRGenFunction::emitSimpleStmt(const Stmt *S,
bool useCurrentScope) {
switch (S->getStmtClass()) {
default:
return mlir::failure();
case Stmt::DeclStmtClass:
return emitDeclStmt(cast<DeclStmt>(*S));
case Stmt::CompoundStmtClass:
useCurrentScope ? emitCompoundStmtWithoutScope(cast<CompoundStmt>(*S))
: emitCompoundStmt(cast<CompoundStmt>(*S));
break;
case Stmt::ReturnStmtClass:
return emitReturnStmt(cast<ReturnStmt>(*S));
case Stmt::GotoStmtClass:
return emitGotoStmt(cast<GotoStmt>(*S));
case Stmt::ContinueStmtClass:
return emitContinueStmt(cast<ContinueStmt>(*S));
case Stmt::NullStmtClass:
break;
case Stmt::LabelStmtClass:
return emitLabelStmt(cast<LabelStmt>(*S));
case Stmt::CaseStmtClass:
case Stmt::DefaultStmtClass:
// If we reached here, we must not handling a switch case in the top level.
return emitSwitchCase(cast<SwitchCase>(*S),
/*buildingTopLevelCase=*/false);
break;
case Stmt::BreakStmtClass:
return emitBreakStmt(cast<BreakStmt>(*S));
case Stmt::AttributedStmtClass:
return emitAttributedStmt(cast<AttributedStmt>(*S));
case Stmt::SEHLeaveStmtClass:
llvm::errs() << "CIR codegen for '" << S->getStmtClassName()
<< "' not implemented\n";
assert(0 && "not implemented");
}
return mlir::success();
}
mlir::LogicalResult CIRGenFunction::emitLabelStmt(const clang::LabelStmt &S) {
if (emitLabel(S.getDecl()).failed())
return mlir::failure();
// IsEHa: not implemented.
assert(!(getContext().getLangOpts().EHAsynch && S.isSideEntry()));
return emitStmt(S.getSubStmt(), /* useCurrentScope */ true);
}
mlir::LogicalResult
CIRGenFunction::emitAttributedStmt(const AttributedStmt &S) {
for (const auto *A : S.getAttrs()) {
switch (A->getKind()) {
case attr::NoMerge:
case attr::NoInline:
case attr::AlwaysInline:
case attr::MustTail:
llvm_unreachable("NIY attributes");
case attr::CXXAssume: {
const Expr *assumption = cast<CXXAssumeAttr>(A)->getAssumption();
if (getLangOpts().CXXAssumptions && builder.getInsertionBlock() &&
!assumption->HasSideEffects(getContext())) {
mlir::Value assumptionValue = emitCheckedArgForAssume(assumption);
builder.create<cir::AssumeOp>(getLoc(S.getSourceRange()),
assumptionValue);
}
break;
}
default:
break;
}
}
return emitStmt(S.getSubStmt(), true, S.getAttrs());
}
// Add terminating yield on body regions (loops, ...) in case there are
// not other terminators used.
// FIXME: make terminateCaseRegion use this too.
static void terminateBody(CIRGenBuilderTy &builder, mlir::Region &r,
mlir::Location loc) {
if (r.empty())
return;
SmallVector<mlir::Block *, 4> eraseBlocks;
unsigned numBlocks = r.getBlocks().size();
for (auto &block : r.getBlocks()) {
// Already cleanup after return operations, which might create
// empty blocks if emitted as last stmt.
if (numBlocks != 1 && block.empty() && block.hasNoPredecessors() &&
block.hasNoSuccessors())
eraseBlocks.push_back(&block);
if (block.empty() ||
!block.back().hasTrait<mlir::OpTrait::IsTerminator>()) {
mlir::OpBuilder::InsertionGuard guardCase(builder);
builder.setInsertionPointToEnd(&block);
builder.createYield(loc);
}
}
for (auto *b : eraseBlocks)
b->erase();
}
mlir::LogicalResult CIRGenFunction::emitIfStmt(const IfStmt &S) {
mlir::LogicalResult res = mlir::success();
// The else branch of a consteval if statement is always the only branch
// that can be runtime evaluated.
const Stmt *ConstevalExecuted;
if (S.isConsteval()) {
ConstevalExecuted = S.isNegatedConsteval() ? S.getThen() : S.getElse();
if (!ConstevalExecuted)
// No runtime code execution required
return res;
}
// C99 6.8.4.1: The first substatement is executed if the expression
// compares unequal to 0. The condition must be a scalar type.
auto ifStmtBuilder = [&]() -> mlir::LogicalResult {
if (S.isConsteval())
return emitStmt(ConstevalExecuted, /*useCurrentScope=*/true);
if (S.getInit())
if (emitStmt(S.getInit(), /*useCurrentScope=*/true).failed())
return mlir::failure();
if (S.getConditionVariable())
emitDecl(*S.getConditionVariable());
// During LLVM codegen, if the condition constant folds and can be elided,
// it tries to avoid emitting the condition and the dead arm of the if/else.
// TODO(cir): we skip this in CIRGen, but should implement this as part of
// SSCP or a specific CIR pass.
bool CondConstant;
if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant,
S.isConstexpr())) {
if (S.isConstexpr()) {
// Handle "if constexpr" explicitly here to avoid generating some
// ill-formed code since in CIR the "if" is no longer simplified
// in this lambda like in Clang but postponed to other MLIR
// passes.
if (const Stmt *Executed = CondConstant ? S.getThen() : S.getElse())
return emitStmt(Executed, /*useCurrentScope=*/true);
// There is nothing to execute at runtime.
// TODO(cir): there is still an empty cir.scope generated by the caller.
return mlir::success();
}
assert(!cir::MissingFeatures::constantFoldsToSimpleInteger());
}
assert(!cir::MissingFeatures::emitCondLikelihoodViaExpectIntrinsic());
assert(!cir::MissingFeatures::incrementProfileCounter());
return emitIfOnBoolExpr(S.getCond(), S.getThen(), S.getElse());
};
// TODO: Add a new scoped symbol table.
// LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
// The if scope contains the full source range for IfStmt.
auto scopeLoc = getLoc(S.getSourceRange());
builder.create<cir::ScopeOp>(
scopeLoc, /*scopeBuilder=*/
[&](mlir::OpBuilder &b, mlir::Location loc) {
LexicalScope lexScope{*this, scopeLoc, builder.getInsertionBlock()};
res = ifStmtBuilder();
});
return res;
}
mlir::LogicalResult CIRGenFunction::emitDeclStmt(const DeclStmt &S) {
if (!builder.getInsertionBlock()) {
CGM.emitError("Seems like this is unreachable code, what should we do?");
return mlir::failure();
}
for (const auto *I : S.decls()) {
emitDecl(*I);
}
return mlir::success();
}
mlir::LogicalResult CIRGenFunction::emitReturnStmt(const ReturnStmt &S) {
assert(!cir::MissingFeatures::requiresReturnValueCheck());
auto loc = getLoc(S.getSourceRange());
// Emit the result value, even if unused, to evaluate the side effects.
const Expr *RV = S.getRetValue();
// TODO(cir): LLVM codegen uses a RunCleanupsScope cleanupScope here, we
// should model this in face of dtors.
bool createNewScope = false;
if (const auto *EWC = dyn_cast_or_null<ExprWithCleanups>(RV)) {
RV = EWC->getSubExpr();
createNewScope = true;
}
auto handleReturnVal = [&]() {
if (getContext().getLangOpts().ElideConstructors && S.getNRVOCandidate() &&
S.getNRVOCandidate()->isNRVOVariable()) {
assert(!cir::MissingFeatures::openMP());
// Apply the named return value optimization for this return statement,
// which means doing nothing: the appropriate result has already been
// constructed into the NRVO variable.
// If there is an NRVO flag for this variable, set it to 1 into indicate
// that the cleanup code should not destroy the variable.
if (auto NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
getBuilder().createFlagStore(loc, true, NRVOFlag);
} else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) {
// Make sure not to return anything, but evaluate the expression
// for side effects.
if (RV) {
emitAnyExpr(RV);
}
} else if (!RV) {
// Do nothing (return value is left uninitialized)
} else if (FnRetTy->isReferenceType()) {
// If this function returns a reference, take the address of the
// expression rather than the value.
RValue Result = emitReferenceBindingToExpr(RV);
builder.createStore(loc, Result.getScalarVal(), ReturnValue);
} else {
mlir::Value V = nullptr;
switch (CIRGenFunction::getEvaluationKind(RV->getType())) {
case cir::TEK_Scalar:
V = emitScalarExpr(RV);
builder.CIRBaseBuilderTy::createStore(loc, V, *FnRetAlloca);
break;
case cir::TEK_Complex:
emitComplexExprIntoLValue(RV,
makeAddrLValue(ReturnValue, RV->getType()),
/*isInit*/ true);
break;
case cir::TEK_Aggregate:
emitAggExpr(
RV, AggValueSlot::forAddr(
ReturnValue, Qualifiers(), AggValueSlot::IsDestructed,
AggValueSlot::DoesNotNeedGCBarriers,
AggValueSlot::IsNotAliased, getOverlapForReturnValue()));
break;
}
}
};
if (!createNewScope)
handleReturnVal();
else {
mlir::Location scopeLoc =
getLoc(RV ? RV->getSourceRange() : S.getSourceRange());
// First create cir.scope and later emit it's body. Otherwise all CIRGen
// dispatched by `handleReturnVal()` might needs to manipulate blocks and
// look into parents, which are all unlinked.
mlir::OpBuilder::InsertPoint scopeBody;
builder.create<cir::ScopeOp>(scopeLoc, /*scopeBuilder=*/
[&](mlir::OpBuilder &b, mlir::Location loc) {
scopeBody = b.saveInsertionPoint();
});
{
mlir::OpBuilder::InsertionGuard guard(builder);
builder.restoreInsertionPoint(scopeBody);
CIRGenFunction::LexicalScope lexScope{*this, scopeLoc,
builder.getInsertionBlock()};
handleReturnVal();
}
}
// Create a new return block (if not existent) and add a branch to
// it. The actual return instruction is only inserted during current
// scope cleanup handling.
auto *retBlock = currLexScope->getOrCreateRetBlock(*this, loc);
builder.create<BrOp>(loc, retBlock);
// Insert the new block to continue codegen after branch to ret block.
builder.createBlock(builder.getBlock()->getParent());
// TODO(cir): LLVM codegen for a cleanup on cleanupScope here.
return mlir::success();
}
mlir::LogicalResult CIRGenFunction::emitGotoStmt(const GotoStmt &S) {
// FIXME: LLVM codegen inserts emit stop point here for debug info
// sake when the insertion point is available, but doesn't do
// anything special when there isn't. We haven't implemented debug
// info support just yet, look at this again once we have it.
assert(builder.getInsertionBlock() && "not yet implemented");
builder.create<cir::GotoOp>(getLoc(S.getSourceRange()),
S.getLabel()->getName());
// A goto marks the end of a block, create a new one for codegen after
// emitGotoStmt can resume building in that block.
// Insert the new block to continue codegen after goto.
builder.createBlock(builder.getBlock()->getParent());
// What here...
return mlir::success();
}
mlir::LogicalResult CIRGenFunction::emitLabel(const LabelDecl *D) {
// Create a new block to tag with a label and add a branch from
// the current one to it. If the block is empty just call attach it
// to this label.
mlir::Block *currBlock = builder.getBlock();
mlir::Block *labelBlock = currBlock;
if (!currBlock->empty()) {
{
mlir::OpBuilder::InsertionGuard guard(builder);
labelBlock = builder.createBlock(builder.getBlock()->getParent());
}
builder.create<BrOp>(getLoc(D->getSourceRange()), labelBlock);
}
builder.setInsertionPointToEnd(labelBlock);
builder.create<cir::LabelOp>(getLoc(D->getSourceRange()), D->getName());
builder.setInsertionPointToEnd(labelBlock);
// FIXME: emit debug info for labels, incrementProfileCounter
return mlir::success();
}
mlir::LogicalResult
CIRGenFunction::emitContinueStmt(const clang::ContinueStmt &S) {
builder.createContinue(getLoc(S.getContinueLoc()));
// Insert the new block to continue codegen after the continue statement.
builder.createBlock(builder.getBlock()->getParent());
return mlir::success();
}
mlir::LogicalResult CIRGenFunction::emitBreakStmt(const clang::BreakStmt &S) {
builder.createBreak(getLoc(S.getBreakLoc()));
// Insert the new block to continue codegen after the break statement.
builder.createBlock(builder.getBlock()->getParent());
return mlir::success();
}
const CaseStmt *CIRGenFunction::foldCaseStmt(const clang::CaseStmt &S,
mlir::Type condType,
mlir::ArrayAttr &value,
cir::CaseOpKind &kind) {
const CaseStmt *caseStmt = &S;
const CaseStmt *lastCase = &S;
SmallVector<mlir::Attribute, 4> caseEltValueListAttr;
// Fold cascading cases whenever possible to simplify codegen a bit.
while (caseStmt) {
lastCase = caseStmt;
auto intVal = caseStmt->getLHS()->EvaluateKnownConstInt(getContext());
if (auto *rhs = caseStmt->getRHS()) {
auto endVal = rhs->EvaluateKnownConstInt(getContext());
SmallVector<mlir::Attribute, 4> rangeCaseAttr = {
cir::IntAttr::get(condType, intVal),
cir::IntAttr::get(condType, endVal)};
value = builder.getArrayAttr(rangeCaseAttr);
kind = cir::CaseOpKind::Range;
// We may not be able to fold rangaes. Due to we can't present range case
// with other trivial cases now.
return caseStmt;
}
caseEltValueListAttr.push_back(cir::IntAttr::get(condType, intVal));
caseStmt = dyn_cast_or_null<CaseStmt>(caseStmt->getSubStmt());
// Break early if we found ranges. We can't fold ranges due to the same
// reason above.
if (caseStmt && caseStmt->getRHS())
break;
}
if (!caseEltValueListAttr.empty()) {
value = builder.getArrayAttr(caseEltValueListAttr);
kind = caseEltValueListAttr.size() > 1 ? cir::CaseOpKind::Anyof
: cir::CaseOpKind::Equal;
}
return lastCase;
}
template <typename T>
mlir::LogicalResult
CIRGenFunction::emitCaseDefaultCascade(const T *stmt, mlir::Type condType,
mlir::ArrayAttr value, CaseOpKind kind,
bool buildingTopLevelCase) {
assert((isa<CaseStmt, DefaultStmt>(stmt)) &&
"only case or default stmt go here");
mlir::LogicalResult result = mlir::success();
auto loc = getLoc(stmt->getBeginLoc());
enum class SubStmtKind { Case, Default, Other };
SubStmtKind subStmtKind = SubStmtKind::Other;
auto *sub = stmt->getSubStmt();
mlir::OpBuilder::InsertPoint insertPoint;
builder.create<CaseOp>(loc, value, kind, insertPoint);
{
mlir::OpBuilder::InsertionGuard guardSwitch(builder);
builder.restoreInsertionPoint(insertPoint);
if (isa<DefaultStmt>(sub) && isa<CaseStmt>(stmt)) {
subStmtKind = SubStmtKind::Default;
builder.createYield(loc);
} else if (isa<CaseStmt>(sub) && isa<DefaultStmt>(stmt)) {
subStmtKind = SubStmtKind::Case;
builder.createYield(loc);
} else
result = emitStmt(sub, /*useCurrentScope=*/!isa<CompoundStmt>(sub));
insertPoint = builder.saveInsertionPoint();
}
// If the substmt is default stmt or case stmt, try to handle the special case
// to make it into the simple form. e.g.
//
// swtich () {
// case 1:
// default:
// ...
// }
//
// we prefer generating
//
// cir.switch() {
// cir.case(equal, 1) {
// cir.yield
// }
// cir.case(default) {
// ...
// }
// }
//
// than
//
// cir.switch() {
// cir.case(equal, 1) {
// cir.case(default) {
// ...
// }
// }
// }
//
// We don't need to revert this if we find the current switch can't be in
// simple form later since the conversion itself should be harmless.
if (subStmtKind == SubStmtKind::Case)
result = emitCaseStmt(*cast<CaseStmt>(sub), condType, buildingTopLevelCase);
else if (subStmtKind == SubStmtKind::Default)
result = emitDefaultStmt(*cast<DefaultStmt>(sub), condType,
buildingTopLevelCase);
else if (buildingTopLevelCase)
// If we're building a top level case, try to restore the insert point to
// the case we're building, then we can attach more random stmts to the
// case to make generating `cir.switch` operation to be a simple form.
builder.restoreInsertionPoint(insertPoint);
return result;
}
mlir::LogicalResult CIRGenFunction::emitCaseStmt(const CaseStmt &S,
mlir::Type condType,
bool buildingTopLevelCase) {
mlir::ArrayAttr value;
CaseOpKind kind;
auto *caseStmt = foldCaseStmt(S, condType, value, kind);
return emitCaseDefaultCascade(caseStmt, condType, value, kind,
buildingTopLevelCase);
}
mlir::LogicalResult CIRGenFunction::emitDefaultStmt(const DefaultStmt &S,
mlir::Type condType,
bool buildingTopLevelCase) {
return emitCaseDefaultCascade(&S, condType, builder.getArrayAttr({}),
cir::CaseOpKind::Default, buildingTopLevelCase);
}
mlir::LogicalResult CIRGenFunction::emitSwitchCase(const SwitchCase &S,
bool buildingTopLevelCase) {
assert(!condTypeStack.empty() &&
"build switch case without specifying the type of the condition");
if (S.getStmtClass() == Stmt::CaseStmtClass)
return emitCaseStmt(cast<CaseStmt>(S), condTypeStack.back(),
buildingTopLevelCase);
if (S.getStmtClass() == Stmt::DefaultStmtClass)
return emitDefaultStmt(cast<DefaultStmt>(S), condTypeStack.back(),
buildingTopLevelCase);
llvm_unreachable("expect case or default stmt");
}
mlir::LogicalResult
CIRGenFunction::emitCXXForRangeStmt(const CXXForRangeStmt &S,
ArrayRef<const Attr *> ForAttrs) {
cir::ForOp forOp;
// TODO(cir): pass in array of attributes.
auto forStmtBuilder = [&]() -> mlir::LogicalResult {
auto loopRes = mlir::success();
// Evaluate the first pieces before the loop.
if (S.getInit())
if (emitStmt(S.getInit(), /*useCurrentScope=*/true).failed())
return mlir::failure();
if (emitStmt(S.getRangeStmt(), /*useCurrentScope=*/true).failed())
return mlir::failure();
if (emitStmt(S.getBeginStmt(), /*useCurrentScope=*/true).failed())
return mlir::failure();
if (emitStmt(S.getEndStmt(), /*useCurrentScope=*/true).failed())
return mlir::failure();
assert(!cir::MissingFeatures::loopInfoStack());
// From LLVM: if there are any cleanups between here and the loop-exit
// scope, create a block to stage a loop exit along.
// We probably already do the right thing because of ScopeOp, but make
// sure we handle all cases.
assert(!cir::MissingFeatures::requiresCleanups());
forOp = builder.createFor(
getLoc(S.getSourceRange()),
/*condBuilder=*/
[&](mlir::OpBuilder &b, mlir::Location loc) {
assert(!cir::MissingFeatures::createProfileWeightsForLoop());
assert(!cir::MissingFeatures::emitCondLikelihoodViaExpectIntrinsic());
mlir::Value condVal = evaluateExprAsBool(S.getCond());
builder.createCondition(condVal);
},
/*bodyBuilder=*/
[&](mlir::OpBuilder &b, mlir::Location loc) {
// https://en.cppreference.com/w/cpp/language/for
// In C++ the scope of the init-statement and the scope of
// statement are one and the same.
bool useCurrentScope = true;
if (emitStmt(S.getLoopVarStmt(), useCurrentScope).failed())
loopRes = mlir::failure();
if (emitStmt(S.getBody(), useCurrentScope).failed())
loopRes = mlir::failure();
emitStopPoint(&S);
},
/*stepBuilder=*/
[&](mlir::OpBuilder &b, mlir::Location loc) {
if (S.getInc())
if (emitStmt(S.getInc(), /*useCurrentScope=*/true).failed())
loopRes = mlir::failure();
builder.createYield(loc);
});
return loopRes;
};
auto res = mlir::success();
auto scopeLoc = getLoc(S.getSourceRange());
builder.create<cir::ScopeOp>(scopeLoc, /*scopeBuilder=*/
[&](mlir::OpBuilder &b, mlir::Location loc) {
// Create a cleanup scope for the condition
// variable cleanups. Logical equivalent from
// LLVM codegn for LexicalScope
// ConditionScope(*this, S.getSourceRange())...
LexicalScope lexScope{
*this, loc, builder.getInsertionBlock()};
res = forStmtBuilder();
});
if (res.failed())
return res;
terminateBody(builder, forOp.getBody(), getLoc(S.getEndLoc()));
return mlir::success();
}
mlir::LogicalResult CIRGenFunction::emitForStmt(const ForStmt &S) {
cir::ForOp forOp;
// TODO: pass in array of attributes.
auto forStmtBuilder = [&]() -> mlir::LogicalResult {
auto loopRes = mlir::success();
// Evaluate the first part before the loop.
if (S.getInit())
if (emitStmt(S.getInit(), /*useCurrentScope=*/true).failed())
return mlir::failure();
assert(!cir::MissingFeatures::loopInfoStack());
// From LLVM: if there are any cleanups between here and the loop-exit
// scope, create a block to stage a loop exit along.
// We probably already do the right thing because of ScopeOp, but make
// sure we handle all cases.
assert(!cir::MissingFeatures::requiresCleanups());
forOp = builder.createFor(
getLoc(S.getSourceRange()),
/*condBuilder=*/
[&](mlir::OpBuilder &b, mlir::Location loc) {
assert(!cir::MissingFeatures::createProfileWeightsForLoop());
assert(!cir::MissingFeatures::emitCondLikelihoodViaExpectIntrinsic());
mlir::Value condVal;
if (S.getCond()) {
// If the for statement has a condition scope,
// emit the local variable declaration.
if (S.getConditionVariable())
emitDecl(*S.getConditionVariable());
// C99 6.8.5p2/p4: The first substatement is executed if the
// expression compares unequal to 0. The condition must be a
// scalar type.
condVal = evaluateExprAsBool(S.getCond());
} else {
auto boolTy = cir::BoolType::get(b.getContext());
condVal = b.create<cir::ConstantOp>(
loc, boolTy, cir::BoolAttr::get(b.getContext(), boolTy, true));
}
builder.createCondition(condVal);
},
/*bodyBuilder=*/
[&](mlir::OpBuilder &b, mlir::Location loc) {
// https://en.cppreference.com/w/cpp/language/for
// While in C++, the scope of the init-statement and the scope of
// statement are one and the same, in C the scope of statement is
// nested within the scope of init-statement.
bool useCurrentScope =
CGM.getASTContext().getLangOpts().CPlusPlus ? true : false;
if (emitStmt(S.getBody(), useCurrentScope).failed())
loopRes = mlir::failure();
emitStopPoint(&S);
},
/*stepBuilder=*/
[&](mlir::OpBuilder &b, mlir::Location loc) {
if (S.getInc())
if (emitStmt(S.getInc(), /*useCurrentScope=*/true).failed())
loopRes = mlir::failure();
builder.createYield(loc);
});
return loopRes;
};
auto res = mlir::success();
auto scopeLoc = getLoc(S.getSourceRange());
builder.create<cir::ScopeOp>(scopeLoc, /*scopeBuilder=*/
[&](mlir::OpBuilder &b, mlir::Location loc) {
LexicalScope lexScope{
*this, loc, builder.getInsertionBlock()};
res = forStmtBuilder();
});
if (res.failed())
return res;
terminateBody(builder, forOp.getBody(), getLoc(S.getEndLoc()));
return mlir::success();
}
mlir::LogicalResult CIRGenFunction::emitDoStmt(const DoStmt &S) {
cir::DoWhileOp doWhileOp;
// TODO: pass in array of attributes.
auto doStmtBuilder = [&]() -> mlir::LogicalResult {
auto loopRes = mlir::success();
assert(!cir::MissingFeatures::loopInfoStack());
// From LLVM: if there are any cleanups between here and the loop-exit
// scope, create a block to stage a loop exit along.
// We probably already do the right thing because of ScopeOp, but make
// sure we handle all cases.
assert(!cir::MissingFeatures::requiresCleanups());
doWhileOp = builder.createDoWhile(
getLoc(S.getSourceRange()),
/*condBuilder=*/
[&](mlir::OpBuilder &b, mlir::Location loc) {
assert(!cir::MissingFeatures::createProfileWeightsForLoop());
assert(!cir::MissingFeatures::emitCondLikelihoodViaExpectIntrinsic());
// C99 6.8.5p2/p4: The first substatement is executed if the
// expression compares unequal to 0. The condition must be a
// scalar type.
mlir::Value condVal = evaluateExprAsBool(S.getCond());
builder.createCondition(condVal);
},
/*bodyBuilder=*/
[&](mlir::OpBuilder &b, mlir::Location loc) {
if (emitStmt(S.getBody(), /*useCurrentScope=*/true).failed())
loopRes = mlir::failure();
emitStopPoint(&S);
});
return loopRes;
};
auto res = mlir::success();
auto scopeLoc = getLoc(S.getSourceRange());
builder.create<cir::ScopeOp>(scopeLoc, /*scopeBuilder=*/
[&](mlir::OpBuilder &b, mlir::Location loc) {
LexicalScope lexScope{
*this, loc, builder.getInsertionBlock()};
res = doStmtBuilder();
});
if (res.failed())
return res;
terminateBody(builder, doWhileOp.getBody(), getLoc(S.getEndLoc()));
return mlir::success();
}
mlir::LogicalResult CIRGenFunction::emitWhileStmt(const WhileStmt &S) {
cir::WhileOp whileOp;