1//===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
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// This contains code to emit Stmt nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGDebugInfo.h"
14#include "CGOpenMPRuntime.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "CodeGenPGO.h"
18#include "TargetInfo.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Stmt.h"
22#include "clang/AST/StmtSYCL.h"
23#include "clang/AST/StmtVisitor.h"
24#include "clang/Basic/Builtins.h"
25#include "clang/Basic/DiagnosticSema.h"
26#include "clang/Basic/PrettyStackTrace.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/CodeGenUtils/StmtUtils.h"
30#include "llvm/ADT/ArrayRef.h"
31#include "llvm/ADT/DenseMap.h"
32#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/StringExtras.h"
34#include "llvm/IR/Assumptions.h"
35#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/InlineAsm.h"
37#include "llvm/IR/Intrinsics.h"
38#include "llvm/IR/MDBuilder.h"
39#include "llvm/Support/SaveAndRestore.h"
40#include <optional>
41
42using namespace clang;
43using namespace CodeGen;
44
45//===----------------------------------------------------------------------===//
46// Statement Emission
47//===----------------------------------------------------------------------===//
48
49void CodeGenFunction::EmitStopPoint(const Stmt *S) {
50 if (CGDebugInfo *DI = getDebugInfo()) {
51 SourceLocation Loc;
52 Loc = S->getBeginLoc();
53 DI->EmitLocation(Builder, Loc);
54
55 LastStopPoint = Loc;
56 }
57}
58
59void CodeGenFunction::EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs) {
60 assert(S && "Null statement?");
61 PGO->setCurrentStmt(S);
62
63 // These statements have their own debug info handling.
64 if (EmitSimpleStmt(S, Attrs))
65 return;
66
67 // Check if we are generating unreachable code.
68 if (!HaveInsertPoint()) {
69 // If so, and the statement doesn't contain a label, then we do not need to
70 // generate actual code. This is safe because (1) the current point is
71 // unreachable, so we don't need to execute the code, and (2) we've already
72 // handled the statements which update internal data structures (like the
73 // local variable map) which could be used by subsequent statements.
74 if (!ContainsLabel(S)) {
75 // Verify that any decl statements were handled as simple, they may be in
76 // scope of subsequent reachable statements.
77 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
78 PGO->markStmtMaybeUsed(S);
79 return;
80 }
81
82 // Otherwise, make a new block to hold the code.
83 EnsureInsertPoint();
84 }
85
86 // Generate a stoppoint if we are emitting debug info.
87 EmitStopPoint(S);
88
89 // Ignore all OpenMP directives except for simd if OpenMP with Simd is
90 // enabled.
91 if (getLangOpts().OpenMP && getLangOpts().OpenMPSimd) {
92 if (const auto *D = dyn_cast<OMPExecutableDirective>(Val: S)) {
93 EmitSimpleOMPExecutableDirective(D: *D);
94 return;
95 }
96 }
97
98 switch (S->getStmtClass()) {
99 case Stmt::NoStmtClass:
100 case Stmt::CXXCatchStmtClass:
101 case Stmt::SEHExceptStmtClass:
102 case Stmt::SEHFinallyStmtClass:
103 case Stmt::MSDependentExistsStmtClass:
104 case Stmt::UnresolvedSYCLKernelCallStmtClass:
105 llvm_unreachable("invalid statement class to emit generically");
106 case Stmt::NullStmtClass:
107 case Stmt::CompoundStmtClass:
108 case Stmt::DeclStmtClass:
109 case Stmt::LabelStmtClass:
110 case Stmt::AttributedStmtClass:
111 case Stmt::GotoStmtClass:
112 case Stmt::BreakStmtClass:
113 case Stmt::ContinueStmtClass:
114 case Stmt::DefaultStmtClass:
115 case Stmt::CaseStmtClass:
116 case Stmt::DeferStmtClass:
117 case Stmt::SEHLeaveStmtClass:
118 case Stmt::SYCLKernelCallStmtClass:
119 llvm_unreachable("should have emitted these statements as simple");
120
121#define STMT(Type, Base)
122#define ABSTRACT_STMT(Op)
123#define EXPR(Type, Base) \
124 case Stmt::Type##Class:
125#include "clang/AST/StmtNodes.inc"
126 {
127 // Remember the block we came in on.
128 llvm::BasicBlock *incoming = Builder.GetInsertBlock();
129 assert(incoming && "expression emission must have an insertion point");
130
131 EmitIgnoredExpr(E: cast<Expr>(Val: S));
132
133 llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
134 assert(outgoing && "expression emission cleared block!");
135
136 // The expression emitters assume (reasonably!) that the insertion
137 // point is always set. To maintain that, the call-emission code
138 // for noreturn functions has to enter a new block with no
139 // predecessors. We want to kill that block and mark the current
140 // insertion point unreachable in the common case of a call like
141 // "exit();". Since expression emission doesn't otherwise create
142 // blocks with no predecessors, we can just test for that.
143 // However, we must be careful not to do this to our incoming
144 // block, because *statement* emission does sometimes create
145 // reachable blocks which will have no predecessors until later in
146 // the function. This occurs with, e.g., labels that are not
147 // reachable by fallthrough.
148 if (incoming != outgoing && outgoing->use_empty()) {
149 outgoing->eraseFromParent();
150 Builder.ClearInsertionPoint();
151 }
152 break;
153 }
154
155 case Stmt::IndirectGotoStmtClass:
156 EmitIndirectGotoStmt(S: cast<IndirectGotoStmt>(Val: *S)); break;
157
158 case Stmt::IfStmtClass: EmitIfStmt(S: cast<IfStmt>(Val: *S)); break;
159 case Stmt::WhileStmtClass: EmitWhileStmt(S: cast<WhileStmt>(Val: *S), Attrs); break;
160 case Stmt::DoStmtClass: EmitDoStmt(S: cast<DoStmt>(Val: *S), Attrs); break;
161 case Stmt::ForStmtClass: EmitForStmt(S: cast<ForStmt>(Val: *S), Attrs); break;
162
163 case Stmt::ReturnStmtClass: EmitReturnStmt(S: cast<ReturnStmt>(Val: *S)); break;
164
165 case Stmt::SwitchStmtClass: EmitSwitchStmt(S: cast<SwitchStmt>(Val: *S)); break;
166 case Stmt::GCCAsmStmtClass: // Intentional fall-through.
167 case Stmt::MSAsmStmtClass: EmitAsmStmt(S: cast<AsmStmt>(Val: *S)); break;
168 case Stmt::CoroutineBodyStmtClass:
169 EmitCoroutineBody(S: cast<CoroutineBodyStmt>(Val: *S));
170 break;
171 case Stmt::CoreturnStmtClass:
172 EmitCoreturnStmt(S: cast<CoreturnStmt>(Val: *S));
173 break;
174 case Stmt::CapturedStmtClass: {
175 const CapturedStmt *CS = cast<CapturedStmt>(Val: S);
176 EmitCapturedStmt(S: *CS, K: CS->getCapturedRegionKind());
177 }
178 break;
179 case Stmt::ObjCAtTryStmtClass:
180 EmitObjCAtTryStmt(S: cast<ObjCAtTryStmt>(Val: *S));
181 break;
182 case Stmt::ObjCAtCatchStmtClass:
183 llvm_unreachable(
184 "@catch statements should be handled by EmitObjCAtTryStmt");
185 case Stmt::ObjCAtFinallyStmtClass:
186 llvm_unreachable(
187 "@finally statements should be handled by EmitObjCAtTryStmt");
188 case Stmt::ObjCAtThrowStmtClass:
189 EmitObjCAtThrowStmt(S: cast<ObjCAtThrowStmt>(Val: *S));
190 break;
191 case Stmt::ObjCAtSynchronizedStmtClass:
192 EmitObjCAtSynchronizedStmt(S: cast<ObjCAtSynchronizedStmt>(Val: *S));
193 break;
194 case Stmt::ObjCForCollectionStmtClass:
195 EmitObjCForCollectionStmt(S: cast<ObjCForCollectionStmt>(Val: *S));
196 break;
197 case Stmt::ObjCAutoreleasePoolStmtClass:
198 EmitObjCAutoreleasePoolStmt(S: cast<ObjCAutoreleasePoolStmt>(Val: *S));
199 break;
200
201 case Stmt::CXXTryStmtClass:
202 EmitCXXTryStmt(S: cast<CXXTryStmt>(Val: *S));
203 break;
204 case Stmt::CXXForRangeStmtClass:
205 EmitCXXForRangeStmt(S: cast<CXXForRangeStmt>(Val: *S), Attrs);
206 break;
207 case Stmt::CXXExpansionStmtPatternClass:
208 llvm_unreachable("unexpanded expansion statements should not be emitted");
209 case Stmt::CXXExpansionStmtInstantiationClass:
210 EmitCXXExpansionStmtInstantiation(S: cast<CXXExpansionStmtInstantiation>(Val: *S));
211 break;
212 case Stmt::SEHTryStmtClass:
213 EmitSEHTryStmt(S: cast<SEHTryStmt>(Val: *S));
214 break;
215 case Stmt::OMPMetaDirectiveClass:
216 EmitOMPMetaDirective(S: cast<OMPMetaDirective>(Val: *S));
217 break;
218 case Stmt::OMPCanonicalLoopClass:
219 EmitOMPCanonicalLoop(S: cast<OMPCanonicalLoop>(Val: S));
220 break;
221 case Stmt::OMPParallelDirectiveClass:
222 EmitOMPParallelDirective(S: cast<OMPParallelDirective>(Val: *S));
223 break;
224 case Stmt::OMPSimdDirectiveClass:
225 EmitOMPSimdDirective(S: cast<OMPSimdDirective>(Val: *S));
226 break;
227 case Stmt::OMPTileDirectiveClass:
228 EmitOMPTileDirective(S: cast<OMPTileDirective>(Val: *S));
229 break;
230 case Stmt::OMPStripeDirectiveClass:
231 EmitOMPStripeDirective(S: cast<OMPStripeDirective>(Val: *S));
232 break;
233 case Stmt::OMPUnrollDirectiveClass:
234 EmitOMPUnrollDirective(S: cast<OMPUnrollDirective>(Val: *S));
235 break;
236 case Stmt::OMPReverseDirectiveClass:
237 EmitOMPReverseDirective(S: cast<OMPReverseDirective>(Val: *S));
238 break;
239 case Stmt::OMPSplitDirectiveClass:
240 EmitOMPSplitDirective(S: cast<OMPSplitDirective>(Val: *S));
241 break;
242 case Stmt::OMPInterchangeDirectiveClass:
243 EmitOMPInterchangeDirective(S: cast<OMPInterchangeDirective>(Val: *S));
244 break;
245 case Stmt::OMPFlattenDirectiveClass:
246 EmitOMPFlattenDirective(S: cast<OMPFlattenDirective>(Val: *S));
247 break;
248 case Stmt::OMPFuseDirectiveClass:
249 EmitOMPFuseDirective(S: cast<OMPFuseDirective>(Val: *S));
250 break;
251 case Stmt::OMPForDirectiveClass:
252 EmitOMPForDirective(S: cast<OMPForDirective>(Val: *S));
253 break;
254 case Stmt::OMPForSimdDirectiveClass:
255 EmitOMPForSimdDirective(S: cast<OMPForSimdDirective>(Val: *S));
256 break;
257 case Stmt::OMPSectionsDirectiveClass:
258 EmitOMPSectionsDirective(S: cast<OMPSectionsDirective>(Val: *S));
259 break;
260 case Stmt::OMPSectionDirectiveClass:
261 EmitOMPSectionDirective(S: cast<OMPSectionDirective>(Val: *S));
262 break;
263 case Stmt::OMPSingleDirectiveClass:
264 EmitOMPSingleDirective(S: cast<OMPSingleDirective>(Val: *S));
265 break;
266 case Stmt::OMPMasterDirectiveClass:
267 EmitOMPMasterDirective(S: cast<OMPMasterDirective>(Val: *S));
268 break;
269 case Stmt::OMPCriticalDirectiveClass:
270 EmitOMPCriticalDirective(S: cast<OMPCriticalDirective>(Val: *S));
271 break;
272 case Stmt::OMPParallelForDirectiveClass:
273 EmitOMPParallelForDirective(S: cast<OMPParallelForDirective>(Val: *S));
274 break;
275 case Stmt::OMPParallelForSimdDirectiveClass:
276 EmitOMPParallelForSimdDirective(S: cast<OMPParallelForSimdDirective>(Val: *S));
277 break;
278 case Stmt::OMPParallelMasterDirectiveClass:
279 EmitOMPParallelMasterDirective(S: cast<OMPParallelMasterDirective>(Val: *S));
280 break;
281 case Stmt::OMPParallelSectionsDirectiveClass:
282 EmitOMPParallelSectionsDirective(S: cast<OMPParallelSectionsDirective>(Val: *S));
283 break;
284 case Stmt::OMPTaskDirectiveClass:
285 EmitOMPTaskDirective(S: cast<OMPTaskDirective>(Val: *S));
286 break;
287 case Stmt::OMPTaskyieldDirectiveClass:
288 EmitOMPTaskyieldDirective(S: cast<OMPTaskyieldDirective>(Val: *S));
289 break;
290 case Stmt::OMPErrorDirectiveClass:
291 EmitOMPErrorDirective(S: cast<OMPErrorDirective>(Val: *S));
292 break;
293 case Stmt::OMPBarrierDirectiveClass:
294 EmitOMPBarrierDirective(S: cast<OMPBarrierDirective>(Val: *S));
295 break;
296 case Stmt::OMPTaskwaitDirectiveClass:
297 EmitOMPTaskwaitDirective(S: cast<OMPTaskwaitDirective>(Val: *S));
298 break;
299 case Stmt::OMPTaskgroupDirectiveClass:
300 EmitOMPTaskgroupDirective(S: cast<OMPTaskgroupDirective>(Val: *S));
301 break;
302 case Stmt::OMPFlushDirectiveClass:
303 EmitOMPFlushDirective(S: cast<OMPFlushDirective>(Val: *S));
304 break;
305 case Stmt::OMPDepobjDirectiveClass:
306 EmitOMPDepobjDirective(S: cast<OMPDepobjDirective>(Val: *S));
307 break;
308 case Stmt::OMPScanDirectiveClass:
309 EmitOMPScanDirective(S: cast<OMPScanDirective>(Val: *S));
310 break;
311 case Stmt::OMPOrderedStandaloneDirectiveClass:
312 EmitOMPOrderedStandaloneDirective(S: cast<OMPOrderedStandaloneDirective>(Val: *S));
313 break;
314 case Stmt::OMPOrderedBlockAssocDirectiveClass:
315 EmitOMPOrderedBlockAssocDirective(S: cast<OMPOrderedBlockAssocDirective>(Val: *S));
316 break;
317 case Stmt::OMPAtomicDirectiveClass:
318 EmitOMPAtomicDirective(S: cast<OMPAtomicDirective>(Val: *S));
319 break;
320 case Stmt::OMPTargetDirectiveClass:
321 EmitOMPTargetDirective(S: cast<OMPTargetDirective>(Val: *S));
322 break;
323 case Stmt::OMPTeamsDirectiveClass:
324 EmitOMPTeamsDirective(S: cast<OMPTeamsDirective>(Val: *S));
325 break;
326 case Stmt::OMPCancellationPointDirectiveClass:
327 EmitOMPCancellationPointDirective(S: cast<OMPCancellationPointDirective>(Val: *S));
328 break;
329 case Stmt::OMPCancelDirectiveClass:
330 EmitOMPCancelDirective(S: cast<OMPCancelDirective>(Val: *S));
331 break;
332 case Stmt::OMPTargetDataDirectiveClass:
333 EmitOMPTargetDataDirective(S: cast<OMPTargetDataDirective>(Val: *S));
334 break;
335 case Stmt::OMPTargetEnterDataDirectiveClass:
336 EmitOMPTargetEnterDataDirective(S: cast<OMPTargetEnterDataDirective>(Val: *S));
337 break;
338 case Stmt::OMPTargetExitDataDirectiveClass:
339 EmitOMPTargetExitDataDirective(S: cast<OMPTargetExitDataDirective>(Val: *S));
340 break;
341 case Stmt::OMPTargetParallelDirectiveClass:
342 EmitOMPTargetParallelDirective(S: cast<OMPTargetParallelDirective>(Val: *S));
343 break;
344 case Stmt::OMPTargetParallelForDirectiveClass:
345 EmitOMPTargetParallelForDirective(S: cast<OMPTargetParallelForDirective>(Val: *S));
346 break;
347 case Stmt::OMPTaskLoopDirectiveClass:
348 EmitOMPTaskLoopDirective(S: cast<OMPTaskLoopDirective>(Val: *S));
349 break;
350 case Stmt::OMPTaskLoopSimdDirectiveClass:
351 EmitOMPTaskLoopSimdDirective(S: cast<OMPTaskLoopSimdDirective>(Val: *S));
352 break;
353 case Stmt::OMPMasterTaskLoopDirectiveClass:
354 EmitOMPMasterTaskLoopDirective(S: cast<OMPMasterTaskLoopDirective>(Val: *S));
355 break;
356 case Stmt::OMPMaskedTaskLoopDirectiveClass:
357 EmitOMPMaskedTaskLoopDirective(S: cast<OMPMaskedTaskLoopDirective>(Val: *S));
358 break;
359 case Stmt::OMPMasterTaskLoopSimdDirectiveClass:
360 EmitOMPMasterTaskLoopSimdDirective(
361 S: cast<OMPMasterTaskLoopSimdDirective>(Val: *S));
362 break;
363 case Stmt::OMPMaskedTaskLoopSimdDirectiveClass:
364 EmitOMPMaskedTaskLoopSimdDirective(
365 S: cast<OMPMaskedTaskLoopSimdDirective>(Val: *S));
366 break;
367 case Stmt::OMPParallelMasterTaskLoopDirectiveClass:
368 EmitOMPParallelMasterTaskLoopDirective(
369 S: cast<OMPParallelMasterTaskLoopDirective>(Val: *S));
370 break;
371 case Stmt::OMPParallelMaskedTaskLoopDirectiveClass:
372 EmitOMPParallelMaskedTaskLoopDirective(
373 S: cast<OMPParallelMaskedTaskLoopDirective>(Val: *S));
374 break;
375 case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass:
376 EmitOMPParallelMasterTaskLoopSimdDirective(
377 S: cast<OMPParallelMasterTaskLoopSimdDirective>(Val: *S));
378 break;
379 case Stmt::OMPParallelMaskedTaskLoopSimdDirectiveClass:
380 EmitOMPParallelMaskedTaskLoopSimdDirective(
381 S: cast<OMPParallelMaskedTaskLoopSimdDirective>(Val: *S));
382 break;
383 case Stmt::OMPDistributeDirectiveClass:
384 EmitOMPDistributeDirective(S: cast<OMPDistributeDirective>(Val: *S));
385 break;
386 case Stmt::OMPTargetUpdateDirectiveClass:
387 EmitOMPTargetUpdateDirective(S: cast<OMPTargetUpdateDirective>(Val: *S));
388 break;
389 case Stmt::OMPDistributeParallelForDirectiveClass:
390 EmitOMPDistributeParallelForDirective(
391 S: cast<OMPDistributeParallelForDirective>(Val: *S));
392 break;
393 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
394 EmitOMPDistributeParallelForSimdDirective(
395 S: cast<OMPDistributeParallelForSimdDirective>(Val: *S));
396 break;
397 case Stmt::OMPDistributeSimdDirectiveClass:
398 EmitOMPDistributeSimdDirective(S: cast<OMPDistributeSimdDirective>(Val: *S));
399 break;
400 case Stmt::OMPTargetParallelForSimdDirectiveClass:
401 EmitOMPTargetParallelForSimdDirective(
402 S: cast<OMPTargetParallelForSimdDirective>(Val: *S));
403 break;
404 case Stmt::OMPTargetSimdDirectiveClass:
405 EmitOMPTargetSimdDirective(S: cast<OMPTargetSimdDirective>(Val: *S));
406 break;
407 case Stmt::OMPTeamsDistributeDirectiveClass:
408 EmitOMPTeamsDistributeDirective(S: cast<OMPTeamsDistributeDirective>(Val: *S));
409 break;
410 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
411 EmitOMPTeamsDistributeSimdDirective(
412 S: cast<OMPTeamsDistributeSimdDirective>(Val: *S));
413 break;
414 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
415 EmitOMPTeamsDistributeParallelForSimdDirective(
416 S: cast<OMPTeamsDistributeParallelForSimdDirective>(Val: *S));
417 break;
418 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
419 EmitOMPTeamsDistributeParallelForDirective(
420 S: cast<OMPTeamsDistributeParallelForDirective>(Val: *S));
421 break;
422 case Stmt::OMPTargetTeamsDirectiveClass:
423 EmitOMPTargetTeamsDirective(S: cast<OMPTargetTeamsDirective>(Val: *S));
424 break;
425 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
426 EmitOMPTargetTeamsDistributeDirective(
427 S: cast<OMPTargetTeamsDistributeDirective>(Val: *S));
428 break;
429 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
430 EmitOMPTargetTeamsDistributeParallelForDirective(
431 S: cast<OMPTargetTeamsDistributeParallelForDirective>(Val: *S));
432 break;
433 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
434 EmitOMPTargetTeamsDistributeParallelForSimdDirective(
435 S: cast<OMPTargetTeamsDistributeParallelForSimdDirective>(Val: *S));
436 break;
437 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
438 EmitOMPTargetTeamsDistributeSimdDirective(
439 S: cast<OMPTargetTeamsDistributeSimdDirective>(Val: *S));
440 break;
441 case Stmt::OMPInteropDirectiveClass:
442 EmitOMPInteropDirective(S: cast<OMPInteropDirective>(Val: *S));
443 break;
444 case Stmt::OMPDispatchDirectiveClass:
445 CGM.ErrorUnsupported(S, Type: "OpenMP dispatch directive");
446 break;
447 case Stmt::OMPScopeDirectiveClass:
448 EmitOMPScopeDirective(S: cast<OMPScopeDirective>(Val: *S));
449 break;
450 case Stmt::OMPMaskedDirectiveClass:
451 EmitOMPMaskedDirective(S: cast<OMPMaskedDirective>(Val: *S));
452 break;
453 case Stmt::OMPGenericLoopDirectiveClass:
454 EmitOMPGenericLoopDirective(S: cast<OMPGenericLoopDirective>(Val: *S));
455 break;
456 case Stmt::OMPTeamsGenericLoopDirectiveClass:
457 EmitOMPTeamsGenericLoopDirective(S: cast<OMPTeamsGenericLoopDirective>(Val: *S));
458 break;
459 case Stmt::OMPTargetTeamsGenericLoopDirectiveClass:
460 EmitOMPTargetTeamsGenericLoopDirective(
461 S: cast<OMPTargetTeamsGenericLoopDirective>(Val: *S));
462 break;
463 case Stmt::OMPParallelGenericLoopDirectiveClass:
464 EmitOMPParallelGenericLoopDirective(
465 S: cast<OMPParallelGenericLoopDirective>(Val: *S));
466 break;
467 case Stmt::OMPTargetParallelGenericLoopDirectiveClass:
468 EmitOMPTargetParallelGenericLoopDirective(
469 S: cast<OMPTargetParallelGenericLoopDirective>(Val: *S));
470 break;
471 case Stmt::OMPParallelMaskedDirectiveClass:
472 EmitOMPParallelMaskedDirective(S: cast<OMPParallelMaskedDirective>(Val: *S));
473 break;
474 case Stmt::OMPAssumeDirectiveClass:
475 EmitOMPAssumeDirective(S: cast<OMPAssumeDirective>(Val: *S));
476 break;
477 case Stmt::OpenACCComputeConstructClass:
478 EmitOpenACCComputeConstruct(S: cast<OpenACCComputeConstruct>(Val: *S));
479 break;
480 case Stmt::OpenACCLoopConstructClass:
481 EmitOpenACCLoopConstruct(S: cast<OpenACCLoopConstruct>(Val: *S));
482 break;
483 case Stmt::OpenACCCombinedConstructClass:
484 EmitOpenACCCombinedConstruct(S: cast<OpenACCCombinedConstruct>(Val: *S));
485 break;
486 case Stmt::OpenACCDataConstructClass:
487 EmitOpenACCDataConstruct(S: cast<OpenACCDataConstruct>(Val: *S));
488 break;
489 case Stmt::OpenACCEnterDataConstructClass:
490 EmitOpenACCEnterDataConstruct(S: cast<OpenACCEnterDataConstruct>(Val: *S));
491 break;
492 case Stmt::OpenACCExitDataConstructClass:
493 EmitOpenACCExitDataConstruct(S: cast<OpenACCExitDataConstruct>(Val: *S));
494 break;
495 case Stmt::OpenACCHostDataConstructClass:
496 EmitOpenACCHostDataConstruct(S: cast<OpenACCHostDataConstruct>(Val: *S));
497 break;
498 case Stmt::OpenACCWaitConstructClass:
499 EmitOpenACCWaitConstruct(S: cast<OpenACCWaitConstruct>(Val: *S));
500 break;
501 case Stmt::OpenACCInitConstructClass:
502 EmitOpenACCInitConstruct(S: cast<OpenACCInitConstruct>(Val: *S));
503 break;
504 case Stmt::OpenACCShutdownConstructClass:
505 EmitOpenACCShutdownConstruct(S: cast<OpenACCShutdownConstruct>(Val: *S));
506 break;
507 case Stmt::OpenACCSetConstructClass:
508 EmitOpenACCSetConstruct(S: cast<OpenACCSetConstruct>(Val: *S));
509 break;
510 case Stmt::OpenACCUpdateConstructClass:
511 EmitOpenACCUpdateConstruct(S: cast<OpenACCUpdateConstruct>(Val: *S));
512 break;
513 case Stmt::OpenACCAtomicConstructClass:
514 EmitOpenACCAtomicConstruct(S: cast<OpenACCAtomicConstruct>(Val: *S));
515 break;
516 case Stmt::OpenACCCacheConstructClass:
517 EmitOpenACCCacheConstruct(S: cast<OpenACCCacheConstruct>(Val: *S));
518 break;
519 }
520}
521
522bool CodeGenFunction::EmitSimpleStmt(const Stmt *S,
523 ArrayRef<const Attr *> Attrs) {
524 switch (S->getStmtClass()) {
525 default:
526 return false;
527 case Stmt::NullStmtClass:
528 break;
529 case Stmt::CompoundStmtClass:
530 EmitCompoundStmt(S: cast<CompoundStmt>(Val: *S));
531 break;
532 case Stmt::DeclStmtClass:
533 EmitDeclStmt(S: cast<DeclStmt>(Val: *S));
534 break;
535 case Stmt::LabelStmtClass:
536 EmitLabelStmt(S: cast<LabelStmt>(Val: *S));
537 break;
538 case Stmt::AttributedStmtClass:
539 EmitAttributedStmt(S: cast<AttributedStmt>(Val: *S));
540 break;
541 case Stmt::GotoStmtClass:
542 EmitGotoStmt(S: cast<GotoStmt>(Val: *S));
543 break;
544 case Stmt::BreakStmtClass:
545 EmitBreakStmt(S: cast<BreakStmt>(Val: *S));
546 break;
547 case Stmt::ContinueStmtClass:
548 EmitContinueStmt(S: cast<ContinueStmt>(Val: *S));
549 break;
550 case Stmt::DefaultStmtClass:
551 EmitDefaultStmt(S: cast<DefaultStmt>(Val: *S), Attrs);
552 break;
553 case Stmt::CaseStmtClass:
554 EmitCaseStmt(S: cast<CaseStmt>(Val: *S), Attrs);
555 break;
556 case Stmt::DeferStmtClass:
557 EmitDeferStmt(S: cast<DeferStmt>(Val: *S));
558 break;
559 case Stmt::SEHLeaveStmtClass:
560 EmitSEHLeaveStmt(S: cast<SEHLeaveStmt>(Val: *S));
561 break;
562 case Stmt::SYCLKernelCallStmtClass:
563 EmitSYCLKernelCallStmt(S: cast<SYCLKernelCallStmt>(Val: *S));
564 break;
565 }
566 return true;
567}
568
569/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
570/// this captures the expression result of the last sub-statement and returns it
571/// (for use by the statement expression extension).
572Address CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
573 AggValueSlot AggSlot) {
574 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
575 "LLVM IR generation of compound statement ('{}')");
576
577 // Keep track of the current cleanup stack depth, including debug scopes.
578 LexicalScope Scope(*this, S.getSourceRange());
579
580 return EmitCompoundStmtWithoutScope(S, GetLast, AVS: AggSlot);
581}
582
583Address
584CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S,
585 bool GetLast,
586 AggValueSlot AggSlot) {
587
588 for (CompoundStmt::const_body_iterator I = S.body_begin(),
589 E = S.body_end() - GetLast;
590 I != E; ++I)
591 EmitStmt(S: *I);
592
593 Address RetAlloca = Address::invalid();
594 if (GetLast) {
595 // We have to special case labels here. They are statements, but when put
596 // at the end of a statement expression, they yield the value of their
597 // subexpression. Handle this by walking through all labels we encounter,
598 // emitting them before we evaluate the subexpr.
599 // Similar issues arise for attributed statements.
600 const Stmt *LastStmt = S.body_back();
601 while (!isa<Expr>(Val: LastStmt)) {
602 if (const auto *LS = dyn_cast<LabelStmt>(Val: LastStmt)) {
603 EmitLabel(D: LS->getDecl());
604 LastStmt = LS->getSubStmt();
605 } else if (const auto *AS = dyn_cast<AttributedStmt>(Val: LastStmt)) {
606 // FIXME: Update this if we ever have attributes that affect the
607 // semantics of an expression.
608 LastStmt = AS->getSubStmt();
609 } else {
610 llvm_unreachable("unknown value statement");
611 }
612 }
613
614 EnsureInsertPoint();
615
616 const Expr *E = cast<Expr>(Val: LastStmt);
617 QualType ExprTy = E->getType();
618 if (hasAggregateEvaluationKind(T: ExprTy)) {
619 EmitAggExpr(E, AS: AggSlot);
620 } else {
621 // We can't return an RValue here because there might be cleanups at
622 // the end of the StmtExpr. Because of that, we have to emit the result
623 // here into a temporary alloca.
624 RetAlloca = CreateMemTempWithoutCast(T: ExprTy);
625 EmitAnyExprToMem(E, Location: RetAlloca, Quals: Qualifiers(),
626 /*IsInit*/ IsInitializer: false);
627 }
628 }
629
630 return RetAlloca;
631}
632
633void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
634 llvm::UncondBrInst *BI = dyn_cast<llvm::UncondBrInst>(Val: BB->getTerminator());
635
636 // If there is a cleanup stack, then we it isn't worth trying to
637 // simplify this block (we would need to remove it from the scope map
638 // and cleanup entry).
639 if (!EHStack.empty())
640 return;
641
642 // Can only simplify direct branches.
643 if (!BI)
644 return;
645
646 // Can only simplify empty blocks.
647 if (BI->getIterator() != BB->begin())
648 return;
649
650 BB->replaceAllUsesWith(V: BI->getSuccessor());
651 BI->eraseFromParent();
652 BB->eraseFromParent();
653}
654
655void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
656 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
657
658 // Fall out of the current block (if necessary).
659 EmitBranch(Block: BB);
660
661 if (IsFinished && BB->use_empty()) {
662 delete BB;
663 return;
664 }
665
666 // Place the block after the current block, if possible, or else at
667 // the end of the function.
668 if (CurBB && CurBB->getParent())
669 CurFn->insert(Position: std::next(x: CurBB->getIterator()), BB);
670 else
671 CurFn->insert(Position: CurFn->end(), BB);
672 Builder.SetInsertPoint(BB);
673}
674
675void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
676 // Emit a branch from the current block to the target one if this
677 // was a real block. If this was just a fall-through block after a
678 // terminator, don't emit it.
679 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
680
681 if (!CurBB || CurBB->hasTerminator()) {
682 // If there is no insert point or the previous block is already
683 // terminated, don't touch it.
684 } else {
685 // Otherwise, create a fall-through branch.
686 Builder.CreateBr(Dest: Target);
687 }
688
689 Builder.ClearInsertionPoint();
690}
691
692void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
693 bool inserted = false;
694 for (llvm::User *u : block->users()) {
695 if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(Val: u)) {
696 CurFn->insert(Position: std::next(x: insn->getParent()->getIterator()), BB: block);
697 inserted = true;
698 break;
699 }
700 }
701
702 if (!inserted)
703 CurFn->insert(Position: CurFn->end(), BB: block);
704
705 Builder.SetInsertPoint(block);
706}
707
708CodeGenFunction::JumpDest
709CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
710 JumpDest &Dest = LabelMap[D];
711 if (Dest.isValid()) return Dest;
712
713 // Create, but don't insert, the new block.
714 Dest = JumpDest(createBasicBlock(name: D->getName()),
715 EHScopeStack::stable_iterator::invalid(),
716 NextCleanupDestIndex++);
717 return Dest;
718}
719
720void CodeGenFunction::EmitLabel(const LabelDecl *D) {
721 // Add this label to the current lexical scope if we're within any
722 // normal cleanups. Jumps "in" to this label --- when permitted by
723 // the language --- may need to be routed around such cleanups.
724 if (EHStack.hasNormalCleanups() && CurLexicalScope)
725 CurLexicalScope->addLabel(label: D);
726
727 JumpDest &Dest = LabelMap[D];
728
729 // If we didn't need a forward reference to this label, just go
730 // ahead and create a destination at the current scope.
731 if (!Dest.isValid()) {
732 Dest = getJumpDestInCurrentScope(Name: D->getName());
733
734 // Otherwise, we need to give this label a target depth and remove
735 // it from the branch-fixups list.
736 } else {
737 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
738 Dest.setScopeDepth(EHStack.stable_begin());
739 ResolveBranchFixups(Target: Dest.getBlock());
740 }
741
742 EmitBlock(BB: Dest.getBlock());
743
744 // Emit debug info for labels.
745 if (CGDebugInfo *DI = getDebugInfo()) {
746 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
747 DI->setLocation(D->getLocation());
748 DI->EmitLabel(D, Builder);
749 }
750 }
751
752 incrementProfileCounter(S: D->getStmt());
753}
754
755/// Change the cleanup scope of the labels in this lexical scope to
756/// match the scope of the enclosing context.
757void CodeGenFunction::LexicalScope::rescopeLabels() {
758 assert(!Labels.empty());
759 EHScopeStack::stable_iterator innermostScope
760 = CGF.EHStack.getInnermostNormalCleanup();
761
762 // Change the scope depth of all the labels.
763 for (const LabelDecl *Label : Labels) {
764 assert(CGF.LabelMap.count(Label));
765 JumpDest &dest = CGF.LabelMap.find(Val: Label)->second;
766 assert(dest.getScopeDepth().isValid());
767 assert(innermostScope.encloses(dest.getScopeDepth()));
768 dest.setScopeDepth(innermostScope);
769 }
770
771 // Reparent the labels if the new scope also has cleanups.
772 if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
773 ParentScope->Labels.append(in_start: Labels.begin(), in_end: Labels.end());
774 }
775}
776
777
778void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
779 EmitLabel(D: S.getDecl());
780
781 // IsEHa - emit eha.scope.begin if it's a side entry of a scope
782 if (getLangOpts().EHAsynch && S.isSideEntry())
783 EmitSehCppScopeBegin();
784
785 EmitStmt(S: S.getSubStmt());
786}
787
788void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
789 bool nomerge = InNoMergeAttributedStmt;
790 bool noinline = InNoInlineAttributedStmt;
791 bool alwaysinline = InAlwaysInlineAttributedStmt;
792 bool noconvergent = InNoConvergentAttributedStmt;
793 StringRef amdgpuAVMode = AMDGPUAvailableVisibleMode;
794 HLSLControlFlowHintAttr::Spelling flattenOrBranch = HLSLControlFlowAttr;
795 const CallExpr *musttail = MustTailCall;
796 const AtomicAttr *AA = nullptr;
797
798 for (const auto *A : S.getAttrs()) {
799 switch (A->getKind()) {
800 default:
801 break;
802 case attr::NoMerge:
803 nomerge = true;
804 break;
805 case attr::NoInline:
806 noinline = true;
807 alwaysinline = false;
808 break;
809 case attr::AlwaysInline:
810 alwaysinline = true;
811 noinline = false;
812 break;
813 case attr::NoConvergent:
814 noconvergent = true;
815 break;
816 case attr::MustTail: {
817 const Stmt *Sub = S.getSubStmt();
818 const ReturnStmt *R = cast<ReturnStmt>(Val: Sub);
819 musttail = cast<CallExpr>(Val: R->getRetValue()->IgnoreParens());
820 } break;
821 case attr::CXXAssume: {
822 const Expr *Assumption = cast<CXXAssumeAttr>(Val: A)->getAssumption();
823 if (getLangOpts().CXXAssumptions && Builder.GetInsertBlock() &&
824 !Assumption->HasSideEffects(Ctx: getContext())) {
825 llvm::Value *AssumptionVal = EmitCheckedArgForAssume(E: Assumption);
826 Builder.CreateAssumption(Cond: AssumptionVal);
827 }
828 } break;
829 case attr::Atomic:
830 AA = cast<AtomicAttr>(Val: A);
831 break;
832 case attr::AMDGPUAvailableVisible:
833 amdgpuAVMode = cast<AMDGPUAvailableVisibleAttr>(Val: A)->getMode();
834 break;
835 case attr::HLSLControlFlowHint: {
836 flattenOrBranch = cast<HLSLControlFlowHintAttr>(Val: A)->getSemanticSpelling();
837 } break;
838 }
839 }
840
841 assert(!(alwaysinline && noinline) &&
842 "alwaysinline and noinline are mutually exclusive");
843
844 SaveAndRestore save_nomerge(InNoMergeAttributedStmt, nomerge);
845 SaveAndRestore save_noinline(InNoInlineAttributedStmt, noinline);
846 SaveAndRestore save_alwaysinline(InAlwaysInlineAttributedStmt, alwaysinline);
847 SaveAndRestore save_noconvergent(InNoConvergentAttributedStmt, noconvergent);
848 SaveAndRestore save_amdgpuav(AMDGPUAvailableVisibleMode, amdgpuAVMode);
849 SaveAndRestore save_musttail(MustTailCall, musttail);
850 SaveAndRestore save_flattenOrBranch(HLSLControlFlowAttr, flattenOrBranch);
851 CGAtomicOptionsRAII AORAII(CGM, AA);
852 EmitStmt(S: S.getSubStmt(), Attrs: S.getAttrs());
853}
854
855void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
856 // If this code is reachable then emit a stop point (if generating
857 // debug info). We have to do this ourselves because we are on the
858 // "simple" statement path.
859 if (HaveInsertPoint())
860 EmitStopPoint(S: &S);
861
862 // Reinitialize the variables this goto bypasses, whose scope it re-enters.
863 // Backward gotos reinit here while forward gotos are recorded for
864 // EmitAutoVarAlloca to patch once the alloca exists. Skip when jump sources
865 // are unknown (computed goto); EmitAutoVarAlloca then uses function-scope
866 // init.
867 if (HaveInsertPoint() && !Bypasses.isAlwaysBypassed()) {
868 emitBypassedVarInitsForSource(Source: &S);
869 BypassingForwardJumps.push_back(Elt: {.Block: Builder.GetInsertBlock(), .Source: &S});
870 }
871
872 ApplyAtomGroup Grp(getDebugInfo());
873 EmitBranchThroughCleanup(Dest: getJumpDestForLabel(D: S.getLabel()));
874}
875
876
877void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
878 ApplyAtomGroup Grp(getDebugInfo());
879 if (const LabelDecl *Target = S.getConstantTarget()) {
880 EmitBranchThroughCleanup(Dest: getJumpDestForLabel(D: Target));
881 return;
882 }
883
884 // Ensure that we have an i8* for our PHI node.
885 llvm::Value *V = Builder.CreateBitCast(V: EmitScalarExpr(E: S.getTarget()),
886 DestTy: Int8PtrTy, Name: "addr");
887 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
888
889 // Get the basic block for the indirect goto.
890 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
891
892 // The first instruction in the block has to be the PHI for the switch dest,
893 // add an entry for this branch.
894 cast<llvm::PHINode>(Val: IndGotoBB->begin())->addIncoming(V, BB: CurBB);
895
896 EmitBranch(Target: IndGotoBB);
897 if (CurBB && CurBB->hasTerminator())
898 addInstToCurrentSourceAtom(KeyInstruction: CurBB->getTerminator(), Backup: nullptr);
899}
900
901void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
902 const Stmt *Else = S.getElse();
903
904 // The else branch of a consteval if statement is always the only branch that
905 // can be runtime evaluated.
906 if (S.isConsteval()) {
907 const Stmt *Executed = S.isNegatedConsteval() ? S.getThen() : Else;
908 if (Executed) {
909 RunCleanupsScope ExecutedScope(*this);
910 EmitStmt(S: Executed);
911 }
912 return;
913 }
914
915 // C99 6.8.4.1: The first substatement is executed if the expression compares
916 // unequal to 0. The condition must be a scalar type.
917 LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
918 ApplyDebugLocation DL(*this, S.getCond());
919
920 if (S.getInit()) {
921 EmitStmt(S: S.getInit());
922
923 // The init statement may have cleared the insertion point (e.g. it ended in
924 // a 'noreturn' call); the condition emitted below needs a valid one.
925 EnsureInsertPoint();
926 }
927
928 if (S.getConditionVariable())
929 EmitDecl(D: *S.getConditionVariable());
930
931 // If the condition constant folds and can be elided, try to avoid emitting
932 // the condition and the dead arm of the if/else.
933 bool CondConstant;
934 if (ConstantFoldsToSimpleInteger(Cond: S.getCond(), Result&: CondConstant,
935 AllowLabels: S.isConstexpr())) {
936 // Figure out which block (then or else) is executed.
937 const Stmt *Executed = S.getThen();
938 const Stmt *Skipped = Else;
939 if (!CondConstant) // Condition false?
940 std::swap(a&: Executed, b&: Skipped);
941
942 // If the skipped block has no labels in it, just emit the executed block.
943 // This avoids emitting dead code and simplifies the CFG substantially.
944 if (S.isConstexpr() || !ContainsLabel(S: Skipped)) {
945 incrementProfileCounter(ExecSkip: CondConstant ? UseExecPath : UseSkipPath, S: &S,
946 /*UseBoth=*/true);
947 if (Executed) {
948 MaybeEmitDeferredVarDeclInit(var: S.getConditionVariable());
949 RunCleanupsScope ExecutedScope(*this);
950 EmitStmt(S: Executed);
951 }
952 PGO->markStmtMaybeUsed(S: Skipped);
953 return;
954 }
955 }
956
957 auto HasSkip = hasSkipCounter(S: &S);
958
959 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
960 // the conditional branch.
961 llvm::BasicBlock *ThenBlock = createBasicBlock(name: "if.then");
962 llvm::BasicBlock *ContBlock = createBasicBlock(name: "if.end");
963 llvm::BasicBlock *ElseBlock =
964 (Else || HasSkip ? createBasicBlock(name: "if.else") : ContBlock);
965 // Prefer the PGO based weights over the likelihood attribute.
966 // When the build isn't optimized the metadata isn't used, so don't generate
967 // it.
968 // Also, differentiate between disabled PGO and a never executed branch with
969 // PGO. Assuming PGO is in use:
970 // - we want to ignore the [[likely]] attribute if the branch is never
971 // executed,
972 // - assuming the profile is poor, preserving the attribute may still be
973 // beneficial.
974 // As an approximation, preserve the attribute only if both the branch and the
975 // parent context were not executed.
976 Stmt::Likelihood LH = Stmt::LH_None;
977 uint64_t ThenCount = getProfileCount(S: S.getThen());
978 if (!ThenCount && !getCurrentProfileCount() &&
979 CGM.getCodeGenOpts().OptimizationLevel)
980 LH = Stmt::getLikelihood(Then: S.getThen(), Else);
981
982 // When measuring MC/DC, always fully evaluate the condition up front using
983 // EvaluateExprAsBool() so that the test vector bitmap can be updated prior to
984 // executing the body of the if.then or if.else. This is useful for when
985 // there is a 'return' within the body, but this is particularly beneficial
986 // when one if-stmt is nested within another if-stmt so that all of the MC/DC
987 // updates are kept linear and consistent.
988 if (!CGM.getCodeGenOpts().MCDCCoverage) {
989 EmitBranchOnBoolExpr(Cond: S.getCond(), TrueBlock: ThenBlock, FalseBlock: ElseBlock, TrueCount: ThenCount, LH,
990 /*ConditionalOp=*/nullptr,
991 /*ConditionalDecl=*/S.getConditionVariable());
992 } else {
993 llvm::Value *BoolCondVal = EvaluateExprAsBool(E: S.getCond());
994 MaybeEmitDeferredVarDeclInit(var: S.getConditionVariable());
995 Builder.CreateCondBr(Cond: BoolCondVal, True: ThenBlock, False: ElseBlock);
996 }
997
998 // Emit the 'then' code.
999 EmitBlock(BB: ThenBlock);
1000 incrementProfileCounter(ExecSkip: UseExecPath, S: &S);
1001 {
1002 RunCleanupsScope ThenScope(*this);
1003 EmitStmt(S: S.getThen());
1004 }
1005 EmitBranch(Target: ContBlock);
1006
1007 // Emit the 'else' code if present.
1008 if (Else) {
1009 {
1010 // There is no need to emit line number for an unconditional branch.
1011 auto NL = ApplyDebugLocation::CreateEmpty(CGF&: *this);
1012 EmitBlock(BB: ElseBlock);
1013 }
1014 // Add a counter to else block unless it has CounterExpr.
1015 if (HasSkip)
1016 incrementProfileCounter(ExecSkip: UseSkipPath, S: &S);
1017 {
1018 RunCleanupsScope ElseScope(*this);
1019 EmitStmt(S: Else);
1020 }
1021 {
1022 // There is no need to emit line number for an unconditional branch.
1023 auto NL = ApplyDebugLocation::CreateEmpty(CGF&: *this);
1024 EmitBranch(Target: ContBlock);
1025 }
1026 } else if (HasSkip) {
1027 EmitBlock(BB: ElseBlock);
1028 incrementProfileCounter(ExecSkip: UseSkipPath, S: &S);
1029 EmitBranch(Target: ContBlock);
1030 }
1031
1032 // Emit the continuation block for code after the if.
1033 EmitBlock(BB: ContBlock, IsFinished: true);
1034}
1035
1036bool CodeGenFunction::checkIfLoopMustProgress(const Expr *ControllingExpression,
1037 bool HasEmptyBody) {
1038 return CodeGenUtils::checkIfLoopMustProgress(
1039 LangOpts: getLangOpts(), CGOpts: CGM.getCodeGenOpts(), Ctx&: getContext(), ControllingExpression,
1040 HasEmptyBody,
1041 RemoveMustProgress: [this] { CurFn->removeFnAttr(Kind: llvm::Attribute::MustProgress); });
1042}
1043
1044void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
1045 ArrayRef<const Attr *> WhileAttrs) {
1046 // Emit the header for the loop, which will also become
1047 // the continue target.
1048 JumpDest LoopHeader = getJumpDestInCurrentScope(Name: "while.cond");
1049 EmitBlock(BB: LoopHeader.getBlock());
1050
1051 if (CGM.shouldEmitConvergenceTokens())
1052 ConvergenceTokenStack.push_back(
1053 Elt: emitConvergenceLoopToken(BB: LoopHeader.getBlock()));
1054
1055 // Create an exit block for when the condition fails, which will
1056 // also become the break target.
1057 JumpDest LoopExit = getJumpDestInCurrentScope(Name: "while.end");
1058
1059 // Store the blocks to use for break and continue.
1060 BreakContinueStack.push_back(Elt: BreakContinue(S, LoopExit, LoopHeader));
1061
1062 // C++ [stmt.while]p2:
1063 // When the condition of a while statement is a declaration, the
1064 // scope of the variable that is declared extends from its point
1065 // of declaration (3.3.2) to the end of the while statement.
1066 // [...]
1067 // The object created in a condition is destroyed and created
1068 // with each iteration of the loop.
1069 RunCleanupsScope ConditionScope(*this);
1070
1071 if (S.getConditionVariable())
1072 EmitDecl(D: *S.getConditionVariable());
1073
1074 // Evaluate the conditional in the while header. C99 6.8.5.1: The
1075 // evaluation of the controlling expression takes place before each
1076 // execution of the loop body.
1077 llvm::Value *BoolCondVal = EvaluateExprAsBool(E: S.getCond());
1078
1079 MaybeEmitDeferredVarDeclInit(var: S.getConditionVariable());
1080
1081 // while(1) is common, avoid extra exit blocks. Be sure
1082 // to correctly handle break/continue though.
1083 llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(Val: BoolCondVal);
1084 bool EmitBoolCondBranch = !C || !C->isOne();
1085 const SourceRange &R = S.getSourceRange();
1086 LoopStack.push(
1087 Header: LoopHeader.getBlock(), Ctx&: CGM.getContext(), CGOpts: CGM.getCodeGenOpts(), Attrs: WhileAttrs,
1088 StartLoc: SourceLocToDebugLoc(Location: R.getBegin()), EndLoc: SourceLocToDebugLoc(Location: R.getEnd()),
1089 MustProgress: checkIfLoopMustProgress(ControllingExpression: S.getCond(), HasEmptyBody: CodeGenUtils::hasEmptyLoopBody(S)));
1090
1091 // As long as the condition is true, go to the loop body.
1092 llvm::BasicBlock *LoopBody = createBasicBlock(name: "while.body");
1093 if (EmitBoolCondBranch) {
1094 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
1095 if (hasSkipCounter(S: &S) || ConditionScope.requiresCleanups())
1096 ExitBlock = createBasicBlock(name: "while.exit");
1097 llvm::MDNode *Weights =
1098 createProfileWeightsForLoop(Cond: S.getCond(), LoopCount: getProfileCount(S: S.getBody()));
1099 if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
1100 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
1101 Cond: BoolCondVal, LH: Stmt::getLikelihood(S: S.getBody()));
1102 auto *I = Builder.CreateCondBr(Cond: BoolCondVal, True: LoopBody, False: ExitBlock, BranchWeights: Weights);
1103 // Key Instructions: Emit the condition and branch as separate source
1104 // location atoms otherwise we may omit a step onto the loop condition in
1105 // favour of the `while` keyword.
1106 // FIXME: We could have the branch as the backup location for the condition,
1107 // which would probably be a better experience. Explore this later.
1108 if (auto *CondI = dyn_cast<llvm::Instruction>(Val: BoolCondVal))
1109 addInstToNewSourceAtom(KeyInstruction: CondI, Backup: nullptr);
1110 addInstToNewSourceAtom(KeyInstruction: I, Backup: nullptr);
1111
1112 if (ExitBlock != LoopExit.getBlock()) {
1113 EmitBlock(BB: ExitBlock);
1114 incrementProfileCounter(ExecSkip: UseSkipPath, S: &S);
1115 EmitBranchThroughCleanup(Dest: LoopExit);
1116 }
1117 } else if (const Attr *A = Stmt::getLikelihoodAttr(S: S.getBody())) {
1118 CGM.getDiags().Report(Loc: A->getLocation(),
1119 DiagID: diag::warn_attribute_has_no_effect_on_infinite_loop)
1120 << A << A->getRange();
1121 CGM.getDiags().Report(
1122 Loc: S.getWhileLoc(),
1123 DiagID: diag::note_attribute_has_no_effect_on_infinite_loop_here)
1124 << SourceRange(S.getWhileLoc(), S.getRParenLoc());
1125 }
1126
1127 // Emit the loop body. We have to emit this in a cleanup scope
1128 // because it might be a singleton DeclStmt.
1129 {
1130 RunCleanupsScope BodyScope(*this);
1131 EmitBlock(BB: LoopBody);
1132 incrementProfileCounter(ExecSkip: UseExecPath, S: &S);
1133 EmitStmt(S: S.getBody());
1134 }
1135
1136 BreakContinueStack.pop_back();
1137
1138 // Immediately force cleanup.
1139 ConditionScope.ForceCleanup();
1140
1141 EmitStopPoint(S: &S);
1142 // Branch to the loop header again.
1143 EmitBranch(Target: LoopHeader.getBlock());
1144
1145 LoopStack.pop();
1146
1147 // Emit the exit block.
1148 EmitBlock(BB: LoopExit.getBlock(), IsFinished: true);
1149
1150 // The LoopHeader typically is just a branch if we skipped emitting
1151 // a branch, try to erase it.
1152 if (!EmitBoolCondBranch) {
1153 SimplifyForwardingBlocks(BB: LoopHeader.getBlock());
1154 PGO->markStmtAsUsed(Skipped: true, S: &S);
1155 }
1156
1157 if (CGM.shouldEmitConvergenceTokens())
1158 ConvergenceTokenStack.pop_back();
1159}
1160
1161void CodeGenFunction::EmitDoStmt(const DoStmt &S,
1162 ArrayRef<const Attr *> DoAttrs) {
1163 JumpDest LoopExit = getJumpDestInCurrentScope(Name: "do.end");
1164 JumpDest LoopCond = getJumpDestInCurrentScope(Name: "do.cond");
1165
1166 uint64_t ParentCount = getCurrentProfileCount();
1167
1168 // Store the blocks to use for break and continue.
1169 BreakContinueStack.push_back(Elt: BreakContinue(S, LoopExit, LoopCond));
1170
1171 // Emit the body of the loop.
1172 llvm::BasicBlock *LoopBody = createBasicBlock(name: "do.body");
1173
1174 EmitBlockWithFallThrough(BB: LoopBody, S: &S);
1175
1176 if (CGM.shouldEmitConvergenceTokens())
1177 ConvergenceTokenStack.push_back(Elt: emitConvergenceLoopToken(BB: LoopBody));
1178
1179 {
1180 RunCleanupsScope BodyScope(*this);
1181 EmitStmt(S: S.getBody());
1182 }
1183
1184 EmitBlock(BB: LoopCond.getBlock());
1185
1186 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
1187 // after each execution of the loop body."
1188
1189 // Evaluate the conditional in the while header.
1190 // C99 6.8.5p2/p4: The first substatement is executed if the expression
1191 // compares unequal to 0. The condition must be a scalar type.
1192 llvm::Value *BoolCondVal = EvaluateExprAsBool(E: S.getCond());
1193
1194 BreakContinueStack.pop_back();
1195
1196 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
1197 // to correctly handle break/continue though.
1198 llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(Val: BoolCondVal);
1199 bool EmitBoolCondBranch = !C || !C->isZero();
1200
1201 const SourceRange &R = S.getSourceRange();
1202 LoopStack.push(
1203 Header: LoopBody, Ctx&: CGM.getContext(), CGOpts: CGM.getCodeGenOpts(), Attrs: DoAttrs,
1204 StartLoc: SourceLocToDebugLoc(Location: R.getBegin()), EndLoc: SourceLocToDebugLoc(Location: R.getEnd()),
1205 MustProgress: checkIfLoopMustProgress(ControllingExpression: S.getCond(), HasEmptyBody: CodeGenUtils::hasEmptyLoopBody(S)));
1206
1207 auto *LoopFalse = (hasSkipCounter(S: &S) ? createBasicBlock(name: "do.loopfalse")
1208 : LoopExit.getBlock());
1209
1210 // As long as the condition is true, iterate the loop.
1211 if (EmitBoolCondBranch) {
1212 uint64_t BackedgeCount = getProfileCount(S: S.getBody()) - ParentCount;
1213 auto *I = Builder.CreateCondBr(
1214 Cond: BoolCondVal, True: LoopBody, False: LoopFalse,
1215 BranchWeights: createProfileWeightsForLoop(Cond: S.getCond(), LoopCount: BackedgeCount));
1216
1217 // Key Instructions: Emit the condition and branch as separate source
1218 // location atoms otherwise we may omit a step onto the loop condition in
1219 // favour of the closing brace.
1220 // FIXME: We could have the branch as the backup location for the condition,
1221 // which would probably be a better experience (no jumping to the brace).
1222 if (auto *CondI = dyn_cast<llvm::Instruction>(Val: BoolCondVal))
1223 addInstToNewSourceAtom(KeyInstruction: CondI, Backup: nullptr);
1224 addInstToNewSourceAtom(KeyInstruction: I, Backup: nullptr);
1225 }
1226
1227 LoopStack.pop();
1228
1229 if (LoopFalse != LoopExit.getBlock()) {
1230 EmitBlock(BB: LoopFalse);
1231 incrementProfileCounter(ExecSkip: UseSkipPath, S: &S, /*UseBoth=*/true);
1232 }
1233
1234 // Emit the exit block.
1235 EmitBlock(BB: LoopExit.getBlock());
1236
1237 // The DoCond block typically is just a branch if we skipped
1238 // emitting a branch, try to erase it.
1239 if (!EmitBoolCondBranch)
1240 SimplifyForwardingBlocks(BB: LoopCond.getBlock());
1241
1242 if (CGM.shouldEmitConvergenceTokens())
1243 ConvergenceTokenStack.pop_back();
1244}
1245
1246void CodeGenFunction::EmitForStmt(const ForStmt &S,
1247 ArrayRef<const Attr *> ForAttrs) {
1248 JumpDest LoopExit = getJumpDestInCurrentScope(Name: "for.end");
1249
1250 std::optional<LexicalScope> ForScope;
1251 if (getLangOpts().C99 || getLangOpts().CPlusPlus)
1252 ForScope.emplace(args&: *this, args: S.getSourceRange());
1253
1254 // Evaluate the first part before the loop.
1255 if (S.getInit())
1256 EmitStmt(S: S.getInit());
1257
1258 // Start the loop with a block that tests the condition.
1259 // If there's an increment, the continue scope will be overwritten
1260 // later.
1261 JumpDest CondDest = getJumpDestInCurrentScope(Name: "for.cond");
1262 llvm::BasicBlock *CondBlock = CondDest.getBlock();
1263 EmitBlock(BB: CondBlock);
1264
1265 if (CGM.shouldEmitConvergenceTokens())
1266 ConvergenceTokenStack.push_back(Elt: emitConvergenceLoopToken(BB: CondBlock));
1267
1268 const SourceRange &R = S.getSourceRange();
1269 LoopStack.push(
1270 Header: CondBlock, Ctx&: CGM.getContext(), CGOpts: CGM.getCodeGenOpts(), Attrs: ForAttrs,
1271 StartLoc: SourceLocToDebugLoc(Location: R.getBegin()), EndLoc: SourceLocToDebugLoc(Location: R.getEnd()),
1272 MustProgress: checkIfLoopMustProgress(ControllingExpression: S.getCond(), HasEmptyBody: CodeGenUtils::hasEmptyLoopBody(S)));
1273
1274 // Create a cleanup scope for the condition variable cleanups.
1275 LexicalScope ConditionScope(*this, S.getSourceRange());
1276
1277 // If the for loop doesn't have an increment we can just use the condition as
1278 // the continue block. Otherwise, if there is no condition variable, we can
1279 // form the continue block now. If there is a condition variable, we can't
1280 // form the continue block until after we've emitted the condition, because
1281 // the condition is in scope in the increment, but Sema's jump diagnostics
1282 // ensure that there are no continues from the condition variable that jump
1283 // to the loop increment.
1284 JumpDest Continue;
1285 if (!S.getInc())
1286 Continue = CondDest;
1287 else if (!S.getConditionVariable())
1288 Continue = getJumpDestInCurrentScope(Name: "for.inc");
1289 BreakContinueStack.push_back(Elt: BreakContinue(S, LoopExit, Continue));
1290
1291 if (S.getCond()) {
1292 // If the for statement has a condition scope, emit the local variable
1293 // declaration.
1294 if (S.getConditionVariable()) {
1295 EmitDecl(D: *S.getConditionVariable());
1296
1297 // We have entered the condition variable's scope, so we're now able to
1298 // jump to the continue block.
1299 Continue = S.getInc() ? getJumpDestInCurrentScope(Name: "for.inc") : CondDest;
1300 BreakContinueStack.back().ContinueBlock = Continue;
1301 }
1302
1303 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
1304 // If there are any cleanups between here and the loop-exit scope,
1305 // create a block to stage a loop exit along.
1306 if (hasSkipCounter(S: &S) || (ForScope && ForScope->requiresCleanups()))
1307 ExitBlock = createBasicBlock(name: "for.cond.cleanup");
1308
1309 // As long as the condition is true, iterate the loop.
1310 llvm::BasicBlock *ForBody = createBasicBlock(name: "for.body");
1311
1312 // C99 6.8.5p2/p4: The first substatement is executed if the expression
1313 // compares unequal to 0. The condition must be a scalar type.
1314 llvm::Value *BoolCondVal = EvaluateExprAsBool(E: S.getCond());
1315
1316 MaybeEmitDeferredVarDeclInit(var: S.getConditionVariable());
1317
1318 llvm::MDNode *Weights =
1319 createProfileWeightsForLoop(Cond: S.getCond(), LoopCount: getProfileCount(S: S.getBody()));
1320 if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
1321 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
1322 Cond: BoolCondVal, LH: Stmt::getLikelihood(S: S.getBody()));
1323
1324 auto *I = Builder.CreateCondBr(Cond: BoolCondVal, True: ForBody, False: ExitBlock, BranchWeights: Weights);
1325 // Key Instructions: Emit the condition and branch as separate atoms to
1326 // match existing loop stepping behaviour. FIXME: We could have the branch
1327 // as the backup location for the condition, which would probably be a
1328 // better experience (no jumping to the brace).
1329 if (auto *CondI = dyn_cast<llvm::Instruction>(Val: BoolCondVal))
1330 addInstToNewSourceAtom(KeyInstruction: CondI, Backup: nullptr);
1331 addInstToNewSourceAtom(KeyInstruction: I, Backup: nullptr);
1332
1333 if (ExitBlock != LoopExit.getBlock()) {
1334 EmitBlock(BB: ExitBlock);
1335 incrementProfileCounter(ExecSkip: UseSkipPath, S: &S);
1336 EmitBranchThroughCleanup(Dest: LoopExit);
1337 }
1338
1339 EmitBlock(BB: ForBody);
1340 } else {
1341 // Treat it as a non-zero constant. Don't even create a new block for the
1342 // body, just fall into it.
1343 PGO->markStmtAsUsed(Skipped: true, S: &S);
1344 }
1345
1346 incrementProfileCounter(ExecSkip: UseExecPath, S: &S);
1347
1348 {
1349 // Create a separate cleanup scope for the body, in case it is not
1350 // a compound statement.
1351 RunCleanupsScope BodyScope(*this);
1352 EmitStmt(S: S.getBody());
1353 }
1354
1355 // The last block in the loop's body (which unconditionally branches to the
1356 // `inc` block if there is one).
1357 auto *FinalBodyBB = Builder.GetInsertBlock();
1358
1359 // If there is an increment, emit it next.
1360 if (S.getInc()) {
1361 EmitBlock(BB: Continue.getBlock());
1362 EmitStmt(S: S.getInc());
1363 }
1364
1365 BreakContinueStack.pop_back();
1366
1367 ConditionScope.ForceCleanup();
1368
1369 EmitStopPoint(S: &S);
1370 EmitBranch(Target: CondBlock);
1371
1372 if (ForScope)
1373 ForScope->ForceCleanup();
1374
1375 LoopStack.pop();
1376
1377 // Emit the fall-through block.
1378 EmitBlock(BB: LoopExit.getBlock(), IsFinished: true);
1379
1380 if (CGM.shouldEmitConvergenceTokens())
1381 ConvergenceTokenStack.pop_back();
1382
1383 if (FinalBodyBB) {
1384 // Key Instructions: We want the for closing brace to be step-able on to
1385 // match existing behaviour.
1386 addInstToNewSourceAtom(KeyInstruction: FinalBodyBB->getTerminator(), Backup: nullptr);
1387 }
1388}
1389
1390void
1391CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
1392 ArrayRef<const Attr *> ForAttrs) {
1393 JumpDest LoopExit = getJumpDestInCurrentScope(Name: "for.end");
1394
1395 LexicalScope ForScope(*this, S.getSourceRange());
1396
1397 // Evaluate the first pieces before the loop.
1398 if (S.getInit())
1399 EmitStmt(S: S.getInit());
1400 EmitStmt(S: S.getRangeStmt());
1401 EmitStmt(S: S.getBeginStmt());
1402 EmitStmt(S: S.getEndStmt());
1403
1404 // Start the loop with a block that tests the condition.
1405 // If there's an increment, the continue scope will be overwritten
1406 // later.
1407 llvm::BasicBlock *CondBlock = createBasicBlock(name: "for.cond");
1408 EmitBlock(BB: CondBlock);
1409
1410 if (CGM.shouldEmitConvergenceTokens())
1411 ConvergenceTokenStack.push_back(Elt: emitConvergenceLoopToken(BB: CondBlock));
1412
1413 const SourceRange &R = S.getSourceRange();
1414 LoopStack.push(Header: CondBlock, Ctx&: CGM.getContext(), CGOpts: CGM.getCodeGenOpts(), Attrs: ForAttrs,
1415 StartLoc: SourceLocToDebugLoc(Location: R.getBegin()),
1416 EndLoc: SourceLocToDebugLoc(Location: R.getEnd()));
1417
1418 // If there are any cleanups between here and the loop-exit scope,
1419 // create a block to stage a loop exit along.
1420 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
1421 if (hasSkipCounter(S: &S) || ForScope.requiresCleanups())
1422 ExitBlock = createBasicBlock(name: "for.cond.cleanup");
1423
1424 // The loop body, consisting of the specified body and the loop variable.
1425 llvm::BasicBlock *ForBody = createBasicBlock(name: "for.body");
1426
1427 // The body is executed if the expression, contextually converted
1428 // to bool, is true.
1429 llvm::Value *BoolCondVal = EvaluateExprAsBool(E: S.getCond());
1430 llvm::MDNode *Weights =
1431 createProfileWeightsForLoop(Cond: S.getCond(), LoopCount: getProfileCount(S: S.getBody()));
1432 if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
1433 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
1434 Cond: BoolCondVal, LH: Stmt::getLikelihood(S: S.getBody()));
1435 auto *I = Builder.CreateCondBr(Cond: BoolCondVal, True: ForBody, False: ExitBlock, BranchWeights: Weights);
1436 // Key Instructions: Emit the condition and branch as separate atoms to
1437 // match existing loop stepping behaviour. FIXME: We could have the branch as
1438 // the backup location for the condition, which would probably be a better
1439 // experience.
1440 if (auto *CondI = dyn_cast<llvm::Instruction>(Val: BoolCondVal))
1441 addInstToNewSourceAtom(KeyInstruction: CondI, Backup: nullptr);
1442 addInstToNewSourceAtom(KeyInstruction: I, Backup: nullptr);
1443
1444 if (ExitBlock != LoopExit.getBlock()) {
1445 EmitBlock(BB: ExitBlock);
1446 incrementProfileCounter(ExecSkip: UseSkipPath, S: &S);
1447 EmitBranchThroughCleanup(Dest: LoopExit);
1448 }
1449
1450 EmitBlock(BB: ForBody);
1451 incrementProfileCounter(ExecSkip: UseExecPath, S: &S);
1452
1453 // Create a block for the increment. In case of a 'continue', we jump there.
1454 JumpDest Continue = getJumpDestInCurrentScope(Name: "for.inc");
1455
1456 // Store the blocks to use for break and continue.
1457 BreakContinueStack.push_back(Elt: BreakContinue(S, LoopExit, Continue));
1458
1459 {
1460 // Create a separate cleanup scope for the loop variable and body.
1461 LexicalScope BodyScope(*this, S.getSourceRange());
1462 EmitStmt(S: S.getLoopVarStmt());
1463 EmitStmt(S: S.getBody());
1464 }
1465 // The last block in the loop's body (which unconditionally branches to the
1466 // `inc` block if there is one).
1467 auto *FinalBodyBB = Builder.GetInsertBlock();
1468
1469 EmitStopPoint(S: &S);
1470 // If there is an increment, emit it next.
1471 EmitBlock(BB: Continue.getBlock());
1472 EmitStmt(S: S.getInc());
1473
1474 BreakContinueStack.pop_back();
1475
1476 EmitBranch(Target: CondBlock);
1477
1478 ForScope.ForceCleanup();
1479
1480 LoopStack.pop();
1481
1482 // Emit the fall-through block.
1483 EmitBlock(BB: LoopExit.getBlock(), IsFinished: true);
1484
1485 if (CGM.shouldEmitConvergenceTokens())
1486 ConvergenceTokenStack.pop_back();
1487
1488 if (FinalBodyBB) {
1489 // We want the for closing brace to be step-able on to match existing
1490 // behaviour.
1491 addInstToNewSourceAtom(KeyInstruction: FinalBodyBB->getTerminator(), Backup: nullptr);
1492 }
1493}
1494
1495void CodeGenFunction::EmitCXXExpansionStmtInstantiation(
1496 const CXXExpansionStmtInstantiation &S) {
1497 LexicalScope Scope(*this, S.getSourceRange());
1498
1499 for (const Stmt *DS : S.getPreambleStmts())
1500 EmitStmt(S: DS);
1501
1502 if (S.getInstantiations().empty())
1503 return;
1504
1505 JumpDest ExpandExit = getJumpDestInCurrentScope(Name: "expand.end");
1506 JumpDest ContinueDest;
1507 for (auto [N, Inst] : enumerate(First: S.getInstantiations())) {
1508 if (N == S.getInstantiations().size() - 1)
1509 ContinueDest = ExpandExit;
1510 else
1511 ContinueDest = getJumpDestInCurrentScope(Name: "expand.next");
1512
1513 LexicalScope ExpansionScope(*this, Inst->getSourceRange());
1514 BreakContinueStack.push_back(Elt: BreakContinue(S, ExpandExit, ContinueDest));
1515 EmitStmt(S: Inst);
1516 BreakContinueStack.pop_back();
1517 EmitBlock(BB: ContinueDest.getBlock(), IsFinished: true);
1518 }
1519}
1520
1521void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
1522 if (RV.isScalar()) {
1523 Builder.CreateStore(Val: RV.getScalarVal(), Addr: ReturnValue);
1524 } else if (RV.isAggregate()) {
1525 LValue Dest = MakeAddrLValue(Addr: ReturnValue, T: Ty);
1526 LValue Src = MakeAddrLValue(Addr: RV.getAggregateAddress(), T: Ty);
1527 EmitAggregateCopy(Dest, Src, EltTy: Ty, MayOverlap: getOverlapForReturnValue());
1528 } else {
1529 EmitStoreOfComplex(V: RV.getComplexVal(), dest: MakeAddrLValue(Addr: ReturnValue, T: Ty),
1530 /*init*/ isInit: true);
1531 }
1532 EmitBranchThroughCleanup(Dest: ReturnBlock);
1533}
1534
1535namespace {
1536// RAII struct used to save and restore a return statment's result expression.
1537struct SaveRetExprRAII {
1538 SaveRetExprRAII(const Expr *RetExpr, CodeGenFunction &CGF)
1539 : OldRetExpr(CGF.RetExpr), CGF(CGF) {
1540 CGF.RetExpr = RetExpr;
1541 }
1542 ~SaveRetExprRAII() { CGF.RetExpr = OldRetExpr; }
1543 const Expr *OldRetExpr;
1544 CodeGenFunction &CGF;
1545};
1546} // namespace
1547
1548/// Determine if the given call uses the swiftasync calling convention.
1549static bool isSwiftAsyncCallee(const CallExpr *CE) {
1550 auto calleeQualType = CE->getCallee()->getType();
1551 const FunctionType *calleeType = nullptr;
1552 if (calleeQualType->isFunctionPointerType() ||
1553 calleeQualType->isFunctionReferenceType() ||
1554 calleeQualType->isBlockPointerType() ||
1555 calleeQualType->isMemberFunctionPointerType()) {
1556 calleeType = calleeQualType->getPointeeType()->castAs<FunctionType>();
1557 } else if (auto *ty = dyn_cast<FunctionType>(Val&: calleeQualType)) {
1558 calleeType = ty;
1559 } else if (auto CMCE = dyn_cast<CXXMemberCallExpr>(Val: CE)) {
1560 if (auto methodDecl = CMCE->getMethodDecl()) {
1561 // getMethodDecl() doesn't handle member pointers at the moment.
1562 calleeType = methodDecl->getType()->castAs<FunctionType>();
1563 } else {
1564 return false;
1565 }
1566 } else {
1567 return false;
1568 }
1569 return calleeType->getCallConv() == CallingConv::CC_SwiftAsync;
1570}
1571
1572/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
1573/// if the function returns void, or may be missing one if the function returns
1574/// non-void. Fun stuff :).
1575void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
1576 ApplyAtomGroup Grp(getDebugInfo());
1577 if (requiresReturnValueCheck()) {
1578 llvm::Constant *SLoc = EmitCheckSourceLocation(Loc: S.getBeginLoc());
1579 auto *SLocPtr =
1580 new llvm::GlobalVariable(CGM.getModule(), SLoc->getType(), false,
1581 llvm::GlobalVariable::PrivateLinkage, SLoc);
1582 SLocPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1583 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV: SLocPtr);
1584 assert(ReturnLocation.isValid() && "No valid return location");
1585 Builder.CreateStore(Val: SLocPtr, Addr: ReturnLocation);
1586 }
1587
1588 // Returning from an outlined SEH helper is UB, and we already warn on it.
1589 if (IsOutlinedSEHHelper) {
1590 Builder.CreateUnreachable();
1591 Builder.ClearInsertionPoint();
1592 }
1593
1594 // Emit the result value, even if unused, to evaluate the side effects.
1595 const Expr *RV = S.getRetValue();
1596
1597 // Record the result expression of the return statement. The recorded
1598 // expression is used to determine whether a block capture's lifetime should
1599 // end at the end of the full expression as opposed to the end of the scope
1600 // enclosing the block expression.
1601 //
1602 // This permits a small, easily-implemented exception to our over-conservative
1603 // rules about not jumping to statements following block literals with
1604 // non-trivial cleanups.
1605 SaveRetExprRAII SaveRetExpr(RV, *this);
1606
1607 RunCleanupsScope cleanupScope(*this);
1608 if (const auto *EWC = dyn_cast_or_null<ExprWithCleanups>(Val: RV))
1609 RV = EWC->getSubExpr();
1610
1611 // If we're in a swiftasynccall function, and the return expression is a
1612 // call to a swiftasynccall function, mark the call as the musttail call.
1613 std::optional<llvm::SaveAndRestore<const CallExpr *>> SaveMustTail;
1614 if (RV && CurFnInfo &&
1615 CurFnInfo->getASTCallingConvention() == CallingConv::CC_SwiftAsync) {
1616 if (auto CE = dyn_cast<CallExpr>(Val: RV)) {
1617 if (isSwiftAsyncCallee(CE)) {
1618 SaveMustTail.emplace(args&: MustTailCall, args&: CE);
1619 }
1620 }
1621 }
1622
1623 // FIXME: Clean this up by using an LValue for ReturnTemp,
1624 // EmitStoreThroughLValue, and EmitAnyExpr.
1625 // Check if the NRVO candidate was not globalized in OpenMP mode.
1626 if (getLangOpts().ElideConstructors && S.getNRVOCandidate() &&
1627 S.getNRVOCandidate()->isNRVOVariable() &&
1628 (!getLangOpts().OpenMP ||
1629 !CGM.getOpenMPRuntime()
1630 .getAddressOfLocalVariable(CGF&: *this, VD: S.getNRVOCandidate())
1631 .isValid())) {
1632 // Apply the named return value optimization for this return statement,
1633 // which means doing nothing: the appropriate result has already been
1634 // constructed into the NRVO variable.
1635
1636 // If there is an NRVO flag for this variable, set it to 1 into indicate
1637 // that the cleanup code should not destroy the variable.
1638 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
1639 Builder.CreateFlagStore(Value: Builder.getTrue(), Addr: NRVOFlag);
1640 } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) {
1641 // Make sure not to return anything, but evaluate the expression
1642 // for side effects.
1643 if (RV) {
1644 EmitAnyExpr(E: RV);
1645 }
1646 } else if (!RV) {
1647 // Do nothing (return value is left uninitialized)
1648 } else if (FnRetTy->isReferenceType()) {
1649 // If this function returns a reference, take the address of the expression
1650 // rather than the value.
1651 RValue Result = EmitReferenceBindingToExpr(E: RV);
1652 auto *I = Builder.CreateStore(Val: Result.getScalarVal(), Addr: ReturnValue);
1653 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: I->getValueOperand());
1654 } else {
1655 switch (getEvaluationKind(T: RV->getType())) {
1656 case TEK_Scalar: {
1657 llvm::Value *Ret = EmitScalarExpr(E: RV);
1658 if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
1659 EmitStoreOfScalar(value: Ret, lvalue: MakeAddrLValue(Addr: ReturnValue, T: RV->getType()),
1660 /*isInit*/ true);
1661 } else {
1662 auto *I = Builder.CreateStore(Val: Ret, Addr: ReturnValue);
1663 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: I->getValueOperand());
1664 }
1665 break;
1666 }
1667 case TEK_Complex:
1668 EmitComplexExprIntoLValue(E: RV, dest: MakeAddrLValue(Addr: ReturnValue, T: RV->getType()),
1669 /*isInit*/ true);
1670 break;
1671 case TEK_Aggregate:
1672 EmitAggExpr(E: RV, AS: AggValueSlot::forAddr(
1673 addr: ReturnValue, quals: Qualifiers(),
1674 isDestructed: AggValueSlot::IsDestructed,
1675 needsGC: AggValueSlot::DoesNotNeedGCBarriers,
1676 isAliased: AggValueSlot::IsNotAliased,
1677 mayOverlap: getOverlapForReturnValue()));
1678 break;
1679 }
1680 }
1681
1682 ++NumReturnExprs;
1683 if (!RV || RV->isEvaluatable(Ctx: getContext()))
1684 ++NumSimpleReturnExprs;
1685
1686 cleanupScope.ForceCleanup();
1687 EmitBranchThroughCleanup(Dest: ReturnBlock);
1688}
1689
1690void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
1691 // As long as debug info is modeled with instructions, we have to ensure we
1692 // have a place to insert here and write the stop point here.
1693 if (HaveInsertPoint())
1694 EmitStopPoint(S: &S);
1695
1696 for (const auto *I : S.decls())
1697 EmitDecl(D: *I, /*EvaluateConditionDecl=*/true);
1698}
1699
1700auto CodeGenFunction::GetDestForLoopControlStmt(const LoopControlStmt &S)
1701 -> const BreakContinue * {
1702 if (!S.hasLabelTarget())
1703 return &BreakContinueStack.back();
1704
1705 const Stmt *LoopOrSwitch = S.getNamedLoopOrSwitch();
1706 assert(LoopOrSwitch && "break/continue target not set?");
1707 for (const BreakContinue &BC : llvm::reverse(C&: BreakContinueStack))
1708 if (BC.LoopOrSwitch == LoopOrSwitch)
1709 return &BC;
1710
1711 llvm_unreachable("break/continue target not found");
1712}
1713
1714void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
1715 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1716
1717 // If this code is reachable then emit a stop point (if generating
1718 // debug info). We have to do this ourselves because we are on the
1719 // "simple" statement path.
1720 if (HaveInsertPoint())
1721 EmitStopPoint(S: &S);
1722
1723 ApplyAtomGroup Grp(getDebugInfo());
1724 EmitBranchThroughCleanup(Dest: GetDestForLoopControlStmt(S)->BreakBlock);
1725}
1726
1727void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
1728 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1729
1730 // If this code is reachable then emit a stop point (if generating
1731 // debug info). We have to do this ourselves because we are on the
1732 // "simple" statement path.
1733 if (HaveInsertPoint())
1734 EmitStopPoint(S: &S);
1735
1736 ApplyAtomGroup Grp(getDebugInfo());
1737 EmitBranchThroughCleanup(Dest: GetDestForLoopControlStmt(S)->ContinueBlock);
1738}
1739
1740/// EmitCaseStmtRange - If case statement range is not too big then
1741/// add multiple cases to switch instruction, one for each value within
1742/// the range. If range is too big then emit "if" condition check.
1743void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S,
1744 ArrayRef<const Attr *> Attrs) {
1745 assert(S.getRHS() && "Expected RHS value in CaseStmt");
1746
1747 llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(Ctx: getContext());
1748 llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(Ctx: getContext());
1749
1750 // Emit the code for this case. We do this first to make sure it is
1751 // properly chained from our predecessor before generating the
1752 // switch machinery to enter this block.
1753 llvm::BasicBlock *CaseDest = createBasicBlock(name: "sw.bb");
1754 EmitBlockWithFallThrough(BB: CaseDest, S: &S);
1755 EmitStmt(S: S.getSubStmt());
1756
1757 // If range is empty, do nothing.
1758 if (LHS.isSigned() ? RHS.slt(RHS: LHS) : RHS.ult(RHS: LHS))
1759 return;
1760
1761 Stmt::Likelihood LH = Stmt::getLikelihood(Attrs);
1762 llvm::APInt Range = RHS - LHS;
1763 // FIXME: parameters such as this should not be hardcoded.
1764 if (Range.getBitWidth() < 7 ||
1765 Range.ult(RHS: llvm::APInt(Range.getBitWidth(), 64))) {
1766 // Range is small enough to add multiple switch instruction cases.
1767 uint64_t Total = getProfileCount(S: &S);
1768 unsigned NCases = Range.getZExtValue() + 1;
1769 // We only have one region counter for the entire set of cases here, so we
1770 // need to divide the weights evenly between the generated cases, ensuring
1771 // that the total weight is preserved. E.g., a weight of 5 over three cases
1772 // will be distributed as weights of 2, 2, and 1.
1773 uint64_t Weight = Total / NCases, Rem = Total % NCases;
1774 for (unsigned I = 0; I != NCases; ++I) {
1775 if (SwitchWeights)
1776 SwitchWeights->push_back(Elt: Weight + (Rem ? 1 : 0));
1777 else if (SwitchLikelihood)
1778 SwitchLikelihood->push_back(Elt: LH);
1779
1780 if (Rem)
1781 Rem--;
1782 SwitchInsn->addCase(OnVal: Builder.getInt(AI: LHS), Dest: CaseDest);
1783 ++LHS;
1784 }
1785 return;
1786 }
1787
1788 // The range is too big. Emit "if" condition into a new block,
1789 // making sure to save and restore the current insertion point.
1790 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
1791
1792 // Push this test onto the chain of range checks (which terminates
1793 // in the default basic block). The switch's default will be changed
1794 // to the top of this chain after switch emission is complete.
1795 llvm::BasicBlock *FalseDest = CaseRangeBlock;
1796 CaseRangeBlock = createBasicBlock(name: "sw.caserange");
1797
1798 CurFn->insert(Position: CurFn->end(), BB: CaseRangeBlock);
1799 Builder.SetInsertPoint(CaseRangeBlock);
1800
1801 // Emit range check.
1802 llvm::Value *Diff =
1803 Builder.CreateSub(LHS: SwitchInsn->getCondition(), RHS: Builder.getInt(AI: LHS));
1804 llvm::Value *Cond =
1805 Builder.CreateICmpULE(LHS: Diff, RHS: Builder.getInt(AI: Range), Name: "inbounds");
1806
1807 llvm::MDNode *Weights = nullptr;
1808 if (SwitchWeights) {
1809 uint64_t ThisCount = getProfileCount(S: &S);
1810 uint64_t DefaultCount = (*SwitchWeights)[0];
1811 Weights = createProfileWeights(TrueCount: ThisCount, FalseCount: DefaultCount);
1812
1813 // Since we're chaining the switch default through each large case range, we
1814 // need to update the weight for the default, ie, the first case, to include
1815 // this case.
1816 (*SwitchWeights)[0] += ThisCount;
1817 } else if (SwitchLikelihood)
1818 Cond = emitCondLikelihoodViaExpectIntrinsic(Cond, LH);
1819
1820 Builder.CreateCondBr(Cond, True: CaseDest, False: FalseDest, BranchWeights: Weights);
1821
1822 // Restore the appropriate insertion point.
1823 if (RestoreBB)
1824 Builder.SetInsertPoint(RestoreBB);
1825 else
1826 Builder.ClearInsertionPoint();
1827}
1828
1829void CodeGenFunction::EmitCaseStmt(const CaseStmt &S,
1830 ArrayRef<const Attr *> Attrs) {
1831 // If there is no enclosing switch instance that we're aware of, then this
1832 // case statement and its block can be elided. This situation only happens
1833 // when we've constant-folded the switch, are emitting the constant case,
1834 // and part of the constant case includes another case statement. For
1835 // instance: switch (4) { case 4: do { case 5: } while (1); }
1836 if (!SwitchInsn) {
1837 EmitStmt(S: S.getSubStmt());
1838 return;
1839 }
1840
1841 // Handle case ranges.
1842 if (S.getRHS()) {
1843 EmitCaseStmtRange(S, Attrs);
1844 return;
1845 }
1846
1847 llvm::ConstantInt *CaseVal =
1848 Builder.getInt(AI: S.getLHS()->EvaluateKnownConstInt(Ctx: getContext()));
1849
1850 // Emit debuginfo for the case value if it is an enum value.
1851 const ConstantExpr *CE;
1852 if (auto ICE = dyn_cast<ImplicitCastExpr>(Val: S.getLHS()))
1853 CE = dyn_cast<ConstantExpr>(Val: ICE->getSubExpr());
1854 else
1855 CE = dyn_cast<ConstantExpr>(Val: S.getLHS());
1856 if (CE) {
1857 if (auto DE = dyn_cast<DeclRefExpr>(Val: CE->getSubExpr()))
1858 if (CGDebugInfo *Dbg = getDebugInfo())
1859 if (CGM.getCodeGenOpts().hasReducedDebugInfo())
1860 Dbg->EmitGlobalVariable(VD: DE->getDecl(),
1861 Init: APValue(llvm::APSInt(CaseVal->getValue())));
1862 }
1863
1864 if (SwitchLikelihood)
1865 SwitchLikelihood->push_back(Elt: Stmt::getLikelihood(Attrs));
1866
1867 // If the body of the case is just a 'break', try to not emit an empty block.
1868 // If we're profiling or we're not optimizing, leave the block in for better
1869 // debug and coverage analysis.
1870 if (!CGM.getCodeGenOpts().hasProfileClangInstr() &&
1871 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1872 isa<BreakStmt>(Val: S.getSubStmt())) {
1873 JumpDest Block = BreakContinueStack.back().BreakBlock;
1874
1875 // Only do this optimization if there are no cleanups that need emitting.
1876 if (isObviouslyBranchWithoutCleanups(Dest: Block)) {
1877 if (SwitchWeights)
1878 SwitchWeights->push_back(Elt: getProfileCount(S: &S));
1879 SwitchInsn->addCase(OnVal: CaseVal, Dest: Block.getBlock());
1880
1881 // If there was a fallthrough into this case, make sure to redirect it to
1882 // the end of the switch as well.
1883 if (Builder.GetInsertBlock()) {
1884 Builder.CreateBr(Dest: Block.getBlock());
1885 Builder.ClearInsertionPoint();
1886 }
1887 return;
1888 }
1889 }
1890
1891 llvm::BasicBlock *CaseDest = createBasicBlock(name: "sw.bb");
1892 EmitBlockWithFallThrough(BB: CaseDest, S: &S);
1893 if (SwitchWeights)
1894 SwitchWeights->push_back(Elt: getProfileCount(S: &S));
1895 SwitchInsn->addCase(OnVal: CaseVal, Dest: CaseDest);
1896
1897 // Recursively emitting the statement is acceptable, but is not wonderful for
1898 // code where we have many case statements nested together, i.e.:
1899 // case 1:
1900 // case 2:
1901 // case 3: etc.
1902 // Handling this recursively will create a new block for each case statement
1903 // that falls through to the next case which is IR intensive. It also causes
1904 // deep recursion which can run into stack depth limitations. Handle
1905 // sequential non-range case statements specially.
1906 //
1907 // TODO When the next case has a likelihood attribute the code returns to the
1908 // recursive algorithm. Maybe improve this case if it becomes common practice
1909 // to use a lot of attributes.
1910 const CaseStmt *CurCase = &S;
1911 const CaseStmt *NextCase = dyn_cast<CaseStmt>(Val: S.getSubStmt());
1912
1913 // Otherwise, iteratively add consecutive cases to this switch stmt.
1914 while (NextCase && NextCase->getRHS() == nullptr) {
1915 CurCase = NextCase;
1916 llvm::ConstantInt *CaseVal =
1917 Builder.getInt(AI: CurCase->getLHS()->EvaluateKnownConstInt(Ctx: getContext()));
1918
1919 if (SwitchWeights)
1920 SwitchWeights->push_back(Elt: getProfileCount(S: NextCase));
1921 if (CGM.getCodeGenOpts().hasProfileClangInstr()) {
1922 CaseDest = createBasicBlock(name: "sw.bb");
1923 EmitBlockWithFallThrough(BB: CaseDest, S: CurCase);
1924 }
1925 // Since this loop is only executed when the CaseStmt has no attributes
1926 // use a hard-coded value.
1927 if (SwitchLikelihood)
1928 SwitchLikelihood->push_back(Elt: Stmt::LH_None);
1929
1930 SwitchInsn->addCase(OnVal: CaseVal, Dest: CaseDest);
1931 NextCase = dyn_cast<CaseStmt>(Val: CurCase->getSubStmt());
1932 }
1933
1934 // Generate a stop point for debug info if the case statement is
1935 // followed by a default statement. A fallthrough case before a
1936 // default case gets its own branch target.
1937 if (CurCase->getSubStmt()->getStmtClass() == Stmt::DefaultStmtClass)
1938 EmitStopPoint(S: CurCase);
1939
1940 // Normal default recursion for non-cases.
1941 EmitStmt(S: CurCase->getSubStmt());
1942}
1943
1944void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S,
1945 ArrayRef<const Attr *> Attrs) {
1946 // If there is no enclosing switch instance that we're aware of, then this
1947 // default statement can be elided. This situation only happens when we've
1948 // constant-folded the switch.
1949 if (!SwitchInsn) {
1950 EmitStmt(S: S.getSubStmt());
1951 return;
1952 }
1953
1954 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1955 assert(DefaultBlock->empty() &&
1956 "EmitDefaultStmt: Default block already defined?");
1957
1958 if (SwitchLikelihood)
1959 SwitchLikelihood->front() = Stmt::getLikelihood(Attrs);
1960
1961 EmitBlockWithFallThrough(BB: DefaultBlock, S: &S);
1962
1963 EmitStmt(S: S.getSubStmt());
1964}
1965
1966namespace {
1967struct EmitDeferredStatement final : EHScopeStack::Cleanup {
1968 const DeferStmt &Stmt;
1969 EmitDeferredStatement(const DeferStmt *Stmt) : Stmt(*Stmt) {}
1970
1971 void Emit(CodeGenFunction &CGF, Flags) override {
1972 // Take care that any cleanups pushed by the body of a '_Defer' statement
1973 // don't clobber the current cleanup slot value.
1974 //
1975 // Assume we have a scope that pushes a cleanup; when that scope is exited,
1976 // we need to run that cleanup; this is accomplished by emitting the cleanup
1977 // into a separate block and then branching to that block at scope exit.
1978 //
1979 // Where this gets complicated is if we exit the scope in multiple different
1980 // ways; e.g. in a 'for' loop, we may exit the scope of its body by falling
1981 // off the end (in which case we need to run the cleanup and then branch to
1982 // the increment), or by 'break'ing out of the loop (in which case we need
1983 // to run the cleanup and then branch to the loop exit block); in both cases
1984 // we first branch to the cleanup block to run the cleanup, but the block we
1985 // need to jump to *after* running the cleanup is different.
1986 //
1987 // This is accomplished using a local integer variable called the 'cleanup
1988 // slot': before branching to the cleanup block, we store a value into that
1989 // slot. Then, in the cleanup block, after running the cleanup, we load the
1990 // value of that variable and 'switch' on it to branch to the appropriate
1991 // continuation block.
1992 //
1993 // The problem that arises once '_Defer' statements are involved is that the
1994 // body of a '_Defer' is an arbitrary statement which itself can create more
1995 // cleanups. This means we may end up overwriting the cleanup slot before we
1996 // ever have a chance to 'switch' on it, which means that once we *do* get
1997 // to the 'switch', we end up in whatever block the cleanup code happened to
1998 // pick as the default 'switch' exit label!
1999 //
2000 // That is, what is normally supposed to happen is something like:
2001 //
2002 // 1. Store 'X' to cleanup slot.
2003 // 2. Branch to cleanup block.
2004 // 3. Execute cleanup.
2005 // 4. Read value from cleanup slot.
2006 // 5. Branch to the block associated with 'X'.
2007 //
2008 // But if we encounter a _Defer' statement that contains a cleanup, then
2009 // what might instead happen is:
2010 //
2011 // 1. Store 'X' to cleanup slot.
2012 // 2. Branch to cleanup block.
2013 // 3. Execute cleanup; this ends up pushing another cleanup, so:
2014 // 3a. Store 'Y' to cleanup slot.
2015 // 3b. Run steps 2–5 recursively.
2016 // 4. Read value from cleanup slot, which is now 'Y' instead of 'X'.
2017 // 5. Branch to the block associated with 'Y'... which doesn't even
2018 // exist because the value 'Y' is only meaningful for the inner
2019 // cleanup. The result is we just branch 'somewhere random'.
2020 //
2021 // The rest of the cleanup code simply isn't prepared to handle this case
2022 // because most other cleanups can't push more cleanups, and thus, emitting
2023 // other cleanups generally cannot clobber the cleanup slot.
2024 //
2025 // To prevent this from happening, save the current cleanup slot value and
2026 // restore it after emitting the '_Defer' statement.
2027 llvm::Value *SavedCleanupDest = nullptr;
2028 if (CGF.NormalCleanupDest.isValid())
2029 SavedCleanupDest =
2030 CGF.Builder.CreateLoad(Addr: CGF.NormalCleanupDest, Name: "cleanup.dest.saved");
2031
2032 CGF.EmitStmt(S: Stmt.getBody());
2033
2034 if (SavedCleanupDest && CGF.HaveInsertPoint())
2035 CGF.Builder.CreateStore(Val: SavedCleanupDest, Addr: CGF.NormalCleanupDest);
2036
2037 // Cleanups must end with an insert point.
2038 CGF.EnsureInsertPoint();
2039 }
2040};
2041} // namespace
2042
2043void CodeGenFunction::EmitDeferStmt(const DeferStmt &S) {
2044 EHStack.pushCleanup<EmitDeferredStatement>(Kind: NormalAndEHCleanup, A: &S);
2045}
2046
2047/// CollectStatementsForCase - Given the body of a 'switch' statement and a
2048/// constant value that is being switched on, see if we can dead code eliminate
2049/// the body of the switch to a simple series of statements to emit. Basically,
2050/// on a switch (5) we want to find these statements:
2051/// case 5:
2052/// printf(...); <--
2053/// ++i; <--
2054/// break;
2055///
2056/// and add them to the ResultStmts vector. If it is unsafe to do this
2057/// transformation (for example, one of the elided statements contains a label
2058/// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
2059/// should include statements after it (e.g. the printf() line is a substmt of
2060/// the case) then return CSFC_FallThrough. If we handled it and found a break
2061/// statement, then return CSFC_Success.
2062///
2063/// If Case is non-null, then we are looking for the specified case, checking
2064/// that nothing we jump over contains labels. If Case is null, then we found
2065/// the case and are looking for the break.
2066///
2067/// If the recursive walk actually finds our Case, then we set FoundCase to
2068/// true.
2069///
2070enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
2071static CSFC_Result CollectStatementsForCase(const Stmt *S,
2072 const SwitchCase *Case,
2073 bool &FoundCase,
2074 SmallVectorImpl<const Stmt*> &ResultStmts) {
2075 // If this is a null statement, just succeed.
2076 if (!S)
2077 return Case ? CSFC_Success : CSFC_FallThrough;
2078
2079 // If this is the switchcase (case 4: or default) that we're looking for, then
2080 // we're in business. Just add the substatement.
2081 if (const SwitchCase *SC = dyn_cast<SwitchCase>(Val: S)) {
2082 if (S == Case) {
2083 FoundCase = true;
2084 return CollectStatementsForCase(S: SC->getSubStmt(), Case: nullptr, FoundCase,
2085 ResultStmts);
2086 }
2087
2088 // Otherwise, this is some other case or default statement, just ignore it.
2089 return CollectStatementsForCase(S: SC->getSubStmt(), Case, FoundCase,
2090 ResultStmts);
2091 }
2092
2093 // If we are in the live part of the code and we found our break statement,
2094 // return a success!
2095 if (!Case && isa<BreakStmt>(Val: S))
2096 return CSFC_Success;
2097
2098 // If this is a switch statement, then it might contain the SwitchCase, the
2099 // break, or neither.
2100 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(Val: S)) {
2101 // Handle this as two cases: we might be looking for the SwitchCase (if so
2102 // the skipped statements must be skippable) or we might already have it.
2103 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
2104 bool StartedInLiveCode = FoundCase;
2105 unsigned StartSize = ResultStmts.size();
2106
2107 // If we've not found the case yet, scan through looking for it.
2108 if (Case) {
2109 // Keep track of whether we see a skipped declaration. The code could be
2110 // using the declaration even if it is skipped, so we can't optimize out
2111 // the decl if the kept statements might refer to it.
2112 bool HadSkippedDecl = false;
2113
2114 // If we're looking for the case, just see if we can skip each of the
2115 // substatements.
2116 for (; Case && I != E; ++I) {
2117 HadSkippedDecl |= CodeGenFunction::mightAddDeclToScope(S: *I);
2118
2119 switch (CollectStatementsForCase(S: *I, Case, FoundCase, ResultStmts)) {
2120 case CSFC_Failure: return CSFC_Failure;
2121 case CSFC_Success:
2122 // A successful result means that either 1) that the statement doesn't
2123 // have the case and is skippable, or 2) does contain the case value
2124 // and also contains the break to exit the switch. In the later case,
2125 // we just verify the rest of the statements are elidable.
2126 if (FoundCase) {
2127 // If we found the case and skipped declarations, we can't do the
2128 // optimization.
2129 if (HadSkippedDecl)
2130 return CSFC_Failure;
2131
2132 for (++I; I != E; ++I)
2133 if (CodeGenFunction::ContainsLabel(S: *I, IgnoreCaseStmts: true))
2134 return CSFC_Failure;
2135 return CSFC_Success;
2136 }
2137 break;
2138 case CSFC_FallThrough:
2139 // If we have a fallthrough condition, then we must have found the
2140 // case started to include statements. Consider the rest of the
2141 // statements in the compound statement as candidates for inclusion.
2142 assert(FoundCase && "Didn't find case but returned fallthrough?");
2143 // We recursively found Case, so we're not looking for it anymore.
2144 Case = nullptr;
2145
2146 // If we found the case and skipped declarations, we can't do the
2147 // optimization.
2148 if (HadSkippedDecl)
2149 return CSFC_Failure;
2150 break;
2151 }
2152 }
2153
2154 if (!FoundCase)
2155 return CSFC_Success;
2156
2157 assert(!HadSkippedDecl && "fallthrough after skipping decl");
2158 }
2159
2160 // If we have statements in our range, then we know that the statements are
2161 // live and need to be added to the set of statements we're tracking.
2162 bool AnyDecls = false;
2163 for (; I != E; ++I) {
2164 AnyDecls |= CodeGenFunction::mightAddDeclToScope(S: *I);
2165
2166 switch (CollectStatementsForCase(S: *I, Case: nullptr, FoundCase, ResultStmts)) {
2167 case CSFC_Failure: return CSFC_Failure;
2168 case CSFC_FallThrough:
2169 // A fallthrough result means that the statement was simple and just
2170 // included in ResultStmt, keep adding them afterwards.
2171 break;
2172 case CSFC_Success:
2173 // A successful result means that we found the break statement and
2174 // stopped statement inclusion. We just ensure that any leftover stmts
2175 // are skippable and return success ourselves.
2176 for (++I; I != E; ++I)
2177 if (CodeGenFunction::ContainsLabel(S: *I, IgnoreCaseStmts: true))
2178 return CSFC_Failure;
2179 return CSFC_Success;
2180 }
2181 }
2182
2183 // If we're about to fall out of a scope without hitting a 'break;', we
2184 // can't perform the optimization if there were any decls in that scope
2185 // (we'd lose their end-of-lifetime).
2186 if (AnyDecls) {
2187 // If the entire compound statement was live, there's one more thing we
2188 // can try before giving up: emit the whole thing as a single statement.
2189 // We can do that unless the statement contains a 'break;'.
2190 // FIXME: Such a break must be at the end of a construct within this one.
2191 // We could emit this by just ignoring the BreakStmts entirely.
2192 if (StartedInLiveCode && !CodeGenFunction::containsBreak(S)) {
2193 ResultStmts.resize(N: StartSize);
2194 ResultStmts.push_back(Elt: S);
2195 } else {
2196 return CSFC_Failure;
2197 }
2198 }
2199
2200 return CSFC_FallThrough;
2201 }
2202
2203 // Okay, this is some other statement that we don't handle explicitly, like a
2204 // for statement or increment etc. If we are skipping over this statement,
2205 // just verify it doesn't have labels, which would make it invalid to elide.
2206 if (Case) {
2207 if (CodeGenFunction::ContainsLabel(S, IgnoreCaseStmts: true))
2208 return CSFC_Failure;
2209 return CSFC_Success;
2210 }
2211
2212 // Otherwise, we want to include this statement. Everything is cool with that
2213 // so long as it doesn't contain a break out of the switch we're in.
2214 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
2215
2216 // Otherwise, everything is great. Include the statement and tell the caller
2217 // that we fall through and include the next statement as well.
2218 ResultStmts.push_back(Elt: S);
2219 return CSFC_FallThrough;
2220}
2221
2222/// FindCaseStatementsForValue - Find the case statement being jumped to and
2223/// then invoke CollectStatementsForCase to find the list of statements to emit
2224/// for a switch on constant. See the comment above CollectStatementsForCase
2225/// for more details.
2226static bool FindCaseStatementsForValue(const SwitchStmt &S,
2227 const llvm::APSInt &ConstantCondValue,
2228 SmallVectorImpl<const Stmt*> &ResultStmts,
2229 ASTContext &C,
2230 const SwitchCase *&ResultCase) {
2231 // First step, find the switch case that is being branched to. We can do this
2232 // efficiently by scanning the SwitchCase list.
2233 const SwitchCase *Case = S.getSwitchCaseList();
2234 const DefaultStmt *DefaultCase = nullptr;
2235
2236 for (; Case; Case = Case->getNextSwitchCase()) {
2237 // It's either a default or case. Just remember the default statement in
2238 // case we're not jumping to any numbered cases.
2239 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Val: Case)) {
2240 DefaultCase = DS;
2241 continue;
2242 }
2243
2244 // Check to see if this case is the one we're looking for.
2245 const CaseStmt *CS = cast<CaseStmt>(Val: Case);
2246 // Don't handle case ranges yet.
2247 if (CS->getRHS()) return false;
2248
2249 // If we found our case, remember it as 'case'.
2250 if (CS->getLHS()->EvaluateKnownConstInt(Ctx: C) == ConstantCondValue)
2251 break;
2252 }
2253
2254 // If we didn't find a matching case, we use a default if it exists, or we
2255 // elide the whole switch body!
2256 if (!Case) {
2257 // It is safe to elide the body of the switch if it doesn't contain labels
2258 // etc. If it is safe, return successfully with an empty ResultStmts list.
2259 if (!DefaultCase)
2260 return !CodeGenFunction::ContainsLabel(S: &S);
2261 Case = DefaultCase;
2262 }
2263
2264 // Ok, we know which case is being jumped to, try to collect all the
2265 // statements that follow it. This can fail for a variety of reasons. Also,
2266 // check to see that the recursive walk actually found our case statement.
2267 // Insane cases like this can fail to find it in the recursive walk since we
2268 // don't handle every stmt kind:
2269 // switch (4) {
2270 // while (1) {
2271 // case 4: ...
2272 bool FoundCase = false;
2273 ResultCase = Case;
2274 return CollectStatementsForCase(S: S.getBody(), Case, FoundCase,
2275 ResultStmts) != CSFC_Failure &&
2276 FoundCase;
2277}
2278
2279static std::optional<SmallVector<uint64_t, 16>>
2280getLikelihoodWeights(ArrayRef<Stmt::Likelihood> Likelihoods) {
2281 // Are there enough branches to weight them?
2282 if (Likelihoods.size() <= 1)
2283 return std::nullopt;
2284
2285 uint64_t NumUnlikely = 0;
2286 uint64_t NumNone = 0;
2287 uint64_t NumLikely = 0;
2288 for (const auto LH : Likelihoods) {
2289 switch (LH) {
2290 case Stmt::LH_Unlikely:
2291 ++NumUnlikely;
2292 break;
2293 case Stmt::LH_None:
2294 ++NumNone;
2295 break;
2296 case Stmt::LH_Likely:
2297 ++NumLikely;
2298 break;
2299 }
2300 }
2301
2302 // Is there a likelihood attribute used?
2303 if (NumUnlikely == 0 && NumLikely == 0)
2304 return std::nullopt;
2305
2306 // When multiple cases share the same code they can be combined during
2307 // optimization. In that case the weights of the branch will be the sum of
2308 // the individual weights. Make sure the combined sum of all neutral cases
2309 // doesn't exceed the value of a single likely attribute.
2310 // The additions both avoid divisions by 0 and make sure the weights of None
2311 // don't exceed the weight of Likely.
2312 const uint64_t Likely = INT32_MAX / (NumLikely + 2);
2313 const uint64_t None = Likely / (NumNone + 1);
2314 const uint64_t Unlikely = 0;
2315
2316 SmallVector<uint64_t, 16> Result;
2317 Result.reserve(N: Likelihoods.size());
2318 for (const auto LH : Likelihoods) {
2319 switch (LH) {
2320 case Stmt::LH_Unlikely:
2321 Result.push_back(Elt: Unlikely);
2322 break;
2323 case Stmt::LH_None:
2324 Result.push_back(Elt: None);
2325 break;
2326 case Stmt::LH_Likely:
2327 Result.push_back(Elt: Likely);
2328 break;
2329 }
2330 }
2331
2332 return Result;
2333}
2334
2335void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
2336 // Handle nested switch statements.
2337 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
2338 SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
2339 SmallVector<Stmt::Likelihood, 16> *SavedSwitchLikelihood = SwitchLikelihood;
2340 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
2341
2342 // See if we can constant fold the condition of the switch and therefore only
2343 // emit the live case statement (if any) of the switch.
2344 llvm::APSInt ConstantCondValue;
2345 if (ConstantFoldsToSimpleInteger(Cond: S.getCond(), Result&: ConstantCondValue)) {
2346 SmallVector<const Stmt*, 4> CaseStmts;
2347 const SwitchCase *Case = nullptr;
2348 if (FindCaseStatementsForValue(S, ConstantCondValue, ResultStmts&: CaseStmts,
2349 C&: getContext(), ResultCase&: Case)) {
2350 if (Case)
2351 incrementProfileCounter(S: Case);
2352 RunCleanupsScope ExecutedScope(*this);
2353
2354 if (S.getInit())
2355 EmitStmt(S: S.getInit());
2356
2357 // Emit the condition variable if needed inside the entire cleanup scope
2358 // used by this special case for constant folded switches.
2359 if (S.getConditionVariable())
2360 EmitDecl(D: *S.getConditionVariable(), /*EvaluateConditionDecl=*/true);
2361
2362 // At this point, we are no longer "within" a switch instance, so
2363 // we can temporarily enforce this to ensure that any embedded case
2364 // statements are not emitted.
2365 SwitchInsn = nullptr;
2366
2367 // Okay, we can dead code eliminate everything except this case. Emit the
2368 // specified series of statements and we're good.
2369 for (const Stmt *CaseStmt : CaseStmts)
2370 EmitStmt(S: CaseStmt);
2371 incrementProfileCounter(S: &S);
2372 PGO->markStmtMaybeUsed(S: S.getBody());
2373
2374 // Now we want to restore the saved switch instance so that nested
2375 // switches continue to function properly
2376 SwitchInsn = SavedSwitchInsn;
2377
2378 return;
2379 }
2380 }
2381
2382 JumpDest SwitchExit = getJumpDestInCurrentScope(Name: "sw.epilog");
2383
2384 RunCleanupsScope ConditionScope(*this);
2385
2386 if (S.getInit()) {
2387 EmitStmt(S: S.getInit());
2388
2389 // The init statement may have cleared the insertion point (e.g. it ended in
2390 // a 'noreturn' call); the condition emitted below needs a valid one.
2391 EnsureInsertPoint();
2392 }
2393
2394 if (S.getConditionVariable())
2395 EmitDecl(D: *S.getConditionVariable());
2396 llvm::Value *CondV = EmitScalarExpr(E: S.getCond());
2397 MaybeEmitDeferredVarDeclInit(var: S.getConditionVariable());
2398
2399 // Create basic block to hold stuff that comes after switch
2400 // statement. We also need to create a default block now so that
2401 // explicit case ranges tests can have a place to jump to on
2402 // failure.
2403 llvm::BasicBlock *DefaultBlock = createBasicBlock(name: "sw.default");
2404
2405 // The dispatch is the jump that bypasses any declarations sitting between the
2406 // switch and its case labels, so the initialization goes here, ahead of the
2407 // switch instruction -- not at the case labels. A case label is also reached
2408 // by falling through from the case above it, and that edge bypasses nothing;
2409 // initializing there would clobber a variable the previous case had written.
2410 // The declarations are inside the body and so have no alloca yet, hence the
2411 // patch-it-in-later handling in EmitAutoVarAlloca.
2412 if (!Bypasses.isAlwaysBypassed())
2413 BypassingForwardJumps.push_back(Elt: {.Block: Builder.GetInsertBlock(), .Source: &S});
2414
2415 SwitchInsn = Builder.CreateSwitch(V: CondV, Dest: DefaultBlock);
2416 addInstToNewSourceAtom(KeyInstruction: SwitchInsn, Backup: CondV);
2417
2418 if (HLSLControlFlowAttr != HLSLControlFlowHintAttr::SpellingNotCalculated) {
2419 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2420 llvm::ConstantInt *BranchHintConstant =
2421 HLSLControlFlowAttr ==
2422 HLSLControlFlowHintAttr::Spelling::Microsoft_branch
2423 ? llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: 1)
2424 : llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: 2);
2425 llvm::Metadata *Vals[] = {MDHelper.createString(Str: "hlsl.controlflow.hint"),
2426 MDHelper.createConstant(C: BranchHintConstant)};
2427 SwitchInsn->setMetadata(Kind: "hlsl.controlflow.hint",
2428 Node: llvm::MDNode::get(Context&: CGM.getLLVMContext(), MDs: Vals));
2429 }
2430
2431 if (PGO->haveRegionCounts()) {
2432 // Walk the SwitchCase list to find how many there are.
2433 uint64_t DefaultCount = 0;
2434 unsigned NumCases = 0;
2435 for (const SwitchCase *Case = S.getSwitchCaseList();
2436 Case;
2437 Case = Case->getNextSwitchCase()) {
2438 if (isa<DefaultStmt>(Val: Case))
2439 DefaultCount = getProfileCount(S: Case);
2440 NumCases += 1;
2441 }
2442 SwitchWeights = new SmallVector<uint64_t, 16>();
2443 SwitchWeights->reserve(N: NumCases);
2444 // The default needs to be first. We store the edge count, so we already
2445 // know the right weight.
2446 SwitchWeights->push_back(Elt: DefaultCount);
2447 } else if (CGM.getCodeGenOpts().OptimizationLevel) {
2448 SwitchLikelihood = new SmallVector<Stmt::Likelihood, 16>();
2449 // Initialize the default case.
2450 SwitchLikelihood->push_back(Elt: Stmt::LH_None);
2451 }
2452
2453 CaseRangeBlock = DefaultBlock;
2454
2455 // Clear the insertion point to indicate we are in unreachable code.
2456 Builder.ClearInsertionPoint();
2457
2458 // All break statements jump to NextBlock. If BreakContinueStack is non-empty
2459 // then reuse last ContinueBlock.
2460 JumpDest OuterContinue;
2461 if (!BreakContinueStack.empty())
2462 OuterContinue = BreakContinueStack.back().ContinueBlock;
2463
2464 BreakContinueStack.push_back(Elt: BreakContinue(S, SwitchExit, OuterContinue));
2465
2466 // Emit switch body.
2467 EmitStmt(S: S.getBody());
2468
2469 BreakContinueStack.pop_back();
2470
2471 // Update the default block in case explicit case range tests have
2472 // been chained on top.
2473 SwitchInsn->setDefaultDest(CaseRangeBlock);
2474
2475 // If a default was never emitted:
2476 if (!DefaultBlock->getParent()) {
2477 // If we have cleanups, emit the default block so that there's a
2478 // place to jump through the cleanups from.
2479 if (ConditionScope.requiresCleanups()) {
2480 EmitBlock(BB: DefaultBlock);
2481
2482 // Otherwise, just forward the default block to the switch end.
2483 } else {
2484 DefaultBlock->replaceAllUsesWith(V: SwitchExit.getBlock());
2485 delete DefaultBlock;
2486 }
2487 }
2488
2489 ConditionScope.ForceCleanup();
2490
2491 // Close the last case (or DefaultBlock).
2492 EmitBranch(Target: SwitchExit.getBlock());
2493
2494 // Insert a False Counter if SwitchStmt doesn't have DefaultStmt.
2495 if (hasSkipCounter(S: S.getCond())) {
2496 auto *ImplicitDefaultBlock = createBasicBlock(name: "sw.false");
2497 EmitBlock(BB: ImplicitDefaultBlock);
2498 incrementProfileCounter(ExecSkip: UseSkipPath, S: S.getCond());
2499 Builder.CreateBr(Dest: SwitchInsn->getDefaultDest());
2500 SwitchInsn->setDefaultDest(ImplicitDefaultBlock);
2501 }
2502
2503 // Emit continuation.
2504 EmitBlock(BB: SwitchExit.getBlock(), IsFinished: true);
2505 incrementProfileCounter(S: &S);
2506
2507 // If the switch has a condition wrapped by __builtin_unpredictable,
2508 // create metadata that specifies that the switch is unpredictable.
2509 // Don't bother if not optimizing because that metadata would not be used.
2510 auto *Call = dyn_cast<CallExpr>(Val: S.getCond());
2511 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
2512 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: Call->getCalleeDecl());
2513 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
2514 llvm::MDBuilder MDHelper(getLLVMContext());
2515 SwitchInsn->setMetadata(KindID: llvm::LLVMContext::MD_unpredictable,
2516 Node: MDHelper.createUnpredictable());
2517 }
2518 }
2519
2520 if (SwitchWeights) {
2521 assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
2522 "switch weights do not match switch cases");
2523 // If there's only one jump destination there's no sense weighting it.
2524 if (SwitchWeights->size() > 1)
2525 SwitchInsn->setMetadata(KindID: llvm::LLVMContext::MD_prof,
2526 Node: createProfileWeights(Weights: *SwitchWeights));
2527 delete SwitchWeights;
2528 } else if (SwitchLikelihood) {
2529 assert(SwitchLikelihood->size() == 1 + SwitchInsn->getNumCases() &&
2530 "switch likelihoods do not match switch cases");
2531 std::optional<SmallVector<uint64_t, 16>> LHW =
2532 getLikelihoodWeights(Likelihoods: *SwitchLikelihood);
2533 if (LHW) {
2534 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2535 SwitchInsn->setMetadata(KindID: llvm::LLVMContext::MD_prof,
2536 Node: createProfileWeights(Weights: *LHW));
2537 }
2538 delete SwitchLikelihood;
2539 }
2540 SwitchInsn = SavedSwitchInsn;
2541 SwitchWeights = SavedSwitchWeights;
2542 SwitchLikelihood = SavedSwitchLikelihood;
2543 CaseRangeBlock = SavedCRBlock;
2544}
2545
2546std::pair<llvm::Value*, llvm::Type *> CodeGenFunction::EmitAsmInputLValue(
2547 const TargetInfo::ConstraintInfo &Info, LValue InputValue,
2548 QualType InputType, std::string &ConstraintStr, SourceLocation Loc) {
2549 if (Info.allowsRegister() || !Info.allowsMemory()) {
2550 if (CodeGenFunction::hasScalarEvaluationKind(T: InputType))
2551 return {EmitLoadOfLValue(V: InputValue, Loc).getScalarVal(), nullptr};
2552
2553 llvm::Type *Ty = ConvertType(T: InputType);
2554 uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
2555 if ((Size <= 64 && llvm::isPowerOf2_64(Value: Size)) ||
2556 getTargetHooks().isScalarizableAsmOperand(CGF&: *this, Ty)) {
2557 Ty = llvm::IntegerType::get(C&: getLLVMContext(), NumBits: Size);
2558
2559 return {Builder.CreateLoad(Addr: InputValue.getAddress().withElementType(ElemTy: Ty)),
2560 nullptr};
2561 }
2562 }
2563
2564 Address Addr = InputValue.getAddress();
2565 ConstraintStr += '*';
2566 return {InputValue.getPointer(CGF&: *this), Addr.getElementType()};
2567}
2568std::pair<llvm::Value *, llvm::Type *>
2569CodeGenFunction::EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
2570 const Expr *InputExpr,
2571 std::string &ConstraintStr) {
2572 // If this can't be a register or memory, i.e., has to be a constant
2573 // (immediate or symbolic), try to emit it as such.
2574 if (!Info.allowsRegister() && !Info.allowsMemory()) {
2575 if (Info.requiresImmediateConstant()) {
2576 Expr::EvalResult EVResult;
2577 InputExpr->EvaluateAsRValue(Result&: EVResult, Ctx: getContext(), InConstantContext: true);
2578
2579 llvm::APSInt IntResult;
2580 if (EVResult.Val.toIntegralConstant(Result&: IntResult, SrcTy: InputExpr->getType(),
2581 Ctx: getContext()))
2582 return {llvm::ConstantInt::get(Context&: getLLVMContext(), V: IntResult), nullptr};
2583 }
2584
2585 Expr::EvalResult Result;
2586 if (InputExpr->EvaluateAsInt(Result, Ctx: getContext()))
2587 return {llvm::ConstantInt::get(Context&: getLLVMContext(), V: Result.Val.getInt()),
2588 nullptr};
2589 }
2590
2591 if (Info.allowsRegister() || !Info.allowsMemory())
2592 if (CodeGenFunction::hasScalarEvaluationKind(T: InputExpr->getType()))
2593 return {EmitScalarExpr(E: InputExpr), nullptr};
2594 if (InputExpr->getStmtClass() == Expr::CXXThisExprClass)
2595 return {EmitScalarExpr(E: InputExpr), nullptr};
2596 InputExpr = InputExpr->IgnoreParenNoopCasts(Ctx: getContext());
2597 LValue Dest = EmitLValue(E: InputExpr);
2598 return EmitAsmInputLValue(Info, InputValue: Dest, InputType: InputExpr->getType(), ConstraintStr,
2599 Loc: InputExpr->getExprLoc());
2600}
2601
2602/// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
2603/// asm call instruction. The !srcloc MDNode contains a list of constant
2604/// integers which are the source locations of the start of each line in the
2605/// asm.
2606static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
2607 CodeGenFunction &CGF) {
2608 SmallVector<llvm::Metadata *, 8> Locs;
2609 // Add the location of the first line to the MDNode.
2610 Locs.push_back(Elt: llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::get(
2611 Ty: CGF.Int64Ty, V: Str->getBeginLoc().getRawEncoding())));
2612 StringRef StrVal = Str->getString();
2613 if (!StrVal.empty()) {
2614 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
2615 const LangOptions &LangOpts = CGF.CGM.getLangOpts();
2616 unsigned StartToken = 0;
2617 unsigned ByteOffset = 0;
2618
2619 // Add the location of the start of each subsequent line of the asm to the
2620 // MDNode.
2621 for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) {
2622 if (StrVal[i] != '\n') continue;
2623 SourceLocation LineLoc = Str->getLocationOfByte(
2624 ByteNo: i + 1, SM, Features: LangOpts, Target: CGF.getTarget(), StartToken: &StartToken, StartTokenByteOffset: &ByteOffset);
2625 Locs.push_back(Elt: llvm::ConstantAsMetadata::get(
2626 C: llvm::ConstantInt::get(Ty: CGF.Int64Ty, V: LineLoc.getRawEncoding())));
2627 }
2628 }
2629
2630 return llvm::MDNode::get(Context&: CGF.getLLVMContext(), MDs: Locs);
2631}
2632
2633namespace clang {
2634
2635/// This structure holds the information gathered about the constraints for an
2636/// inline assembly statement. It helps in separating the constraint processing
2637/// from the code generation.
2638class AsmConstraintsInfo {
2639 CodeGenFunction &CGF;
2640 CodeGenModule &CGM; // Per-module state.
2641 const AsmStmt &S;
2642 CGBuilderTy &Builder;
2643
2644 // The final asm string.
2645 std::string AsmString;
2646
2647 // The output and input constraints.
2648 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
2649 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
2650
2651 // Constraint strings.
2652 std::string Constraints;
2653 std::string InOutConstraints;
2654
2655 // Keep track of out constraints for tied input operand.
2656 std::vector<std::string> OutputConstraints;
2657
2658 // Keep track of argument types.
2659 std::vector<llvm::Value *> Args;
2660 std::vector<llvm::Type *> ArgTypes;
2661 std::vector<llvm::Type *> ArgElemTypes;
2662
2663 // Keep track of result register constraints.
2664 std::vector<LValue> ResultRegDests;
2665 std::vector<QualType> ResultRegQualTys;
2666 std::vector<llvm::Type *> ResultRegTypes;
2667 std::vector<llvm::Type *> ResultTruncRegTypes;
2668
2669 llvm::BitVector ResultTypeRequiresCast;
2670
2671 // Keep track of in/out constraints.
2672 std::vector<llvm::Value *> InOutArgs;
2673 std::vector<llvm::Type *> InOutArgTypes;
2674 std::vector<llvm::Type *> InOutArgElemTypes;
2675
2676 // Destination blocks for 'asm gotos'.
2677 llvm::BasicBlock *DefaultDest = nullptr;
2678 SmallVector<llvm::BasicBlock *, 3> IndirectDests;
2679
2680 std::vector<std::optional<std::pair<unsigned, unsigned>>> ResultBounds;
2681
2682 // An inline asm can be marked readonly if it meets the following
2683 // conditions:
2684 //
2685 // - it doesn't have any sideeffects
2686 // - it doesn't clobber memory
2687 // - it doesn't return a value by-reference
2688 //
2689 // It can be marked readnone if it doesn't have any input memory
2690 // constraints in addition to meeting the conditions listed above.
2691 bool ReadOnly = true;
2692 bool ReadNone = true;
2693
2694 bool GetOutputAndInputConstraints();
2695 void HandleOutputConstraints();
2696 void HandleMSStyleAsmBlob();
2697 void HandleInputConstraints();
2698 bool HandleLabels();
2699 bool HandleClobbers();
2700 void UpdateAsmCallInst(llvm::CallBase &Result, bool HasSideEffect,
2701 bool HasUnwindClobber, bool NoMerge, bool NoConvergent,
2702 std::vector<llvm::Value *> &RegResults);
2703 void EmitAsmStores(const llvm::ArrayRef<llvm::Value *> RegResults);
2704
2705 void EmitHipStdParUnsupportedAsm() {
2706 constexpr auto Name = "__ASM__hipstdpar_unsupported";
2707
2708 std::string Asm;
2709 if (auto GCCAsm = dyn_cast<GCCAsmStmt>(Val: &S))
2710 Asm = GCCAsm->getAsmString();
2711
2712 auto &Ctx = getLLVMContext();
2713 auto StrTy = llvm::ConstantDataArray::getString(Context&: Ctx, Initializer: Asm);
2714 auto FnTy = llvm::FunctionType::get(Result: llvm::Type::getVoidTy(C&: Ctx),
2715 Params: {StrTy->getType()}, isVarArg: false);
2716 auto UBF = CGM.getModule().getOrInsertFunction(Name, T: FnTy);
2717
2718 Builder.CreateCall(Callee: UBF, Args: {StrTy});
2719 }
2720
2721 ASTContext &getContext() { return CGF.getContext(); }
2722 llvm::LLVMContext &getLLVMContext() { return CGF.getLLVMContext(); }
2723 const TargetInfo &getTarget() const { return CGF.getTarget(); }
2724 const LangOptions &getLangOpts() const { return CGF.getLangOpts(); }
2725 const TargetCodeGenInfo &getTargetHooks() const {
2726 return CGM.getTargetCodeGenInfo();
2727 }
2728
2729public:
2730 AsmConstraintsInfo(CodeGenFunction &CGF, const AsmStmt &S)
2731 : CGF(CGF), CGM(CGF.CGM), S(S), Builder(CGF.Builder),
2732 AsmString(S.generateAsmString(C: CGF.getContext())) {}
2733
2734 void EmitAsmStmt();
2735};
2736
2737} // namespace clang
2738
2739void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
2740 // Pop all cleanup blocks at the end of the asm statement.
2741 CodeGenFunction::RunCleanupsScope Cleanups(*this);
2742
2743 // Get all the output and input constraints together.
2744 AsmConstraintsInfo AsmInfo(*this, S);
2745 AsmInfo.EmitAsmStmt();
2746}
2747
2748void AsmConstraintsInfo::EmitAsmStmt() {
2749 if (!GetOutputAndInputConstraints())
2750 return EmitHipStdParUnsupportedAsm();
2751
2752 // Handle output constraints.
2753 HandleOutputConstraints();
2754
2755 // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
2756 // to the return value slot. Only do this when returning in registers.
2757 HandleMSStyleAsmBlob();
2758
2759 // Handle input constraints.
2760 HandleInputConstraints();
2761
2762 // Handle 'asm goto' labels.
2763 bool IsGCCAsmGoto = HandleLabels();
2764
2765 // Handle any clobbers.
2766 bool HasUnwindClobber = HandleClobbers();
2767 assert(!(HasUnwindClobber && IsGCCAsmGoto) &&
2768 "unwind clobber can't be used with asm goto");
2769
2770 // Add machine specific clobbers
2771 std::string_view MachineClobbers = getTarget().getClobbers();
2772 if (!MachineClobbers.empty()) {
2773 if (!Constraints.empty())
2774 Constraints += ',';
2775 Constraints += MachineClobbers;
2776 }
2777
2778 llvm::Type *ResultType;
2779 if (ResultRegTypes.empty())
2780 ResultType = CGF.VoidTy;
2781 else if (ResultRegTypes.size() == 1)
2782 ResultType = ResultRegTypes[0];
2783 else
2784 ResultType = llvm::StructType::get(Context&: getLLVMContext(), Elements: ResultRegTypes);
2785
2786 llvm::FunctionType *FTy =
2787 llvm::FunctionType::get(Result: ResultType, Params: ArgTypes, isVarArg: false);
2788
2789 bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
2790
2791 llvm::InlineAsm::AsmDialect GnuAsmDialect =
2792 CGM.getCodeGenOpts().getInlineAsmDialect() == CodeGenOptions::IAD_ATT
2793 ? llvm::InlineAsm::AD_ATT
2794 : llvm::InlineAsm::AD_Intel;
2795 llvm::InlineAsm::AsmDialect AsmDialect =
2796 isa<MSAsmStmt>(Val: &S) ? llvm::InlineAsm::AD_Intel : GnuAsmDialect;
2797
2798 llvm::InlineAsm *IA = llvm::InlineAsm::get(
2799 Ty: FTy, AsmString, Constraints, hasSideEffects: HasSideEffect,
2800 /* IsAlignStack */ isAlignStack: false, asmDialect: AsmDialect, canThrow: HasUnwindClobber);
2801 std::vector<llvm::Value *> RegResults;
2802 llvm::CallBrInst *CBR;
2803 llvm::DenseMap<llvm::BasicBlock *, SmallVector<llvm::Value *, 4>>
2804 CBRRegResults;
2805
2806 if (IsGCCAsmGoto) {
2807 CBR = Builder.CreateCallBr(Callee: IA, DefaultDest, IndirectDests, Args);
2808 CGF.EmitBlock(BB: DefaultDest);
2809 UpdateAsmCallInst(Result&: *CBR, HasSideEffect,
2810 /*HasUnwindClobber=*/false, NoMerge: CGF.InNoMergeAttributedStmt,
2811 NoConvergent: CGF.InNoConvergentAttributedStmt, RegResults);
2812
2813 // Because we are emitting code top to bottom, we don't have enough
2814 // information at this point to know precisely whether we have a critical
2815 // edge. If we have outputs, split all indirect destinations.
2816 if (!RegResults.empty()) {
2817 unsigned I = 0;
2818 for (llvm::BasicBlock *Dest : CBR->getIndirectDests()) {
2819 llvm::Twine SynthName = Dest->getName() + ".split";
2820 llvm::BasicBlock *SynthBB = CGF.createBasicBlock(name: SynthName);
2821 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
2822 Builder.SetInsertPoint(SynthBB);
2823
2824 if (ResultRegTypes.size() == 1) {
2825 CBRRegResults[SynthBB].push_back(Elt: CBR);
2826 } else {
2827 for (unsigned J = 0, E = ResultRegTypes.size(); J != E; ++J) {
2828 llvm::Value *Tmp = Builder.CreateExtractValue(Agg: CBR, Idxs: J, Name: "asmresult");
2829 CBRRegResults[SynthBB].push_back(Elt: Tmp);
2830 }
2831 }
2832
2833 CGF.EmitBranch(Target: Dest);
2834 CGF.EmitBlock(BB: SynthBB);
2835 CBR->setIndirectDest(i: I++, B: SynthBB);
2836 }
2837 }
2838 } else if (HasUnwindClobber) {
2839 llvm::CallBase *Result = CGF.EmitCallOrInvoke(Callee: IA, Args, Name: "");
2840 UpdateAsmCallInst(Result&: *Result, HasSideEffect,
2841 /*HasUnwindClobber=*/true, NoMerge: CGF.InNoMergeAttributedStmt,
2842 NoConvergent: CGF.InNoConvergentAttributedStmt, RegResults);
2843 } else {
2844 llvm::CallInst *Result =
2845 Builder.CreateCall(Callee: IA, Args, OpBundles: CGF.getBundlesForFunclet(Callee: IA));
2846 UpdateAsmCallInst(Result&: *Result, HasSideEffect,
2847 /*HasUnwindClobber=*/false, NoMerge: CGF.InNoMergeAttributedStmt,
2848 NoConvergent: CGF.InNoConvergentAttributedStmt, RegResults);
2849 }
2850
2851 EmitAsmStores(RegResults);
2852
2853 // If this is an asm goto with outputs, repeat EmitAsmStores, but with a
2854 // different insertion point; one for each indirect destination and with
2855 // CBRRegResults rather than RegResults.
2856 if (IsGCCAsmGoto && !CBRRegResults.empty()) {
2857 for (llvm::BasicBlock *Succ : CBR->getIndirectDests()) {
2858 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
2859 Builder.SetInsertPoint(--(Succ->end()));
2860 EmitAsmStores(RegResults: CBRRegResults[Succ]);
2861 }
2862 }
2863}
2864
2865/// Gather and validate the output and input constraints for the given inline
2866/// assembly statement. This ensures that the constraints are valid for the
2867/// target and prepares them for further processing.
2868bool AsmConstraintsInfo::GetOutputAndInputConstraints() {
2869 bool IsValidTargetAsm = true;
2870 bool IsHipStdPar = getLangOpts().HIPStdPar && getLangOpts().CUDAIsDevice;
2871 for (unsigned I = 0, E = S.getNumOutputs(); I != E && IsValidTargetAsm; I++) {
2872 StringRef Name;
2873 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(Val: &S))
2874 Name = GAS->getOutputName(i: I);
2875
2876 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i: I), Name);
2877
2878 bool IsValid = getTarget().validateOutputConstraint(Info);
2879 if (IsHipStdPar && !IsValid)
2880 IsValidTargetAsm = false;
2881 else
2882 assert(IsValid && "Failed to parse output constraint");
2883
2884 OutputConstraintInfos.push_back(Elt: Info);
2885 }
2886
2887 for (unsigned I = 0, E = S.getNumInputs(); I != E && IsValidTargetAsm; I++) {
2888 StringRef Name;
2889 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(Val: &S))
2890 Name = GAS->getInputName(i: I);
2891
2892 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i: I), Name);
2893
2894 bool IsValid =
2895 getTarget().validateInputConstraint(OutputConstraints: OutputConstraintInfos, info&: Info);
2896 if (IsHipStdPar && !IsValid)
2897 IsValidTargetAsm = false;
2898 else
2899 assert(IsValid && "Failed to parse input constraint");
2900
2901 InputConstraintInfos.push_back(Elt: Info);
2902 }
2903
2904 return IsValidTargetAsm;
2905}
2906
2907/// Process the output constraints of an inline assembly statement. This method
2908/// handles the complexity of determining whether an output should be a
2909/// register or memory operand, manages tied operands, and prepares the
2910/// necessary arguments for the LLVM inline asm call.
2911void AsmConstraintsInfo::HandleOutputConstraints() {
2912 // Keep track of defined physregs.
2913 llvm::SmallSet<std::string, 8> PhysRegOutputs;
2914
2915 for (unsigned I = 0, E = S.getNumOutputs(); I != E; I++) {
2916 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[I];
2917
2918 // Simplify the output constraint.
2919 std::string OutputConstraint(S.getOutputConstraint(i: I));
2920 OutputConstraint = getTarget().simplifyConstraint(
2921 Constraint: StringRef(OutputConstraint).substr(Start: 1), OutCons: &OutputConstraintInfos);
2922
2923 const Expr *OutExpr = S.getOutputExpr(i: I);
2924 OutExpr = OutExpr->IgnoreParenNoopCasts(Ctx: getContext());
2925
2926 std::string GCCReg;
2927 OutputConstraint = S.addVariableConstraints(
2928 Constraint: OutputConstraint, AsmExpr: *OutExpr, Target: getTarget(), EarlyClobber: Info.earlyClobber(),
2929 UnsupportedCB: [&](const Stmt *UnspStmt, StringRef Msg) {
2930 CGM.ErrorUnsupported(S: UnspStmt, Type: Msg);
2931 },
2932 GCCReg: &GCCReg);
2933
2934 // Give an error on multiple outputs to same physreg.
2935 if (!GCCReg.empty() && !PhysRegOutputs.insert(V: GCCReg).second)
2936 CGM.Error(loc: S.getAsmLoc(), error: "multiple outputs to hard register: " + GCCReg);
2937
2938 OutputConstraints.push_back(x: OutputConstraint);
2939 LValue Dest = CGF.EmitLValue(E: OutExpr);
2940 if (!Constraints.empty())
2941 Constraints += ',';
2942
2943 // If this is a register output, then make the inline asm return it
2944 // by-value. If this is a memory result, return the value by-reference.
2945 QualType QTy = OutExpr->getType();
2946 const bool IsScalarOrAggregate =
2947 CodeGenFunction::hasScalarEvaluationKind(T: QTy) ||
2948 CodeGenFunction::hasAggregateEvaluationKind(T: QTy);
2949
2950 if (!Info.allowsMemory() && IsScalarOrAggregate) {
2951 Constraints += "=" + OutputConstraint;
2952 ResultRegQualTys.push_back(x: QTy);
2953 ResultRegDests.push_back(x: Dest);
2954
2955 ResultBounds.emplace_back(args: Info.getOutputOperandBounds());
2956
2957 llvm::Type *Ty = CGF.ConvertTypeForMem(T: QTy);
2958 const bool RequiresCast =
2959 Info.allowsRegister() &&
2960 (getTargetHooks().isScalarizableAsmOperand(CGF, Ty) ||
2961 Ty->isAggregateType());
2962
2963 ResultTruncRegTypes.push_back(x: Ty);
2964 ResultTypeRequiresCast.push_back(Val: RequiresCast);
2965
2966 if (RequiresCast) {
2967 if (unsigned Size = getContext().getTypeSize(T: QTy))
2968 Ty = llvm::IntegerType::get(C&: getLLVMContext(), NumBits: Size);
2969 else
2970 CGM.Error(loc: OutExpr->getExprLoc(), error: "output size should not be zero");
2971 }
2972
2973 ResultRegTypes.push_back(x: Ty);
2974
2975 // If this output is tied to an input, and if the input is larger, then
2976 // we need to set the actual result type of the inline asm node to be the
2977 // same as the input type.
2978 if (Info.hasMatchingInput()) {
2979 unsigned InputNo;
2980 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
2981 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
2982 if (Input.hasTiedOperand() && Input.getTiedOperand() == I)
2983 break;
2984 }
2985 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
2986
2987 QualType InputTy = S.getInputExpr(i: InputNo)->getType();
2988 QualType OutputType = OutExpr->getType();
2989
2990 uint64_t InputSize = getContext().getTypeSize(T: InputTy);
2991 if (getContext().getTypeSize(T: OutputType) < InputSize)
2992 // Form the asm to return the value as a larger integer or fp type.
2993 ResultRegTypes.back() = CGF.ConvertType(T: InputTy);
2994 }
2995
2996 if (llvm::Type *AdjTy = getTargetHooks().adjustInlineAsmType(
2997 CGF, Constraint: OutputConstraint, Ty: ResultRegTypes.back()))
2998 ResultRegTypes.back() = AdjTy;
2999 else
3000 CGM.getDiags().Report(Loc: S.getAsmLoc(),
3001 DiagID: diag::err_asm_invalid_type_in_input)
3002 << OutExpr->getType() << OutputConstraint;
3003
3004 // Update largest vector width for any vector types.
3005 if (auto *VT = dyn_cast<llvm::VectorType>(Val: ResultRegTypes.back()))
3006 CGF.LargestVectorWidth =
3007 std::max(a: (uint64_t)CGF.LargestVectorWidth,
3008 b: VT->getPrimitiveSizeInBits().getKnownMinValue());
3009 } else {
3010 Address DestAddr = Dest.getAddress();
3011
3012 // Matrix types in memory are represented by arrays, but accessed through
3013 // vector pointers, with the alignment specified on the access operation.
3014 // For inline assembly, update pointer arguments to use vector pointers.
3015 // Otherwise there will be a mis-match if the matrix is also an
3016 // input-argument which is represented as vector.
3017 if (isa<MatrixType>(Val: OutExpr->getType().getCanonicalType()))
3018 DestAddr =
3019 DestAddr.withElementType(ElemTy: CGF.ConvertType(T: OutExpr->getType()));
3020
3021 ArgTypes.push_back(x: DestAddr.getType());
3022 ArgElemTypes.push_back(x: DestAddr.getElementType());
3023 Args.push_back(x: DestAddr.emitRawPointer(CGF));
3024
3025 Constraints += "=*" + OutputConstraint;
3026 ReadOnly = false;
3027 ReadNone = false;
3028 }
3029
3030 if (!Info.isReadWrite())
3031 continue;
3032
3033 InOutConstraints += ',';
3034
3035 const Expr *InputExpr = S.getOutputExpr(i: I);
3036 llvm::Value *Arg;
3037 llvm::Type *ArgElemType;
3038 std::tie(args&: Arg, args&: ArgElemType) =
3039 CGF.EmitAsmInputLValue(Info, InputValue: Dest, InputType: InputExpr->getType(),
3040 ConstraintStr&: InOutConstraints, Loc: InputExpr->getExprLoc());
3041
3042 if (llvm::Type *AdjTy = getTargetHooks().adjustInlineAsmType(
3043 CGF, Constraint: OutputConstraint, Ty: Arg->getType()))
3044 Arg = Builder.CreateBitCast(V: Arg, DestTy: AdjTy);
3045
3046 // Update largest vector width for any vector types.
3047 if (auto *VT = dyn_cast<llvm::VectorType>(Val: Arg->getType()))
3048 CGF.LargestVectorWidth =
3049 std::max(a: (uint64_t)CGF.LargestVectorWidth,
3050 b: VT->getPrimitiveSizeInBits().getKnownMinValue());
3051
3052 // Only tie earlyclobber physregs.
3053 if (Info.allowsRegister() && (GCCReg.empty() || Info.earlyClobber()))
3054 InOutConstraints += llvm::utostr(X: I);
3055 else
3056 InOutConstraints += OutputConstraint;
3057
3058 InOutArgTypes.push_back(x: Arg->getType());
3059 InOutArgElemTypes.push_back(x: ArgElemType);
3060 InOutArgs.push_back(x: Arg);
3061 }
3062}
3063
3064/// Special handling for Microsoft-style inline assembly blocks. This ensures
3065/// that return registers (like EAX:EDX) are correctly mapped to the function's
3066/// return value slot when necessary.
3067void AsmConstraintsInfo::HandleMSStyleAsmBlob() {
3068 if (!isa<MSAsmStmt>(Val: &S))
3069 return;
3070
3071 const ABIArgInfo &RetAI = CGF.CurFnInfo->getReturnInfo();
3072 if (!RetAI.isDirect() && !RetAI.isExtend())
3073 return;
3074
3075 // Make a fake lvalue for the return value slot.
3076 LValue ReturnSlot =
3077 CGF.MakeAddrLValueWithoutTBAA(Addr: CGF.ReturnValue, T: CGF.FnRetTy);
3078 CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
3079 CGF, ReturnValue: ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
3080 ResultRegDests, AsmString, NumOutputs: S.getNumOutputs());
3081 CGF.SawAsmBlock = true;
3082}
3083
3084/// Process the input constraints of an inline assembly statement. It handles
3085/// type conversions, extensions for tied operands, and collects the necessary
3086/// LLVM values to be passed to the inline assembly call.
3087void AsmConstraintsInfo::HandleInputConstraints() {
3088 ASTContext &Ctx = getContext();
3089
3090 for (unsigned I = 0, E = S.getNumInputs(); I != E; I++) {
3091 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[I];
3092 const Expr *InputExpr = S.getInputExpr(i: I);
3093
3094 if (Info.allowsMemory())
3095 ReadNone = false;
3096
3097 if (!Constraints.empty())
3098 Constraints += ',';
3099
3100 // Simplify the input constraint.
3101 std::string InputConstraint(S.getInputConstraint(i: I));
3102 InputConstraint =
3103 getTarget().simplifyConstraint(Constraint: InputConstraint, OutCons: &OutputConstraintInfos);
3104
3105 InputConstraint = S.addVariableConstraints(
3106 Constraint: InputConstraint, AsmExpr: *InputExpr->IgnoreParenNoopCasts(Ctx), Target: getTarget(),
3107 EarlyClobber: false /* No EarlyClobber */,
3108 UnsupportedCB: [&](const Stmt *UnspStmt, std::string_view Msg) {
3109 CGM.ErrorUnsupported(S: UnspStmt, Type: Msg);
3110 });
3111
3112 std::string ReplaceConstraint(InputConstraint);
3113 llvm::Value *Arg;
3114 llvm::Type *ArgElemType;
3115 std::tie(args&: Arg, args&: ArgElemType) = CGF.EmitAsmInput(Info, InputExpr, ConstraintStr&: Constraints);
3116
3117 // If this input argument is tied to a larger output result, extend the
3118 // input to be the same size as the output. The LLVM backend wants to see
3119 // the input and output of a matching constraint be the same size. Note
3120 // that GCC does not define what the top bits are here. We use zext because
3121 // that is usually cheaper, but LLVM IR should really get an anyext someday.
3122 if (Info.hasTiedOperand()) {
3123 unsigned Output = Info.getTiedOperand();
3124 QualType OutputType = S.getOutputExpr(i: Output)->getType();
3125 QualType InputTy = InputExpr->getType();
3126
3127 if (Ctx.getTypeSize(T: OutputType) > Ctx.getTypeSize(T: InputTy)) {
3128 // Use ptrtoint as appropriate so that we can do our extension.
3129 if (isa<llvm::PointerType>(Val: Arg->getType()))
3130 Arg = Builder.CreatePtrToInt(V: Arg, DestTy: CGF.IntPtrTy);
3131
3132 llvm::Type *OutputTy = CGF.ConvertType(T: OutputType);
3133 if (isa<llvm::IntegerType>(Val: OutputTy))
3134 Arg = Builder.CreateZExt(V: Arg, DestTy: OutputTy);
3135 else if (isa<llvm::PointerType>(Val: OutputTy))
3136 Arg = Builder.CreateZExt(V: Arg, DestTy: CGF.IntPtrTy);
3137 else if (OutputTy->isFloatingPointTy())
3138 Arg = Builder.CreateFPExt(V: Arg, DestTy: OutputTy);
3139 }
3140
3141 // Deal with the tied operands' constraint code in adjustInlineAsmType.
3142 ReplaceConstraint = OutputConstraints[Output];
3143 }
3144
3145 if (llvm::Type *AdjTy = getTargetHooks().adjustInlineAsmType(
3146 CGF, Constraint: ReplaceConstraint, Ty: Arg->getType()))
3147 Arg = Builder.CreateBitCast(V: Arg, DestTy: AdjTy);
3148 else
3149 CGM.getDiags().Report(Loc: S.getAsmLoc(), DiagID: diag::err_asm_invalid_type_in_input)
3150 << InputExpr->getType() << InputConstraint;
3151
3152 // Update largest vector width for any vector types.
3153 if (auto *VT = dyn_cast<llvm::VectorType>(Val: Arg->getType()))
3154 CGF.LargestVectorWidth =
3155 std::max(a: (uint64_t)CGF.LargestVectorWidth,
3156 b: VT->getPrimitiveSizeInBits().getKnownMinValue());
3157
3158 ArgTypes.push_back(x: Arg->getType());
3159 ArgElemTypes.push_back(x: ArgElemType);
3160 Args.push_back(x: Arg);
3161
3162 Constraints += InputConstraint;
3163 }
3164
3165 // Append the "input" part of in/out constraints.
3166 for (unsigned I = 0, E = InOutArgs.size(); I != E; I++) {
3167 ArgTypes.push_back(x: InOutArgTypes[I]);
3168 ArgElemTypes.push_back(x: InOutArgElemTypes[I]);
3169 Args.push_back(x: InOutArgs[I]);
3170 }
3171
3172 Constraints += InOutConstraints;
3173}
3174
3175/// Handle labels in an 'asm goto' statement. This method resolves the symbolic
3176/// labels to LLVM basic blocks and updates the constraint string to reflect
3177/// the indirect jump targets.
3178bool AsmConstraintsInfo::HandleLabels() {
3179 if (const auto *GS = dyn_cast<GCCAsmStmt>(Val: &S); GS && GS->isAsmGoto()) {
3180 for (const auto *E : GS->labels()) {
3181 CodeGenFunction::JumpDest Dest = CGF.getJumpDestForLabel(D: E->getLabel());
3182 IndirectDests.push_back(Elt: Dest.getBlock());
3183
3184 if (!Constraints.empty())
3185 Constraints += ',';
3186
3187 Constraints += "!i";
3188 }
3189
3190 DefaultDest = CGF.createBasicBlock(name: "asm.fallthrough");
3191 return true;
3192 }
3193
3194 return false;
3195}
3196
3197/// Process clobber constraints for an inline assembly statement. This
3198/// identifies which registers or system state (like "memory" or "cc") are
3199/// modified by the assembly block, which is crucial for correct optimization
3200/// and side-effect modeling.
3201bool AsmConstraintsInfo::HandleClobbers() {
3202 bool HasUnwindClobber = false;
3203 for (unsigned I = 0, E = S.getNumClobbers(); I != E; I++) {
3204 std::string Clobber = S.getClobber(i: I);
3205
3206 if (Clobber == "unwind") {
3207 HasUnwindClobber = true;
3208 continue;
3209 }
3210
3211 if (Clobber == "memory") {
3212 ReadOnly = false;
3213 ReadNone = false;
3214 } else if (Clobber != "cc") {
3215 Clobber = getTarget().getNormalizedGCCRegisterName(Name: Clobber);
3216 if (CGM.getCodeGenOpts().StackClashProtector &&
3217 getTarget().isSPRegName(Clobber)) {
3218 CGM.getDiags().Report(Loc: S.getAsmLoc(),
3219 DiagID: diag::warn_stack_clash_protection_inline_asm);
3220 }
3221 }
3222
3223 if (isa<MSAsmStmt>(Val: &S)) {
3224 if (Clobber == "eax" || Clobber == "edx") {
3225 if (Constraints.find(s: "=&A") != std::string::npos)
3226 continue;
3227
3228 std::string::size_type position1 =
3229 Constraints.find(str: "={" + Clobber + "}");
3230 if (position1 != std::string::npos) {
3231 Constraints.insert(pos: position1 + 1, s: "&");
3232 continue;
3233 }
3234
3235 std::string::size_type position2 = Constraints.find(s: "=A");
3236 if (position2 != std::string::npos) {
3237 Constraints.insert(pos: position2 + 1, s: "&");
3238 continue;
3239 }
3240 }
3241 }
3242
3243 if (!Constraints.empty())
3244 Constraints += ',';
3245
3246 Constraints += "~{" + Clobber + '}';
3247 }
3248
3249 return HasUnwindClobber;
3250}
3251
3252void AsmConstraintsInfo::UpdateAsmCallInst(
3253 llvm::CallBase &Result, bool HasSideEffect, bool HasUnwindClobber,
3254 bool NoMerge, bool NoConvergent, std::vector<llvm::Value *> &RegResults) {
3255 if (!HasUnwindClobber)
3256 Result.addFnAttr(Kind: llvm::Attribute::NoUnwind);
3257
3258 if (NoMerge)
3259 Result.addFnAttr(Kind: llvm::Attribute::NoMerge);
3260
3261 // Attach readnone and readonly attributes.
3262 if (!HasSideEffect) {
3263 if (ReadNone)
3264 Result.setDoesNotAccessMemory();
3265 else if (ReadOnly)
3266 Result.setOnlyReadsMemory();
3267 }
3268
3269 // Add elementtype attribute for indirect constraints.
3270 for (auto Pair : llvm::enumerate(First&: ArgElemTypes)) {
3271 if (Pair.value()) {
3272 auto Attr = llvm::Attribute::get(
3273 Context&: getLLVMContext(), Kind: llvm::Attribute::ElementType, Ty: Pair.value());
3274 Result.addParamAttr(ArgNo: Pair.index(), Attr);
3275 }
3276 }
3277
3278 // Slap the source location of the inline asm into a !srcloc metadata on the
3279 // call.
3280 const StringLiteral *SL;
3281 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(Val: &S);
3282 gccAsmStmt &&
3283 (SL = dyn_cast<StringLiteral>(Val: gccAsmStmt->getAsmStringExpr()))) {
3284 Result.setMetadata(Kind: "srcloc", Node: getAsmSrcLocInfo(Str: SL, CGF));
3285 } else {
3286 // At least put the line number on MS inline asm blobs and GCC asm constexpr
3287 // strings.
3288 llvm::Constant *Loc =
3289 llvm::ConstantInt::get(Ty: CGF.Int64Ty, V: S.getAsmLoc().getRawEncoding());
3290 Result.setMetadata(Kind: "srcloc",
3291 Node: llvm::MDNode::get(Context&: getLLVMContext(),
3292 MDs: llvm::ConstantAsMetadata::get(C: Loc)));
3293 }
3294
3295 // Make inline-asm calls Key for the debug info feature Key Instructions.
3296 CGF.addInstToNewSourceAtom(KeyInstruction: &Result, Backup: nullptr);
3297
3298 if (!NoConvergent && getLangOpts().assumeFunctionsAreConvergent())
3299 // Conservatively, mark all inline asm blocks in CUDA or OpenCL as
3300 // convergent (meaning, they may call an intrinsically convergent op, such
3301 // as bar.sync, and so can't have certain optimizations applied around
3302 // them) unless it's explicitly marked 'noconvergent'.
3303 Result.addFnAttr(Kind: llvm::Attribute::Convergent);
3304
3305 // Extract all of the register value results from the asm.
3306 if (ResultRegTypes.size() == 1) {
3307 RegResults.push_back(x: &Result);
3308 } else {
3309 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
3310 llvm::Value *Tmp = Builder.CreateExtractValue(Agg: &Result, Idxs: i, Name: "asmresult");
3311 RegResults.push_back(x: Tmp);
3312 }
3313 }
3314}
3315
3316void AsmConstraintsInfo::EmitAsmStores(
3317 const llvm::ArrayRef<llvm::Value *> RegResults) {
3318 llvm::LLVMContext &CTX = getLLVMContext();
3319
3320 assert(RegResults.size() == ResultRegTypes.size());
3321 assert(RegResults.size() == ResultTruncRegTypes.size());
3322 assert(RegResults.size() == ResultRegDests.size());
3323
3324 // ResultRegDests can also be populated by addReturnRegisterOutputs() above,
3325 // in which case its size may grow.
3326 assert(ResultTypeRequiresCast.size() <= ResultRegDests.size());
3327 assert(ResultBounds.size() <= ResultRegDests.size());
3328
3329 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
3330 llvm::Value *Tmp = RegResults[i];
3331 llvm::Type *TruncTy = ResultTruncRegTypes[i];
3332
3333 if (i < ResultBounds.size() && ResultBounds[i].has_value()) {
3334 const auto [LowerBound, UpperBound] = ResultBounds[i].value();
3335
3336 // FIXME: Support for nonzero lower bounds not yet implemented.
3337 assert(LowerBound == 0 && "Output operand lower bound is not zero.");
3338
3339 llvm::Constant *UpperBoundConst =
3340 llvm::ConstantInt::get(Ty: Tmp->getType(), V: UpperBound);
3341 llvm::Value *IsBooleanValue =
3342 Builder.CreateCmp(Pred: llvm::CmpInst::ICMP_ULT, LHS: Tmp, RHS: UpperBoundConst);
3343 llvm::Function *FnAssume = CGM.getIntrinsic(IID: llvm::Intrinsic::assume);
3344
3345 Builder.CreateCall(Callee: FnAssume, Args: IsBooleanValue);
3346 }
3347
3348 // If the result type of the LLVM IR asm doesn't match the result type of
3349 // the expression, do the conversion.
3350 if (ResultRegTypes[i] != TruncTy) {
3351 // Truncate the integer result to the right size, note that TruncTy can be
3352 // a pointer.
3353 if (TruncTy->isFloatingPointTy())
3354 Tmp = Builder.CreateFPTrunc(V: Tmp, DestTy: TruncTy);
3355 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
3356 uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(Ty: TruncTy);
3357 Tmp = Builder.CreateTrunc(
3358 V: Tmp, DestTy: llvm::IntegerType::get(C&: CTX, NumBits: (unsigned)ResSize));
3359 Tmp = Builder.CreateIntToPtr(V: Tmp, DestTy: TruncTy);
3360 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
3361 uint64_t TmpSize =
3362 CGM.getDataLayout().getTypeSizeInBits(Ty: Tmp->getType());
3363 Tmp = Builder.CreatePtrToInt(
3364 V: Tmp, DestTy: llvm::IntegerType::get(C&: CTX, NumBits: (unsigned)TmpSize));
3365 Tmp = Builder.CreateTrunc(V: Tmp, DestTy: TruncTy);
3366 } else if (Tmp->getType()->isIntegerTy() && TruncTy->isIntegerTy()) {
3367 Tmp = Builder.CreateZExtOrTrunc(V: Tmp, DestTy: TruncTy);
3368 } else if (Tmp->getType()->isVectorTy() || TruncTy->isVectorTy()) {
3369 Tmp = Builder.CreateBitCast(V: Tmp, DestTy: TruncTy);
3370 }
3371 }
3372
3373 ApplyAtomGroup Grp(CGF.getDebugInfo());
3374 LValue Dest = ResultRegDests[i];
3375
3376 // ResultTypeRequiresCast elements correspond to the first
3377 // ResultTypeRequiresCast.size() elements of RegResults.
3378 if (i < ResultTypeRequiresCast.size() && ResultTypeRequiresCast[i]) {
3379 unsigned Size = getContext().getTypeSize(T: ResultRegQualTys[i]);
3380 Address A = Dest.getAddress().withElementType(ElemTy: ResultRegTypes[i]);
3381
3382 if (getTargetHooks().isScalarizableAsmOperand(CGF, Ty: TruncTy)) {
3383 llvm::StoreInst *S = Builder.CreateStore(Val: Tmp, Addr: A);
3384 CGF.addInstToCurrentSourceAtom(KeyInstruction: S, Backup: S->getValueOperand());
3385 continue;
3386 }
3387
3388 QualType Ty = getContext().getIntTypeForBitwidth(DestWidth: Size, /*Signed=*/false);
3389 if (Ty.isNull()) {
3390 const Expr *OutExpr = S.getOutputExpr(i);
3391 CGM.getDiags().Report(Loc: OutExpr->getExprLoc(),
3392 DiagID: diag::err_store_value_to_reg);
3393 return;
3394 }
3395
3396 Dest = CGF.MakeAddrLValue(Addr: A, T: Ty);
3397 }
3398
3399 CGF.EmitStoreThroughLValue(Src: RValue::get(V: Tmp), Dst: Dest);
3400 }
3401}
3402
3403LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) {
3404 const RecordDecl *RD = S.getCapturedRecordDecl();
3405 CanQualType RecordTy = getContext().getCanonicalTagType(TD: RD);
3406
3407 // Initialize the captured struct.
3408 LValue SlotLV =
3409 MakeAddrLValue(Addr: CreateMemTemp(T: RecordTy, Name: "agg.captured"), T: RecordTy);
3410
3411 RecordDecl::field_iterator CurField = RD->field_begin();
3412 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
3413 E = S.capture_init_end();
3414 I != E; ++I, ++CurField) {
3415 LValue LV = EmitLValueForFieldInitialization(Base: SlotLV, Field: *CurField);
3416 if (CurField->hasCapturedVLAType()) {
3417 EmitLambdaVLACapture(VAT: CurField->getCapturedVLAType(), LV);
3418 } else {
3419 EmitInitializerForField(Field: *CurField, LHS: LV, Init: *I);
3420 }
3421 }
3422
3423 return SlotLV;
3424}
3425
3426/// Generate an outlined function for the body of a CapturedStmt, store any
3427/// captured variables into the captured struct, and call the outlined function.
3428llvm::Function *
3429CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
3430 LValue CapStruct = InitCapturedStruct(S);
3431
3432 // Emit the CapturedDecl
3433 CodeGenFunction CGF(CGM, true);
3434 CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K));
3435 llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
3436 delete CGF.CapturedStmtInfo;
3437
3438 // Emit call to the helper function.
3439 EmitCallOrInvoke(Callee: F, Args: CapStruct.getPointer(CGF&: *this));
3440
3441 return F;
3442}
3443
3444Address CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
3445 LValue CapStruct = InitCapturedStruct(S);
3446 return CapStruct.getAddress();
3447}
3448
3449/// Creates the outlined function for a CapturedStmt.
3450llvm::Function *
3451CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
3452 assert(CapturedStmtInfo &&
3453 "CapturedStmtInfo should be set when generating the captured function");
3454 const CapturedDecl *CD = S.getCapturedDecl();
3455 const RecordDecl *RD = S.getCapturedRecordDecl();
3456 SourceLocation Loc = S.getBeginLoc();
3457 assert(CD->hasBody() && "missing CapturedDecl body");
3458
3459 // Build the argument list.
3460 ASTContext &Ctx = CGM.getContext();
3461 FunctionArgList Args;
3462 Args.append(in_start: CD->param_begin(), in_end: CD->param_end());
3463
3464 // Create the function declaration.
3465 const CGFunctionInfo &FuncInfo =
3466 CGM.getTypes().arrangeBuiltinFunctionDeclaration(resultType: Ctx.VoidTy, args: Args);
3467 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(Info: FuncInfo);
3468
3469 llvm::Function *F =
3470 llvm::Function::Create(Ty: FuncLLVMTy, Linkage: llvm::GlobalValue::InternalLinkage,
3471 N: CapturedStmtInfo->getHelperName(), M: &CGM.getModule());
3472 CGM.SetInternalFunctionAttributes(GD: CD, F, FI: FuncInfo);
3473 if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
3474 F->addFnAttr(Kind: "sample-profile-suffix-elision-policy", Val: "selected");
3475 if (CD->isNothrow())
3476 F->addFnAttr(Kind: llvm::Attribute::NoUnwind);
3477
3478 // Generate the function.
3479 StartFunction(GD: CD, RetTy: Ctx.VoidTy, Fn: F, FnInfo: FuncInfo, Args, Loc: CD->getLocation(),
3480 StartLoc: CD->getBody()->getBeginLoc());
3481 // Set the context parameter in CapturedStmtInfo.
3482 Address DeclPtr = GetAddrOfLocalVar(VD: CD->getContextParam());
3483 CapturedStmtInfo->setContextValue(Builder.CreateLoad(Addr: DeclPtr));
3484
3485 // Initialize variable-length arrays.
3486 LValue Base = MakeNaturalAlignRawAddrLValue(
3487 V: CapturedStmtInfo->getContextValue(), T: Ctx.getCanonicalTagType(TD: RD));
3488 for (auto *FD : RD->fields()) {
3489 if (FD->hasCapturedVLAType()) {
3490 auto *ExprArg =
3491 EmitLoadOfLValue(V: EmitLValueForField(Base, Field: FD), Loc: S.getBeginLoc())
3492 .getScalarVal();
3493 auto VAT = FD->getCapturedVLAType();
3494 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
3495 }
3496 }
3497
3498 // If 'this' is captured, load it into CXXThisValue.
3499 if (CapturedStmtInfo->isCXXThisExprCaptured()) {
3500 FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
3501 LValue ThisLValue = EmitLValueForField(Base, Field: FD);
3502 CXXThisValue = EmitLoadOfLValue(V: ThisLValue, Loc).getScalarVal();
3503 }
3504
3505 PGO->assignRegionCounters(GD: GlobalDecl(CD), Fn: F);
3506 CapturedStmtInfo->EmitBody(CGF&: *this, S: CD->getBody());
3507 FinishFunction(EndLoc: CD->getBodyRBrace());
3508
3509 return F;
3510}
3511
3512// Returns the first convergence entry/loop/anchor instruction found in |BB|.
3513// std::nullptr otherwise.
3514static llvm::ConvergenceControlInst *getConvergenceToken(llvm::BasicBlock *BB) {
3515 for (auto &I : *BB) {
3516 if (auto *CI = dyn_cast<llvm::ConvergenceControlInst>(Val: &I))
3517 return CI;
3518 }
3519 return nullptr;
3520}
3521
3522llvm::CallBase *
3523CodeGenFunction::addConvergenceControlToken(llvm::CallBase *Input) {
3524 llvm::ConvergenceControlInst *ParentToken = ConvergenceTokenStack.back();
3525 assert(ParentToken);
3526
3527 llvm::Value *bundleArgs[] = {ParentToken};
3528 llvm::OperandBundleDef OB("convergencectrl", bundleArgs);
3529 auto *Output = llvm::CallBase::addOperandBundle(
3530 CB: Input, ID: llvm::LLVMContext::OB_convergencectrl, OB, InsertPt: Input->getIterator());
3531 Input->replaceAllUsesWith(V: Output);
3532 Input->eraseFromParent();
3533 return Output;
3534}
3535
3536llvm::ConvergenceControlInst *
3537CodeGenFunction::emitConvergenceLoopToken(llvm::BasicBlock *BB) {
3538 llvm::ConvergenceControlInst *ParentToken = ConvergenceTokenStack.back();
3539 assert(ParentToken);
3540 return llvm::ConvergenceControlInst::CreateLoop(BB&: *BB, Parent: ParentToken);
3541}
3542
3543llvm::ConvergenceControlInst *
3544CodeGenFunction::getOrEmitConvergenceEntryToken(llvm::Function *F) {
3545 llvm::BasicBlock *BB = &F->getEntryBlock();
3546 llvm::ConvergenceControlInst *Token = getConvergenceToken(BB);
3547 if (Token)
3548 return Token;
3549
3550 // Adding a convergence token requires the function to be marked as
3551 // convergent.
3552 F->setConvergent();
3553 return llvm::ConvergenceControlInst::CreateEntry(BB&: *BB);
3554}
3555