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