Debian Codegraph @

clang/lib/CIR/CodeGen/CIRGenStmt.cpp

raw
1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Emit Stmt nodes as CIR code.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "CIRGenBuilder.h"
14 #include "CIRGenFunction.h"
15
16 #include "mlir/IR/Builders.h"
17 #include "mlir/IR/Location.h"
18 #include "mlir/Support/LLVM.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/Stmt.h"
21 #include "clang/AST/StmtOpenACC.h"
22 #include "clang/AST/StmtOpenMP.h"
23 #include "clang/CIR/MissingFeatures.h"
24
25 using namespace clang;
26 using namespace clang::CIRGen;
27 using namespace cir;
28
29 static mlir::LogicalResult emitStmtWithResult(CIRGenFunction &cgf,
30 const Stmt *exprResult,
31 AggValueSlot slot,
32 Address *lastValue) {
33 // We have to special case labels here. They are statements, but when put
34 // at the end of a statement expression, they yield the value of their
35 // subexpression. Handle this by walking through all labels we encounter,
36 // emitting them before we evaluate the subexpr.
37 // Similar issues arise for attributed statements.
38 while (!isa<Expr>(exprResult)) {
39 if (const auto *ls = dyn_cast<LabelStmt>(exprResult)) {
40 if (cgf.emitLabel(*ls->getDecl()).failed())
41 return mlir::failure();
42 exprResult = ls->getSubStmt();
43 } else if (const auto *as = dyn_cast<AttributedStmt>(exprResult)) {
44 // FIXME: Update this if we ever have attributes that affect the
45 // semantics of an expression.
46 exprResult = as->getSubStmt();
47 } else {
48 llvm_unreachable("Unknown value statement");
49 }
50 }
51
52 const Expr *e = cast<Expr>(exprResult);
53 QualType exprTy = e->getType();
54 if (cgf.hasAggregateEvaluationKind(exprTy)) {
55 cgf.emitAggExpr(e, slot);
56 } else {
57 // We can't return an RValue here because there might be cleanups at
58 // the end of the StmtExpr. Because of that, we have to emit the result
59 // here into a temporary alloca.
60 cgf.emitAnyExprToMem(e, *lastValue, Qualifiers(),
61 /*IsInit*/ false);
62 }
63
64 return mlir::success();
65 }
66
67 mlir::LogicalResult CIRGenFunction::emitCompoundStmtWithoutScope(
68 const CompoundStmt &s, Address *lastValue, AggValueSlot slot) {
69 mlir::LogicalResult result = mlir::success();
70 const Stmt *exprResult = s.body_back();
71 assert((!lastValue || (lastValue && exprResult)) &&
72 "If lastValue is not null then the CompoundStmt must have a "
73 "StmtExprResult");
74
75 for (const Stmt *curStmt : s.body()) {
76 const bool saveResult = lastValue && exprResult == curStmt;
77 if (saveResult) {
78 if (emitStmtWithResult(*this, exprResult, slot, lastValue).failed())
79 result = mlir::failure();
80 } else {
81 if (emitStmt(curStmt, /*useCurrentScope=*/false).failed())
82 result = mlir::failure();
83 }
84 }
85 return result;
86 }
87
88 mlir::LogicalResult CIRGenFunction::emitCompoundStmt(const CompoundStmt &s,
89 Address *lastValue,
90 AggValueSlot slot) {
91 // Add local scope to track new declared variables.
92 SymTableScopeTy varScope(symbolTable);
93 mlir::Location scopeLoc = getLoc(s.getSourceRange());
94 mlir::OpBuilder::InsertPoint scopeInsPt;
95 cir::ScopeOp::create(
96 builder, scopeLoc,
97 [&](mlir::OpBuilder &b, mlir::Type &type, mlir::Location loc) {
98 scopeInsPt = b.saveInsertionPoint();
99 });
100 mlir::OpBuilder::InsertionGuard guard(builder);
101 builder.restoreInsertionPoint(scopeInsPt);
102 LexicalScope lexScope(*this, scopeLoc, builder.getInsertionBlock());
103 return emitCompoundStmtWithoutScope(s, lastValue, slot);
104 }
105
106 void CIRGenFunction::emitStopPoint(const Stmt *s) {
107 assert(!cir::MissingFeatures::generateDebugInfo());
108 }
109
110 // Build CIR for a statement. useCurrentScope should be true if no new scopes
111 // need to be created when finding a compound statement.
112 mlir::LogicalResult CIRGenFunction::emitStmt(const Stmt *s,
113 bool useCurrentScope,
114 ArrayRef<const Attr *> attr) {
115 if (mlir::succeeded(emitSimpleStmt(s, useCurrentScope)))
116 return mlir::success();
117
118 switch (s->getStmtClass()) {
119 case Stmt::NoStmtClass:
120 case Stmt::CXXCatchStmtClass:
121 case Stmt::SEHExceptStmtClass:
122 case Stmt::SEHFinallyStmtClass:
123 case Stmt::MSDependentExistsStmtClass:
124 llvm_unreachable("invalid statement class to emit generically");
125 case Stmt::BreakStmtClass:
126 case Stmt::NullStmtClass:
127 case Stmt::CompoundStmtClass:
128 case Stmt::ContinueStmtClass:
129 case Stmt::DeclStmtClass:
130 case Stmt::ReturnStmtClass:
131 llvm_unreachable("should have emitted these statements as simple");
132
133 #define STMT(Type, Base)
134 #define ABSTRACT_STMT(Op)
135 #define EXPR(Type, Base) case Stmt::Type##Class:
136 #include "clang/AST/StmtNodes.inc"
137 {
138 assert(builder.getInsertionBlock() &&
139 "expression emission must have an insertion point");
140
141 emitIgnoredExpr(cast<Expr>(s));
142
143 // Classic codegen has a check here to see if the emitter created a new
144 // block that isn't used (comparing the incoming and outgoing insertion
145 // points) and deletes the outgoing block if it's not used. In CIR, we
146 // will handle that during the cir.canonicalize pass.
147 return mlir::success();
148 }
149 case Stmt::IfStmtClass:
150 return emitIfStmt(cast<IfStmt>(*s));
151 case Stmt::SwitchStmtClass:
152 return emitSwitchStmt(cast<SwitchStmt>(*s));
153 case Stmt::ForStmtClass:
154 return emitForStmt(cast<ForStmt>(*s));
155 case Stmt::WhileStmtClass:
156 return emitWhileStmt(cast<WhileStmt>(*s));
157 case Stmt::DoStmtClass:
158 return emitDoStmt(cast<DoStmt>(*s));
159 case Stmt::CXXTryStmtClass:
160 return emitCXXTryStmt(cast<CXXTryStmt>(*s));
161 case Stmt::CXXForRangeStmtClass:
162 return emitCXXForRangeStmt(cast<CXXForRangeStmt>(*s), attr);
163 case Stmt::CoroutineBodyStmtClass:
164 return emitCoroutineBody(cast<CoroutineBodyStmt>(*s));
165 case Stmt::IndirectGotoStmtClass:
166 return emitIndirectGotoStmt(cast<IndirectGotoStmt>(*s));
167 case Stmt::CoreturnStmtClass:
168 return emitCoreturnStmt(cast<CoreturnStmt>(*s));
169 case Stmt::OpenACCComputeConstructClass:
170 return emitOpenACCComputeConstruct(cast<OpenACCComputeConstruct>(*s));
171 case Stmt::OpenACCLoopConstructClass:
172 return emitOpenACCLoopConstruct(cast<OpenACCLoopConstruct>(*s));
173 case Stmt::OpenACCCombinedConstructClass:
174 return emitOpenACCCombinedConstruct(cast<OpenACCCombinedConstruct>(*s));
175 case Stmt::OpenACCDataConstructClass:
176 return emitOpenACCDataConstruct(cast<OpenACCDataConstruct>(*s));
177 case Stmt::OpenACCEnterDataConstructClass:
178 return emitOpenACCEnterDataConstruct(cast<OpenACCEnterDataConstruct>(*s));
179 case Stmt::OpenACCExitDataConstructClass:
180 return emitOpenACCExitDataConstruct(cast<OpenACCExitDataConstruct>(*s));
181 case Stmt::OpenACCHostDataConstructClass:
182 return emitOpenACCHostDataConstruct(cast<OpenACCHostDataConstruct>(*s));
183 case Stmt::OpenACCWaitConstructClass:
184 return emitOpenACCWaitConstruct(cast<OpenACCWaitConstruct>(*s));
185 case Stmt::OpenACCInitConstructClass:
186 return emitOpenACCInitConstruct(cast<OpenACCInitConstruct>(*s));
187 case Stmt::OpenACCShutdownConstructClass:
188 return emitOpenACCShutdownConstruct(cast<OpenACCShutdownConstruct>(*s));
189 case Stmt::OpenACCSetConstructClass:
190 return emitOpenACCSetConstruct(cast<OpenACCSetConstruct>(*s));
191 case Stmt::OpenACCUpdateConstructClass:
192 return emitOpenACCUpdateConstruct(cast<OpenACCUpdateConstruct>(*s));
193 case Stmt::OpenACCCacheConstructClass:
194 return emitOpenACCCacheConstruct(cast<OpenACCCacheConstruct>(*s));
195 case Stmt::OpenACCAtomicConstructClass:
196 return emitOpenACCAtomicConstruct(cast<OpenACCAtomicConstruct>(*s));
197 case Stmt::GCCAsmStmtClass:
198 case Stmt::MSAsmStmtClass:
199 return emitAsmStmt(cast<AsmStmt>(*s));
200 case Stmt::OMPScopeDirectiveClass:
201 return emitOMPScopeDirective(cast<OMPScopeDirective>(*s));
202 case Stmt::OMPErrorDirectiveClass:
203 return emitOMPErrorDirective(cast<OMPErrorDirective>(*s));
204 case Stmt::OMPParallelDirectiveClass:
205 return emitOMPParallelDirective(cast<OMPParallelDirective>(*s));
206 case Stmt::OMPTaskwaitDirectiveClass:
207 return emitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*s));
208 case Stmt::OMPTaskyieldDirectiveClass:
209 return emitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*s));
210 case Stmt::OMPBarrierDirectiveClass:
211 return emitOMPBarrierDirective(cast<OMPBarrierDirective>(*s));
212 case Stmt::OMPMetaDirectiveClass:
213 return emitOMPMetaDirective(cast<OMPMetaDirective>(*s));
214 case Stmt::OMPCanonicalLoopClass:
215 return emitOMPCanonicalLoop(cast<OMPCanonicalLoop>(*s));
216 case Stmt::OMPSimdDirectiveClass:
217 return emitOMPSimdDirective(cast<OMPSimdDirective>(*s));
218 case Stmt::OMPTileDirectiveClass:
219 return emitOMPTileDirective(cast<OMPTileDirective>(*s));
220 case Stmt::OMPUnrollDirectiveClass:
221 return emitOMPUnrollDirective(cast<OMPUnrollDirective>(*s));
222 case Stmt::OMPFuseDirectiveClass:
223 return emitOMPFuseDirective(cast<OMPFuseDirective>(*s));
224 case Stmt::OMPForDirectiveClass:
225 return emitOMPForDirective(cast<OMPForDirective>(*s));
226 case Stmt::OMPForSimdDirectiveClass:
227 return emitOMPForSimdDirective(cast<OMPForSimdDirective>(*s));
228 case Stmt::OMPSectionsDirectiveClass:
229 return emitOMPSectionsDirective(cast<OMPSectionsDirective>(*s));
230 case Stmt::OMPSectionDirectiveClass:
231 return emitOMPSectionDirective(cast<OMPSectionDirective>(*s));
232 case Stmt::OMPSingleDirectiveClass:
233 return emitOMPSingleDirective(cast<OMPSingleDirective>(*s));
234 case Stmt::OMPMasterDirectiveClass:
235 return emitOMPMasterDirective(cast<OMPMasterDirective>(*s));
236 case Stmt::OMPCriticalDirectiveClass:
237 return emitOMPCriticalDirective(cast<OMPCriticalDirective>(*s));
238 case Stmt::OMPParallelForDirectiveClass:
239 return emitOMPParallelForDirective(cast<OMPParallelForDirective>(*s));
240 case Stmt::OMPParallelForSimdDirectiveClass:
241 return emitOMPParallelForSimdDirective(
242 cast<OMPParallelForSimdDirective>(*s));
243 case Stmt::OMPParallelMasterDirectiveClass:
244 return emitOMPParallelMasterDirective(cast<OMPParallelMasterDirective>(*s));
245 case Stmt::OMPParallelSectionsDirectiveClass:
246 return emitOMPParallelSectionsDirective(
247 cast<OMPParallelSectionsDirective>(*s));
248 case Stmt::OMPTaskDirectiveClass:
249 return emitOMPTaskDirective(cast<OMPTaskDirective>(*s));
250 case Stmt::OMPTaskgroupDirectiveClass:
251 return emitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*s));
252 case Stmt::OMPFlushDirectiveClass:
253 return emitOMPFlushDirective(cast<OMPFlushDirective>(*s));
254 case Stmt::OMPDepobjDirectiveClass:
255 return emitOMPDepobjDirective(cast<OMPDepobjDirective>(*s));
256 case Stmt::OMPScanDirectiveClass:
257 return emitOMPScanDirective(cast<OMPScanDirective>(*s));
258 case Stmt::OMPOrderedDirectiveClass:
259 return emitOMPOrderedDirective(cast<OMPOrderedDirective>(*s));
260 case Stmt::OMPAtomicDirectiveClass:
261 return emitOMPAtomicDirective(cast<OMPAtomicDirective>(*s));
262 case Stmt::OMPTargetDirectiveClass:
263 return emitOMPTargetDirective(cast<OMPTargetDirective>(*s));
264 case Stmt::OMPTeamsDirectiveClass:
265 return emitOMPTeamsDirective(cast<OMPTeamsDirective>(*s));
266 case Stmt::OMPCancellationPointDirectiveClass:
267 return emitOMPCancellationPointDirective(
268 cast<OMPCancellationPointDirective>(*s));
269 case Stmt::OMPCancelDirectiveClass:
270 return emitOMPCancelDirective(cast<OMPCancelDirective>(*s));
271 case Stmt::OMPTargetDataDirectiveClass:
272 return emitOMPTargetDataDirective(cast<OMPTargetDataDirective>(*s));
273 case Stmt::OMPTargetEnterDataDirectiveClass:
274 return emitOMPTargetEnterDataDirective(
275 cast<OMPTargetEnterDataDirective>(*s));
276 case Stmt::OMPTargetExitDataDirectiveClass:
277 return emitOMPTargetExitDataDirective(cast<OMPTargetExitDataDirective>(*s));
278 case Stmt::OMPTargetParallelDirectiveClass:
279 return emitOMPTargetParallelDirective(cast<OMPTargetParallelDirective>(*s));
280 case Stmt::OMPTargetParallelForDirectiveClass:
281 return emitOMPTargetParallelForDirective(
282 cast<OMPTargetParallelForDirective>(*s));
283 case Stmt::OMPTaskLoopDirectiveClass:
284 return emitOMPTaskLoopDirective(cast<OMPTaskLoopDirective>(*s));
285 case Stmt::OMPTaskLoopSimdDirectiveClass:
286 return emitOMPTaskLoopSimdDirective(cast<OMPTaskLoopSimdDirective>(*s));
287 case Stmt::OMPMaskedTaskLoopDirectiveClass:
288 return emitOMPMaskedTaskLoopDirective(cast<OMPMaskedTaskLoopDirective>(*s));
289 case Stmt::OMPMaskedTaskLoopSimdDirectiveClass:
290 return emitOMPMaskedTaskLoopSimdDirective(
291 cast<OMPMaskedTaskLoopSimdDirective>(*s));
292 case Stmt::OMPMasterTaskLoopDirectiveClass:
293 return emitOMPMasterTaskLoopDirective(cast<OMPMasterTaskLoopDirective>(*s));
294 case Stmt::OMPMasterTaskLoopSimdDirectiveClass:
295 return emitOMPMasterTaskLoopSimdDirective(
296 cast<OMPMasterTaskLoopSimdDirective>(*s));
297 case Stmt::OMPParallelGenericLoopDirectiveClass:
298 return emitOMPParallelGenericLoopDirective(
299 cast<OMPParallelGenericLoopDirective>(*s));
300 case Stmt::OMPParallelMaskedDirectiveClass:
301 return emitOMPParallelMaskedDirective(cast<OMPParallelMaskedDirective>(*s));
302 case Stmt::OMPParallelMaskedTaskLoopDirectiveClass:
303 return emitOMPParallelMaskedTaskLoopDirective(
304 cast<OMPParallelMaskedTaskLoopDirective>(*s));
305 case Stmt::OMPParallelMaskedTaskLoopSimdDirectiveClass:
306 return emitOMPParallelMaskedTaskLoopSimdDirective(
307 cast<OMPParallelMaskedTaskLoopSimdDirective>(*s));
308 case Stmt::OMPParallelMasterTaskLoopDirectiveClass:
309 return emitOMPParallelMasterTaskLoopDirective(
310 cast<OMPParallelMasterTaskLoopDirective>(*s));
311 case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass:
312 return emitOMPParallelMasterTaskLoopSimdDirective(
313 cast<OMPParallelMasterTaskLoopSimdDirective>(*s));
314 case Stmt::OMPDistributeDirectiveClass:
315 return emitOMPDistributeDirective(cast<OMPDistributeDirective>(*s));
316 case Stmt::OMPDistributeParallelForDirectiveClass:
317 return emitOMPDistributeParallelForDirective(
318 cast<OMPDistributeParallelForDirective>(*s));
319 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
320 return emitOMPDistributeParallelForSimdDirective(
321 cast<OMPDistributeParallelForSimdDirective>(*s));
322 case Stmt::OMPDistributeSimdDirectiveClass:
323 return emitOMPDistributeSimdDirective(cast<OMPDistributeSimdDirective>(*s));
324 case Stmt::OMPTargetParallelGenericLoopDirectiveClass:
325 return emitOMPTargetParallelGenericLoopDirective(
326 cast<OMPTargetParallelGenericLoopDirective>(*s));
327 case Stmt::OMPTargetParallelForSimdDirectiveClass:
328 return emitOMPTargetParallelForSimdDirective(
329 cast<OMPTargetParallelForSimdDirective>(*s));
330 case Stmt::OMPTargetSimdDirectiveClass:
331 return emitOMPTargetSimdDirective(cast<OMPTargetSimdDirective>(*s));
332 case Stmt::OMPTargetTeamsGenericLoopDirectiveClass:
333 return emitOMPTargetTeamsGenericLoopDirective(
334 cast<OMPTargetTeamsGenericLoopDirective>(*s));
335 case Stmt::OMPTargetUpdateDirectiveClass:
336 return emitOMPTargetUpdateDirective(cast<OMPTargetUpdateDirective>(*s));
337 case Stmt::OMPTeamsDistributeDirectiveClass:
338 return emitOMPTeamsDistributeDirective(
339 cast<OMPTeamsDistributeDirective>(*s));
340 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
341 return emitOMPTeamsDistributeSimdDirective(
342 cast<OMPTeamsDistributeSimdDirective>(*s));
343 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
344 return emitOMPTeamsDistributeParallelForSimdDirective(
345 cast<OMPTeamsDistributeParallelForSimdDirective>(*s));
346 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
347 return emitOMPTeamsDistributeParallelForDirective(
348 cast<OMPTeamsDistributeParallelForDirective>(*s));
349 case Stmt::OMPTeamsGenericLoopDirectiveClass:
350 return emitOMPTeamsGenericLoopDirective(
351 cast<OMPTeamsGenericLoopDirective>(*s));
352 case Stmt::OMPTargetTeamsDirectiveClass:
353 return emitOMPTargetTeamsDirective(cast<OMPTargetTeamsDirective>(*s));
354 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
355 return emitOMPTargetTeamsDistributeDirective(
356 cast<OMPTargetTeamsDistributeDirective>(*s));
357 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
358 return emitOMPTargetTeamsDistributeParallelForDirective(
359 cast<OMPTargetTeamsDistributeParallelForDirective>(*s));
360 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
361 return emitOMPTargetTeamsDistributeParallelForSimdDirective(
362 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(*s));
363 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
364 return emitOMPTargetTeamsDistributeSimdDirective(
365 cast<OMPTargetTeamsDistributeSimdDirective>(*s));
366 case Stmt::OMPInteropDirectiveClass:
367 return emitOMPInteropDirective(cast<OMPInteropDirective>(*s));
368 case Stmt::OMPDispatchDirectiveClass:
369 return emitOMPDispatchDirective(cast<OMPDispatchDirective>(*s));
370 case Stmt::OMPGenericLoopDirectiveClass:
371 return emitOMPGenericLoopDirective(cast<OMPGenericLoopDirective>(*s));
372 case Stmt::OMPReverseDirectiveClass:
373 return emitOMPReverseDirective(cast<OMPReverseDirective>(*s));
374 case Stmt::OMPInterchangeDirectiveClass:
375 return emitOMPInterchangeDirective(cast<OMPInterchangeDirective>(*s));
376 case Stmt::OMPAssumeDirectiveClass:
377 return emitOMPAssumeDirective(cast<OMPAssumeDirective>(*s));
378 case Stmt::OMPMaskedDirectiveClass:
379 return emitOMPMaskedDirective(cast<OMPMaskedDirective>(*s));
380 case Stmt::OMPStripeDirectiveClass:
381 return emitOMPStripeDirective(cast<OMPStripeDirective>(*s));
382 case Stmt::LabelStmtClass:
383 case Stmt::AttributedStmtClass:
384 case Stmt::GotoStmtClass:
385 case Stmt::DefaultStmtClass:
386 case Stmt::CaseStmtClass:
387 case Stmt::SEHLeaveStmtClass:
388 case Stmt::SYCLKernelCallStmtClass:
389 case Stmt::CapturedStmtClass:
390 case Stmt::ObjCAtTryStmtClass:
391 case Stmt::ObjCAtThrowStmtClass:
392 case Stmt::ObjCAtSynchronizedStmtClass:
393 case Stmt::ObjCForCollectionStmtClass:
394 case Stmt::ObjCAutoreleasePoolStmtClass:
395 case Stmt::SEHTryStmtClass:
396 case Stmt::ObjCAtCatchStmtClass:
397 case Stmt::ObjCAtFinallyStmtClass:
398 case Stmt::DeferStmtClass:
399 cgm.errorNYI(s->getSourceRange(),
400 std::string("emitStmt: ") + s->getStmtClassName());
401 return mlir::failure();
402 }
403
404 llvm_unreachable("Unexpected statement class");
405 }
406
407 mlir::LogicalResult CIRGenFunction::emitSimpleStmt(const Stmt *s,
408 bool useCurrentScope) {
409 switch (s->getStmtClass()) {
410 default:
411 return mlir::failure();
412 case Stmt::DeclStmtClass:
413 return emitDeclStmt(cast<DeclStmt>(*s));
414 case Stmt::CompoundStmtClass:
415 if (useCurrentScope)
416 return emitCompoundStmtWithoutScope(cast<CompoundStmt>(*s));
417 return emitCompoundStmt(cast<CompoundStmt>(*s));
418 case Stmt::GotoStmtClass:
419 return emitGotoStmt(cast<GotoStmt>(*s));
420 case Stmt::ContinueStmtClass:
421 return emitContinueStmt(cast<ContinueStmt>(*s));
422
423 // NullStmt doesn't need any handling, but we need to say we handled it.
424 case Stmt::NullStmtClass:
425 break;
426
427 case Stmt::LabelStmtClass:
428 return emitLabelStmt(cast<LabelStmt>(*s));
429 case Stmt::CaseStmtClass:
430 case Stmt::DefaultStmtClass:
431 // If we reached here, we must not handling a switch case in the top level.
432 return emitSwitchCase(cast<SwitchCase>(*s),
433 /*buildingTopLevelCase=*/false);
434 break;
435
436 case Stmt::BreakStmtClass:
437 return emitBreakStmt(cast<BreakStmt>(*s));
438 case Stmt::ReturnStmtClass:
439 return emitReturnStmt(cast<ReturnStmt>(*s));
440 }
441
442 return mlir::success();
443 }
444
445 mlir::LogicalResult CIRGenFunction::emitLabelStmt(const clang::LabelStmt &s) {
446
447 if (emitLabel(*s.getDecl()).failed())
448 return mlir::failure();
449
450 if (getContext().getLangOpts().EHAsynch && s.isSideEntry())
451 getCIRGenModule().errorNYI(s.getSourceRange(), "IsEHa: not implemented.");
452
453 return emitStmt(s.getSubStmt(), /*useCurrentScope*/ true);
454 }
455
456 // Add a terminating yield on a body region if no other terminators are used.
457 static void terminateBody(CIRGenBuilderTy &builder, mlir::Region &r,
458 mlir::Location loc) {
459 if (r.empty())
460 return;
461
462 SmallVector<mlir::Block *, 4> eraseBlocks;
463 unsigned numBlocks = r.getBlocks().size();
464 for (auto &block : r.getBlocks()) {
465 // Already cleanup after return operations, which might create
466 // empty blocks if emitted as last stmt.
467 if (numBlocks != 1 && block.empty() && block.hasNoPredecessors() &&
468 block.hasNoSuccessors())
469 eraseBlocks.push_back(&block);
470
471 if (block.empty() ||
472 !block.back().hasTrait<mlir::OpTrait::IsTerminator>()) {
473 mlir::OpBuilder::InsertionGuard guardCase(builder);
474 builder.setInsertionPointToEnd(&block);
475 builder.createYield(loc);
476 }
477 }
478
479 for (auto *b : eraseBlocks)
480 b->erase();
481 }
482
483 mlir::LogicalResult CIRGenFunction::emitIfStmt(const IfStmt &s) {
484 mlir::LogicalResult res = mlir::success();
485 // The else branch of a consteval if statement is always the only branch
486 // that can be runtime evaluated.
487 const Stmt *constevalExecuted;
488 if (s.isConsteval()) {
489 constevalExecuted = s.isNegatedConsteval() ? s.getThen() : s.getElse();
490 if (!constevalExecuted) {
491 // No runtime code execution required
492 return res;
493 }
494 }
495
496 // C99 6.8.4.1: The first substatement is executed if the expression
497 // compares unequal to 0. The condition must be a scalar type.
498 auto ifStmtBuilder = [&]() -> mlir::LogicalResult {
499 if (s.isConsteval())
500 return emitStmt(constevalExecuted, /*useCurrentScope=*/true);
501
502 if (s.getInit())
503 if (emitStmt(s.getInit(), /*useCurrentScope=*/true).failed())
504 return mlir::failure();
505
506 if (s.getConditionVariable())
507 emitDecl(*s.getConditionVariable());
508
509 // If the condition folds to a constant and this is an 'if constexpr',
510 // we simplify it early in CIRGen to avoid emitting the full 'if'.
511 bool condConstant;
512 if (constantFoldsToBool(s.getCond(), condConstant, s.isConstexpr())) {
513 if (s.isConstexpr()) {
514 // Handle "if constexpr" explicitly here to avoid generating some
515 // ill-formed code since in CIR the "if" is no longer simplified
516 // in this lambda like in Clang but postponed to other MLIR
517 // passes.
518 if (const Stmt *executed = condConstant ? s.getThen() : s.getElse())
519 return emitStmt(executed, /*useCurrentScope=*/true);
520 // There is nothing to execute at runtime.
521 // TODO(cir): there is still an empty cir.scope generated by the caller.
522 return mlir::success();
523 }
524 }
525
526 assert(!cir::MissingFeatures::emitCondLikelihoodViaExpectIntrinsic());
527 assert(!cir::MissingFeatures::incrementProfileCounter());
528 return emitIfOnBoolExpr(s.getCond(), s.getThen(), s.getElse());
529 };
530
531 // TODO: Add a new scoped symbol table.
532 // LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
533 // The if scope contains the full source range for IfStmt.
534 mlir::Location scopeLoc = getLoc(s.getSourceRange());
535 cir::ScopeOp::create(builder, scopeLoc, /*scopeBuilder=*/
536 [&](mlir::OpBuilder &b, mlir::Location loc) {
537 LexicalScope lexScope{*this, scopeLoc,
538 builder.getInsertionBlock()};
539 res = ifStmtBuilder();
540 });
541
542 return res;
543 }
544
545 mlir::LogicalResult CIRGenFunction::emitDeclStmt(const DeclStmt &s) {
546 assert(builder.getInsertionBlock() && "expected valid insertion point");
547
548 for (const Decl *i : s.decls())
549 emitDecl(*i, /*evaluateConditionDecl=*/true);
550
551 return mlir::success();
552 }
553
554 mlir::LogicalResult CIRGenFunction::emitReturnStmt(const ReturnStmt &s) {
555 mlir::Location loc = getLoc(s.getSourceRange());
556 const Expr *rv = s.getRetValue();
557
558 RunCleanupsScope cleanupScope(*this);
559 bool createNewScope = false;
560 if (const auto *ewc = dyn_cast_or_null<ExprWithCleanups>(rv)) {
561 rv = ewc->getSubExpr();
562 createNewScope = true;
563 }
564
565 auto handleReturnVal = [&]() {
566 if (getContext().getLangOpts().ElideConstructors && s.getNRVOCandidate() &&
567 s.getNRVOCandidate()->isNRVOVariable()) {
568 assert(!cir::MissingFeatures::openMP());
569 // Apply the named return value optimization for this return statement,
570 // which means doing nothing: the appropriate result has already been
571 // constructed into the NRVO variable.
572
573 // If there is an NRVO flag for this variable, set it to 1 into indicate
574 // that the cleanup code should not destroy the variable.
575 if (auto nrvoFlag = nrvoFlags[s.getNRVOCandidate()])
576 builder.createFlagStore(loc, true, nrvoFlag);
577 } else if (!rv) {
578 // No return expression. Do nothing.
579 } else if (rv->getType()->isVoidType()) {
580 // Make sure not to return anything, but evaluate the expression
581 // for side effects.
582 if (rv) {
583 emitAnyExpr(rv);
584 }
585 } else if (cast<FunctionDecl>(curGD.getDecl())
586 ->getReturnType()
587 ->isReferenceType()) {
588 // If this function returns a reference, take the address of the
589 // expression rather than the value.
590 RValue result = emitReferenceBindingToExpr(rv);
591 builder.CIRBaseBuilderTy::createStore(loc, result.getValue(),
592 *fnRetAlloca);
593 } else {
594 mlir::Value value = nullptr;
595 switch (CIRGenFunction::getEvaluationKind(rv->getType())) {
596 case cir::TEK_Scalar:
597 value = emitScalarExpr(rv);
598 if (value) { // Change this to an assert once emitScalarExpr is complete
599 builder.CIRBaseBuilderTy::createStore(loc, value, *fnRetAlloca);
600 }
601 break;
602 case cir::TEK_Complex:
603 emitComplexExprIntoLValue(rv,
604 makeAddrLValue(returnValue, rv->getType()),
605 /*isInit=*/true);
606 break;
607 case cir::TEK_Aggregate:
608 assert(!cir::MissingFeatures::aggValueSlotGC());
609 emitAggExpr(rv, AggValueSlot::forAddr(returnValue, Qualifiers(),
610 AggValueSlot::IsDestructed,
611 AggValueSlot::IsNotAliased,
612 getOverlapForReturnValue()));
613 break;
614 }
615 }
616 };
617
618 if (!createNewScope) {
619 handleReturnVal();
620 } else {
621 mlir::Location scopeLoc =
622 getLoc(rv ? rv->getSourceRange() : s.getSourceRange());
623 // First create cir.scope and later emit it's body. Otherwise all CIRGen
624 // dispatched by `handleReturnVal()` might needs to manipulate blocks and
625 // look into parents, which are all unlinked.
626 mlir::OpBuilder::InsertPoint scopeBody;
627 cir::ScopeOp::create(builder, scopeLoc, /*scopeBuilder=*/
628 [&](mlir::OpBuilder &b, mlir::Location loc) {
629 scopeBody = b.saveInsertionPoint();
630 });
631 {
632 mlir::OpBuilder::InsertionGuard guard(builder);
633 builder.restoreInsertionPoint(scopeBody);
634 CIRGenFunction::LexicalScope lexScope{*this, scopeLoc,
635 builder.getInsertionBlock()};
636 handleReturnVal();
637 }
638 }
639
640 cleanupScope.forceCleanup();
641
642 // In CIR we might have returns in different scopes.
643 // FIXME(cir): cleanup code is handling actual return emission, the logic
644 // should try to match traditional codegen more closely (to the extent which
645 // is possible).
646 auto *retBlock = curLexScope->getOrCreateRetBlock(*this, loc);
647 emitBranchThroughCleanup(loc, returnBlock(retBlock));
648
649 // Insert the new block to continue codegen after branch to ret block.
650 builder.createBlock(builder.getBlock()->getParent());
651
652 return mlir::success();
653 }
654
655 mlir::LogicalResult CIRGenFunction::emitGotoStmt(const clang::GotoStmt &s) {
656 // FIXME: LLVM codegen inserts emit a stop point here for debug info
657 // sake when the insertion point is available, but doesn't do
658 // anything special when there isn't. We haven't implemented debug
659 // info support just yet, look at this again once we have it.
660 assert(!cir::MissingFeatures::generateDebugInfo());
661
662 cir::GotoOp::create(builder, getLoc(s.getSourceRange()),
663 s.getLabel()->getName());
664
665 // A goto marks the end of a block, create a new one for codegen after
666 // emitGotoStmt can resume building in that block.
667 // Insert the new block to continue codegen after goto.
668 builder.createBlock(builder.getBlock()->getParent());
669
670 return mlir::success();
671 }
672
673 mlir::LogicalResult
674 CIRGenFunction::emitIndirectGotoStmt(const IndirectGotoStmt &s) {
675 mlir::Value val = emitScalarExpr(s.getTarget());
676 assert(indirectGotoBlock &&
677 "If you jumping to a indirect branch should be alareadye emitted");
678 cir::BrOp::create(builder, getLoc(s.getSourceRange()), indirectGotoBlock,
679 val);
680 builder.createBlock(builder.getBlock()->getParent());
681 return mlir::success();
682 }
683
684 mlir::LogicalResult
685 CIRGenFunction::emitContinueStmt(const clang::ContinueStmt &s) {
686 builder.createContinue(getLoc(s.getKwLoc()));
687
688 // Insert the new block to continue codegen after the continue statement.
689 builder.createBlock(builder.getBlock()->getParent());
690
691 return mlir::success();
692 }
693
694 mlir::LogicalResult CIRGenFunction::emitLabel(const clang::LabelDecl &d) {
695 // Create a new block to tag with a label and add a branch from
696 // the current one to it. If the block is empty just call attach it
697 // to this label.
698 mlir::Block *currBlock = builder.getBlock();
699 mlir::Block *labelBlock = currBlock;
700
701 if (!currBlock->empty() || currBlock->isEntryBlock()) {
702 {
703 mlir::OpBuilder::InsertionGuard guard(builder);
704 labelBlock = builder.createBlock(builder.getBlock()->getParent());
705 }
706 cir::BrOp::create(builder, getLoc(d.getSourceRange()), labelBlock);
707 }
708
709 builder.setInsertionPointToEnd(labelBlock);
710 cir::LabelOp label =
711 cir::LabelOp::create(builder, getLoc(d.getSourceRange()), d.getName());
712 builder.setInsertionPointToEnd(labelBlock);
713 auto func = cast<cir::FuncOp>(curFn);
714 cgm.mapBlockAddress(cir::BlockAddrInfoAttr::get(builder.getContext(),
715 func.getSymNameAttr(),
716 label.getLabelAttr()),
717 label);
718 // FIXME: emit debug info for labels, incrementProfileCounter
719 assert(!cir::MissingFeatures::ehstackBranches());
720 assert(!cir::MissingFeatures::incrementProfileCounter());
721 assert(!cir::MissingFeatures::generateDebugInfo());
722 return mlir::success();
723 }
724
725 mlir::LogicalResult CIRGenFunction::emitBreakStmt(const clang::BreakStmt &s) {
726 builder.createBreak(getLoc(s.getKwLoc()));
727
728 // Insert the new block to continue codegen after the break statement.
729 builder.createBlock(builder.getBlock()->getParent());
730
731 return mlir::success();
732 }
733
734 template <typename T>
735 mlir::LogicalResult
736 CIRGenFunction::emitCaseDefaultCascade(const T *stmt, mlir::Type condType,
737 mlir::ArrayAttr value, CaseOpKind kind,
738 bool buildingTopLevelCase) {
739
740 assert((isa<CaseStmt, DefaultStmt>(stmt)) &&
741 "only case or default stmt go here");
742
743 mlir::LogicalResult result = mlir::success();
744
745 mlir::Location loc = getLoc(stmt->getBeginLoc());
746
747 enum class SubStmtKind { Case, Default, Other };
748 SubStmtKind subStmtKind = SubStmtKind::Other;
749 const Stmt *sub = stmt->getSubStmt();
750
751 mlir::OpBuilder::InsertPoint insertPoint;
752 CaseOp::create(builder, loc, value, kind, insertPoint);
753
754 {
755 mlir::OpBuilder::InsertionGuard guardSwitch(builder);
756 builder.restoreInsertionPoint(insertPoint);
757
758 if (isa<DefaultStmt>(sub) && isa<CaseStmt>(stmt)) {
759 subStmtKind = SubStmtKind::Default;
760 builder.createYield(loc);
761 } else if (isa<CaseStmt>(sub) && isa<DefaultStmt, CaseStmt>(stmt)) {
762 subStmtKind = SubStmtKind::Case;
763 builder.createYield(loc);
764 } else {
765 result = emitStmt(sub, /*useCurrentScope=*/!isa<CompoundStmt>(sub));
766 }
767
768 insertPoint = builder.saveInsertionPoint();
769 }
770
771 // If the substmt is default stmt or case stmt, try to handle the special case
772 // to make it into the simple form. e.g.
773 //
774 // swtich () {
775 // case 1:
776 // default:
777 // ...
778 // }
779 //
780 // we prefer generating
781 //
782 // cir.switch() {
783 // cir.case(equal, 1) {
784 // cir.yield
785 // }
786 // cir.case(default) {
787 // ...
788 // }
789 // }
790 //
791 // than
792 //
793 // cir.switch() {
794 // cir.case(equal, 1) {
795 // cir.case(default) {
796 // ...
797 // }
798 // }
799 // }
800 //
801 // We don't need to revert this if we find the current switch can't be in
802 // simple form later since the conversion itself should be harmless.
803 if (subStmtKind == SubStmtKind::Case) {
804 result = emitCaseStmt(*cast<CaseStmt>(sub), condType, buildingTopLevelCase);
805 } else if (subStmtKind == SubStmtKind::Default) {
806 result = emitDefaultStmt(*cast<DefaultStmt>(sub), condType,
807 buildingTopLevelCase);
808 } else if (buildingTopLevelCase) {
809 // If we're building a top level case, try to restore the insert point to
810 // the case we're building, then we can attach more random stmts to the
811 // case to make generating `cir.switch` operation to be a simple form.
812 builder.restoreInsertionPoint(insertPoint);
813 }
814
815 return result;
816 }
817
818 mlir::LogicalResult CIRGenFunction::emitCaseStmt(const CaseStmt &s,
819 mlir::Type condType,
820 bool buildingTopLevelCase) {
821 cir::CaseOpKind kind;
822 mlir::ArrayAttr value;
823 llvm::APSInt intVal = s.getLHS()->EvaluateKnownConstInt(getContext());
824
825 // If the case statement has an RHS value, it is representing a GNU
826 // case range statement, where LHS is the beginning of the range
827 // and RHS is the end of the range.
828 if (const Expr *rhs = s.getRHS()) {
829 llvm::APSInt endVal = rhs->EvaluateKnownConstInt(getContext());
830 value = builder.getArrayAttr({cir::IntAttr::get(condType, intVal),
831 cir::IntAttr::get(condType, endVal)});
832 kind = cir::CaseOpKind::Range;
833 } else {
834 value = builder.getArrayAttr({cir::IntAttr::get(condType, intVal)});
835 kind = cir::CaseOpKind::Equal;
836 }
837
838 return emitCaseDefaultCascade(&s, condType, value, kind,
839 buildingTopLevelCase);
840 }
841
842 mlir::LogicalResult CIRGenFunction::emitDefaultStmt(const clang::DefaultStmt &s,
843 mlir::Type condType,
844 bool buildingTopLevelCase) {
845 return emitCaseDefaultCascade(&s, condType, builder.getArrayAttr({}),
846 cir::CaseOpKind::Default, buildingTopLevelCase);
847 }
848
849 mlir::LogicalResult CIRGenFunction::emitSwitchCase(const SwitchCase &s,
850 bool buildingTopLevelCase) {
851 assert(!condTypeStack.empty() &&
852 "build switch case without specifying the type of the condition");
853
854 if (s.getStmtClass() == Stmt::CaseStmtClass)
855 return emitCaseStmt(cast<CaseStmt>(s), condTypeStack.back(),
856 buildingTopLevelCase);
857
858 if (s.getStmtClass() == Stmt::DefaultStmtClass)
859 return emitDefaultStmt(cast<DefaultStmt>(s), condTypeStack.back(),
860 buildingTopLevelCase);
861
862 llvm_unreachable("expect case or default stmt");
863 }
864
865 mlir::LogicalResult
866 CIRGenFunction::emitCXXForRangeStmt(const CXXForRangeStmt &s,
867 ArrayRef<const Attr *> forAttrs) {
868 cir::ForOp forOp;
869
870 // TODO(cir): pass in array of attributes.
871 auto forStmtBuilder = [&]() -> mlir::LogicalResult {
872 mlir::LogicalResult loopRes = mlir::success();
873 // Evaluate the first pieces before the loop.
874 if (s.getInit())
875 if (emitStmt(s.getInit(), /*useCurrentScope=*/true).failed())
876 return mlir::failure();
877 if (emitStmt(s.getRangeStmt(), /*useCurrentScope=*/true).failed())
878 return mlir::failure();
879 if (emitStmt(s.getBeginStmt(), /*useCurrentScope=*/true).failed())
880 return mlir::failure();
881 if (emitStmt(s.getEndStmt(), /*useCurrentScope=*/true).failed())
882 return mlir::failure();
883
884 assert(!cir::MissingFeatures::loopInfoStack());
885 // From LLVM: if there are any cleanups between here and the loop-exit
886 // scope, create a block to stage a loop exit along.
887 // We probably already do the right thing because of ScopeOp, but make
888 // sure we handle all cases.
889 assert(!cir::MissingFeatures::requiresCleanups());
890
891 forOp = builder.createFor(
892 getLoc(s.getSourceRange()),
893 /*condBuilder=*/
894 [&](mlir::OpBuilder &b, mlir::Location loc) {
895 assert(!cir::MissingFeatures::createProfileWeightsForLoop());
896 assert(!cir::MissingFeatures::emitCondLikelihoodViaExpectIntrinsic());
897 mlir::Value condVal = evaluateExprAsBool(s.getCond());
898 builder.createCondition(condVal);
899 },
900 /*bodyBuilder=*/
901 [&](mlir::OpBuilder &b, mlir::Location loc) {
902 // https://en.cppreference.com/w/cpp/language/for
903 // In C++ the scope of the init-statement and the scope of
904 // statement are one and the same.
905 bool useCurrentScope = true;
906 if (emitStmt(s.getLoopVarStmt(), useCurrentScope).failed())
907 loopRes = mlir::failure();
908 if (emitStmt(s.getBody(), useCurrentScope).failed())
909 loopRes = mlir::failure();
910 emitStopPoint(&s);
911 },
912 /*stepBuilder=*/
913 [&](mlir::OpBuilder &b, mlir::Location loc) {
914 if (s.getInc())
915 if (emitStmt(s.getInc(), /*useCurrentScope=*/true).failed())
916 loopRes = mlir::failure();
917 builder.createYield(loc);
918 });
919 return loopRes;
920 };
921
922 mlir::LogicalResult res = mlir::success();
923 mlir::Location scopeLoc = getLoc(s.getSourceRange());
924 cir::ScopeOp::create(builder, scopeLoc, /*scopeBuilder=*/
925 [&](mlir::OpBuilder &b, mlir::Location loc) {
926 // Create a cleanup scope for the condition
927 // variable cleanups. Logical equivalent from
928 // LLVM codegn for LexicalScope
929 // ConditionScope(*this, S.getSourceRange())...
930 LexicalScope lexScope{*this, loc,
931 builder.getInsertionBlock()};
932 res = forStmtBuilder();
933 });
934
935 if (res.failed())
936 return res;
937
938 terminateBody(builder, forOp.getBody(), getLoc(s.getEndLoc()));
939 return mlir::success();
940 }
941
942 mlir::LogicalResult CIRGenFunction::emitForStmt(const ForStmt &s) {
943 cir::ForOp forOp;
944
945 // TODO: pass in an array of attributes.
946 auto forStmtBuilder = [&]() -> mlir::LogicalResult {
947 mlir::LogicalResult loopRes = mlir::success();
948 // Evaluate the first part before the loop.
949 if (s.getInit())
950 if (emitStmt(s.getInit(), /*useCurrentScope=*/true).failed())
951 return mlir::failure();
952 assert(!cir::MissingFeatures::loopInfoStack());
953 // In the classic codegen, if there are any cleanups between here and the
954 // loop-exit scope, a block is created to stage the loop exit. We probably
955 // already do the right thing because of ScopeOp, but we need more testing
956 // to be sure we handle all cases.
957 assert(!cir::MissingFeatures::requiresCleanups());
958
959 forOp = builder.createFor(
960 getLoc(s.getSourceRange()),
961 /*condBuilder=*/
962 [&](mlir::OpBuilder &b, mlir::Location loc) {
963 assert(!cir::MissingFeatures::createProfileWeightsForLoop());
964 assert(!cir::MissingFeatures::emitCondLikelihoodViaExpectIntrinsic());
965 mlir::Value condVal;
966 if (s.getCond()) {
967 // If the for statement has a condition scope,
968 // emit the local variable declaration.
969 if (s.getConditionVariable())
970 emitDecl(*s.getConditionVariable());
971 // C99 6.8.5p2/p4: The first substatement is executed if the
972 // expression compares unequal to 0. The condition must be a
973 // scalar type.
974 condVal = evaluateExprAsBool(s.getCond());
975 } else {
976 condVal = cir::ConstantOp::create(b, loc, builder.getTrueAttr());
977 }
978 builder.createCondition(condVal);
979 },
980 /*bodyBuilder=*/
981 [&](mlir::OpBuilder &b, mlir::Location loc) {
982 // The scope of the for loop body is nested within the scope of the
983 // for loop's init-statement and condition.
984 if (emitStmt(s.getBody(), /*useCurrentScope=*/false).failed())
985 loopRes = mlir::failure();
986 emitStopPoint(&s);
987 },
988 /*stepBuilder=*/
989 [&](mlir::OpBuilder &b, mlir::Location loc) {
990 if (s.getInc())
991 if (emitStmt(s.getInc(), /*useCurrentScope=*/true).failed())
992 loopRes = mlir::failure();
993 builder.createYield(loc);
994 });
995 return loopRes;
996 };
997
998 auto res = mlir::success();
999 auto scopeLoc = getLoc(s.getSourceRange());
1000 cir::ScopeOp::create(builder, scopeLoc, /*scopeBuilder=*/
1001 [&](mlir::OpBuilder &b, mlir::Location loc) {
1002 LexicalScope lexScope{*this, loc,
1003 builder.getInsertionBlock()};
1004 res = forStmtBuilder();
1005 });
1006
1007 if (res.failed())
1008 return res;
1009
1010 terminateBody(builder, forOp.getBody(), getLoc(s.getEndLoc()));
1011 return mlir::success();
1012 }
1013
1014 mlir::LogicalResult CIRGenFunction::emitDoStmt(const DoStmt &s) {
1015 cir::DoWhileOp doWhileOp;
1016
1017 // TODO: pass in array of attributes.
1018 auto doStmtBuilder = [&]() -> mlir::LogicalResult {
1019 mlir::LogicalResult loopRes = mlir::success();
1020 assert(!cir::MissingFeatures::loopInfoStack());
1021 // From LLVM: if there are any cleanups between here and the loop-exit
1022 // scope, create a block to stage a loop exit along.
1023 // We probably already do the right thing because of ScopeOp, but make
1024 // sure we handle all cases.
1025 assert(!cir::MissingFeatures::requiresCleanups());
1026
1027 doWhileOp = builder.createDoWhile(
1028 getLoc(s.getSourceRange()),
1029 /*condBuilder=*/
1030 [&](mlir::OpBuilder &b, mlir::Location loc) {
1031 assert(!cir::MissingFeatures::createProfileWeightsForLoop());
1032 assert(!cir::MissingFeatures::emitCondLikelihoodViaExpectIntrinsic());
1033 // C99 6.8.5p2/p4: The first substatement is executed if the
1034 // expression compares unequal to 0. The condition must be a
1035 // scalar type.
1036 mlir::Value condVal = evaluateExprAsBool(s.getCond());
1037 builder.createCondition(condVal);
1038 },
1039 /*bodyBuilder=*/
1040 [&](mlir::OpBuilder &b, mlir::Location loc) {
1041 // The scope of the do-while loop body is a nested scope.
1042 if (emitStmt(s.getBody(), /*useCurrentScope=*/false).failed())
1043 loopRes = mlir::failure();
1044 emitStopPoint(&s);
1045 });
1046 return loopRes;
1047 };
1048
1049 mlir::LogicalResult res = mlir::success();
1050 mlir::Location scopeLoc = getLoc(s.getSourceRange());
1051 cir::ScopeOp::create(builder, scopeLoc, /*scopeBuilder=*/
1052 [&](mlir::OpBuilder &b, mlir::Location loc) {
1053 LexicalScope lexScope{*this, loc,
1054 builder.getInsertionBlock()};
1055 res = doStmtBuilder();
1056 });
1057
1058 if (res.failed())
1059 return res;
1060
1061 terminateBody(builder, doWhileOp.getBody(), getLoc(s.getEndLoc()));
1062 return mlir::success();
1063 }
1064
1065 mlir::LogicalResult CIRGenFunction::emitWhileStmt(const WhileStmt &s) {
1066 cir::WhileOp whileOp;
1067
1068 // TODO: pass in array of attributes.
1069 auto whileStmtBuilder = [&]() -> mlir::LogicalResult {
1070 mlir::LogicalResult loopRes = mlir::success();
1071 assert(!cir::MissingFeatures::loopInfoStack());
1072 // From LLVM: if there are any cleanups between here and the loop-exit
1073 // scope, create a block to stage a loop exit along.
1074 // We probably already do the right thing because of ScopeOp, but make
1075 // sure we handle all cases.
1076 assert(!cir::MissingFeatures::requiresCleanups());
1077
1078 whileOp = builder.createWhile(
1079 getLoc(s.getSourceRange()),
1080 /*condBuilder=*/
1081 [&](mlir::OpBuilder &b, mlir::Location loc) {
1082 assert(!cir::MissingFeatures::createProfileWeightsForLoop());
1083 assert(!cir::MissingFeatures::emitCondLikelihoodViaExpectIntrinsic());
1084 mlir::Value condVal;
1085 // If the for statement has a condition scope,
1086 // emit the local variable declaration.
1087 if (s.getConditionVariable())
1088 emitDecl(*s.getConditionVariable());
1089 // C99 6.8.5p2/p4: The first substatement is executed if the
1090 // expression compares unequal to 0. The condition must be a
1091 // scalar type.
1092 condVal = evaluateExprAsBool(s.getCond());
1093 builder.createCondition(condVal);
1094 },
1095 /*bodyBuilder=*/
1096 [&](mlir::OpBuilder &b, mlir::Location loc) {
1097 // The scope of the while loop body is a nested scope.
1098 if (emitStmt(s.getBody(), /*useCurrentScope=*/false).failed())
1099 loopRes = mlir::failure();
1100 emitStopPoint(&s);
1101 });
1102 return loopRes;
1103 };
1104
1105 mlir::LogicalResult res = mlir::success();
1106 mlir::Location scopeLoc = getLoc(s.getSourceRange());
1107 cir::ScopeOp::create(builder, scopeLoc, /*scopeBuilder=*/
1108 [&](mlir::OpBuilder &b, mlir::Location loc) {
1109 LexicalScope lexScope{*this, loc,
1110 builder.getInsertionBlock()};
1111 res = whileStmtBuilder();
1112 });
1113
1114 if (res.failed())
1115 return res;
1116
1117 terminateBody(builder, whileOp.getBody(), getLoc(s.getEndLoc()));
1118 return mlir::success();
1119 }
1120
1121 mlir::LogicalResult CIRGenFunction::emitSwitchBody(const Stmt *s) {
1122 // It is rare but legal if the switch body is not a compound stmt. e.g.,
1123 //
1124 // switch(a)
1125 // while(...) {
1126 // case1
1127 // ...
1128 // case2
1129 // ...
1130 // }
1131 if (!isa<CompoundStmt>(s))
1132 return emitStmt(s, /*useCurrentScope=*/true);
1133
1134 auto *compoundStmt = cast<CompoundStmt>(s);
1135
1136 mlir::Block *swtichBlock = builder.getBlock();
1137 for (auto *c : compoundStmt->body()) {
1138 if (auto *switchCase = dyn_cast<SwitchCase>(c)) {
1139 builder.setInsertionPointToEnd(swtichBlock);
1140 // Reset insert point automatically, so that we can attach following
1141 // random stmt to the region of previous built case op to try to make
1142 // the being generated `cir.switch` to be in simple form.
1143 if (mlir::failed(
1144 emitSwitchCase(*switchCase, /*buildingTopLevelCase=*/true)))
1145 return mlir::failure();
1146
1147 continue;
1148 }
1149
1150 // Otherwise, just build the statements in the nearest case region.
1151 if (mlir::failed(emitStmt(c, /*useCurrentScope=*/!isa<CompoundStmt>(c))))
1152 return mlir::failure();
1153 }
1154
1155 return mlir::success();
1156 }
1157
1158 mlir::LogicalResult CIRGenFunction::emitSwitchStmt(const clang::SwitchStmt &s) {
1159 // TODO: LLVM codegen does some early optimization to fold the condition and
1160 // only emit live cases. CIR should use MLIR to achieve similar things,
1161 // nothing to be done here.
1162 // if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue))...
1163 assert(!cir::MissingFeatures::constantFoldSwitchStatement());
1164
1165 SwitchOp swop;
1166 auto switchStmtBuilder = [&]() -> mlir::LogicalResult {
1167 if (s.getInit())
1168 if (emitStmt(s.getInit(), /*useCurrentScope=*/true).failed())
1169 return mlir::failure();
1170
1171 if (s.getConditionVariable())
1172 emitDecl(*s.getConditionVariable(), /*evaluateConditionDecl=*/true);
1173
1174 mlir::Value condV = emitScalarExpr(s.getCond());
1175
1176 // TODO: PGO and likelihood (e.g. PGO.haveRegionCounts())
1177 assert(!cir::MissingFeatures::pgoUse());
1178 assert(!cir::MissingFeatures::emitCondLikelihoodViaExpectIntrinsic());
1179 // TODO: if the switch has a condition wrapped by __builtin_unpredictable?
1180 assert(!cir::MissingFeatures::insertBuiltinUnpredictable());
1181
1182 mlir::LogicalResult res = mlir::success();
1183 swop = SwitchOp::create(
1184 builder, getLoc(s.getBeginLoc()), condV,
1185 /*switchBuilder=*/
1186 [&](mlir::OpBuilder &b, mlir::Location loc, mlir::OperationState &os) {
1187 curLexScope->setAsSwitch();
1188
1189 condTypeStack.push_back(condV.getType());
1190
1191 res = emitSwitchBody(s.getBody());
1192
1193 condTypeStack.pop_back();
1194 });
1195
1196 return res;
1197 };
1198
1199 // The switch scope contains the full source range for SwitchStmt.
1200 mlir::Location scopeLoc = getLoc(s.getSourceRange());
1201 mlir::LogicalResult res = mlir::success();
1202 cir::ScopeOp::create(builder, scopeLoc, /*scopeBuilder=*/
1203 [&](mlir::OpBuilder &b, mlir::Location loc) {
1204 LexicalScope lexScope{*this, loc,
1205 builder.getInsertionBlock()};
1206 res = switchStmtBuilder();
1207 });
1208
1209 llvm::SmallVector<CaseOp> cases;
1210 swop.collectCases(cases);
1211 for (auto caseOp : cases)
1212 terminateBody(builder, caseOp.getCaseRegion(), caseOp.getLoc());
1213 terminateBody(builder, swop.getBody(), swop.getLoc());
1214
1215 swop.setAllEnumCasesCovered(s.isAllEnumCasesCovered());
1216
1217 return res;
1218 }
1219
1220 void CIRGenFunction::emitReturnOfRValue(mlir::Location loc, RValue rv,
1221 QualType ty) {
1222 if (rv.isScalar()) {
1223 builder.createStore(loc, rv.getValue(), returnValue);
1224 } else if (rv.isAggregate()) {
1225 LValue dest = makeAddrLValue(returnValue, ty);
1226 LValue src = makeAddrLValue(rv.getAggregateAddress(), ty);
1227 emitAggregateCopy(dest, src, ty, getOverlapForReturnValue());
1228 } else {
1229 cgm.errorNYI(loc, "emitReturnOfRValue: complex return type");
1230 }
1231 mlir::Block *retBlock = curLexScope->getOrCreateRetBlock(*this, loc);
1232 assert(!cir::MissingFeatures::emitBranchThroughCleanup());
1233 cir::BrOp::create(builder, loc, retBlock);
1234 if (ehStack.stable_begin() != currentCleanupStackDepth)
1235 cgm.errorNYI(loc, "return of r-value with cleanup stack");
1236 }