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