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