1 //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Stmt nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
15 #include "CGDebugInfo.h"
16 #include "CodeGenModule.h"
17 #include "TargetInfo.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/Basic/Builtins.h"
20 #include "clang/Basic/PrettyStackTrace.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Sema/LoopHint.h"
23 #include "clang/Sema/SemaDiagnostic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/MDBuilder.h"
31 using namespace clang;
32 using namespace CodeGen;
34 //===----------------------------------------------------------------------===//
36 //===----------------------------------------------------------------------===//
38 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
39 if (CGDebugInfo *DI = getDebugInfo()) {
41 Loc = S->getLocStart();
42 DI->EmitLocation(Builder, Loc);
48 void CodeGenFunction::EmitStmt(const Stmt *S) {
49 assert(S && "Null statement?");
50 PGO.setCurrentStmt(S);
52 // These statements have their own debug info handling.
53 if (EmitSimpleStmt(S))
56 // Check if we are generating unreachable code.
57 if (!HaveInsertPoint()) {
58 // If so, and the statement doesn't contain a label, then we do not need to
59 // generate actual code. This is safe because (1) the current point is
60 // unreachable, so we don't need to execute the code, and (2) we've already
61 // handled the statements which update internal data structures (like the
62 // local variable map) which could be used by subsequent statements.
63 if (!ContainsLabel(S)) {
64 // Verify that any decl statements were handled as simple, they may be in
65 // scope of subsequent reachable statements.
66 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
70 // Otherwise, make a new block to hold the code.
74 // Generate a stoppoint if we are emitting debug info.
77 switch (S->getStmtClass()) {
78 case Stmt::NoStmtClass:
79 case Stmt::CXXCatchStmtClass:
80 case Stmt::SEHExceptStmtClass:
81 case Stmt::SEHFinallyStmtClass:
82 case Stmt::MSDependentExistsStmtClass:
83 llvm_unreachable("invalid statement class to emit generically");
84 case Stmt::NullStmtClass:
85 case Stmt::CompoundStmtClass:
86 case Stmt::DeclStmtClass:
87 case Stmt::LabelStmtClass:
88 case Stmt::AttributedStmtClass:
89 case Stmt::GotoStmtClass:
90 case Stmt::BreakStmtClass:
91 case Stmt::ContinueStmtClass:
92 case Stmt::DefaultStmtClass:
93 case Stmt::CaseStmtClass:
94 case Stmt::SEHLeaveStmtClass:
95 llvm_unreachable("should have emitted these statements as simple");
97 #define STMT(Type, Base)
98 #define ABSTRACT_STMT(Op)
99 #define EXPR(Type, Base) \
100 case Stmt::Type##Class:
101 #include "clang/AST/StmtNodes.inc"
103 // Remember the block we came in on.
104 llvm::BasicBlock *incoming = Builder.GetInsertBlock();
105 assert(incoming && "expression emission must have an insertion point");
107 EmitIgnoredExpr(cast<Expr>(S));
109 llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
110 assert(outgoing && "expression emission cleared block!");
112 // The expression emitters assume (reasonably!) that the insertion
113 // point is always set. To maintain that, the call-emission code
114 // for noreturn functions has to enter a new block with no
115 // predecessors. We want to kill that block and mark the current
116 // insertion point unreachable in the common case of a call like
117 // "exit();". Since expression emission doesn't otherwise create
118 // blocks with no predecessors, we can just test for that.
119 // However, we must be careful not to do this to our incoming
120 // block, because *statement* emission does sometimes create
121 // reachable blocks which will have no predecessors until later in
122 // the function. This occurs with, e.g., labels that are not
123 // reachable by fallthrough.
124 if (incoming != outgoing && outgoing->use_empty()) {
125 outgoing->eraseFromParent();
126 Builder.ClearInsertionPoint();
131 case Stmt::IndirectGotoStmtClass:
132 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
134 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
135 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
136 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
137 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
139 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
141 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
142 case Stmt::GCCAsmStmtClass: // Intentional fall-through.
143 case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
144 case Stmt::CoroutineBodyStmtClass:
145 EmitCoroutineBody(cast<CoroutineBodyStmt>(*S));
147 case Stmt::CoreturnStmtClass:
148 CGM.ErrorUnsupported(S, "coroutine");
150 case Stmt::CapturedStmtClass: {
151 const CapturedStmt *CS = cast<CapturedStmt>(S);
152 EmitCapturedStmt(*CS, CS->getCapturedRegionKind());
155 case Stmt::ObjCAtTryStmtClass:
156 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
158 case Stmt::ObjCAtCatchStmtClass:
160 "@catch statements should be handled by EmitObjCAtTryStmt");
161 case Stmt::ObjCAtFinallyStmtClass:
163 "@finally statements should be handled by EmitObjCAtTryStmt");
164 case Stmt::ObjCAtThrowStmtClass:
165 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
167 case Stmt::ObjCAtSynchronizedStmtClass:
168 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
170 case Stmt::ObjCForCollectionStmtClass:
171 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
173 case Stmt::ObjCAutoreleasePoolStmtClass:
174 EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
177 case Stmt::CXXTryStmtClass:
178 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
180 case Stmt::CXXForRangeStmtClass:
181 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
183 case Stmt::SEHTryStmtClass:
184 EmitSEHTryStmt(cast<SEHTryStmt>(*S));
186 case Stmt::OMPParallelDirectiveClass:
187 EmitOMPParallelDirective(cast<OMPParallelDirective>(*S));
189 case Stmt::OMPSimdDirectiveClass:
190 EmitOMPSimdDirective(cast<OMPSimdDirective>(*S));
192 case Stmt::OMPForDirectiveClass:
193 EmitOMPForDirective(cast<OMPForDirective>(*S));
195 case Stmt::OMPForSimdDirectiveClass:
196 EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S));
198 case Stmt::OMPSectionsDirectiveClass:
199 EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S));
201 case Stmt::OMPSectionDirectiveClass:
202 EmitOMPSectionDirective(cast<OMPSectionDirective>(*S));
204 case Stmt::OMPSingleDirectiveClass:
205 EmitOMPSingleDirective(cast<OMPSingleDirective>(*S));
207 case Stmt::OMPMasterDirectiveClass:
208 EmitOMPMasterDirective(cast<OMPMasterDirective>(*S));
210 case Stmt::OMPCriticalDirectiveClass:
211 EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S));
213 case Stmt::OMPParallelForDirectiveClass:
214 EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S));
216 case Stmt::OMPParallelForSimdDirectiveClass:
217 EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S));
219 case Stmt::OMPParallelSectionsDirectiveClass:
220 EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S));
222 case Stmt::OMPTaskDirectiveClass:
223 EmitOMPTaskDirective(cast<OMPTaskDirective>(*S));
225 case Stmt::OMPTaskyieldDirectiveClass:
226 EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S));
228 case Stmt::OMPBarrierDirectiveClass:
229 EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S));
231 case Stmt::OMPTaskwaitDirectiveClass:
232 EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S));
234 case Stmt::OMPTaskgroupDirectiveClass:
235 EmitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*S));
237 case Stmt::OMPFlushDirectiveClass:
238 EmitOMPFlushDirective(cast<OMPFlushDirective>(*S));
240 case Stmt::OMPOrderedDirectiveClass:
241 EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S));
243 case Stmt::OMPAtomicDirectiveClass:
244 EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S));
246 case Stmt::OMPTargetDirectiveClass:
247 EmitOMPTargetDirective(cast<OMPTargetDirective>(*S));
249 case Stmt::OMPTeamsDirectiveClass:
250 EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S));
252 case Stmt::OMPCancellationPointDirectiveClass:
253 EmitOMPCancellationPointDirective(cast<OMPCancellationPointDirective>(*S));
255 case Stmt::OMPCancelDirectiveClass:
256 EmitOMPCancelDirective(cast<OMPCancelDirective>(*S));
258 case Stmt::OMPTargetDataDirectiveClass:
259 EmitOMPTargetDataDirective(cast<OMPTargetDataDirective>(*S));
261 case Stmt::OMPTargetEnterDataDirectiveClass:
262 EmitOMPTargetEnterDataDirective(cast<OMPTargetEnterDataDirective>(*S));
264 case Stmt::OMPTargetExitDataDirectiveClass:
265 EmitOMPTargetExitDataDirective(cast<OMPTargetExitDataDirective>(*S));
267 case Stmt::OMPTargetParallelDirectiveClass:
268 EmitOMPTargetParallelDirective(cast<OMPTargetParallelDirective>(*S));
270 case Stmt::OMPTargetParallelForDirectiveClass:
271 EmitOMPTargetParallelForDirective(cast<OMPTargetParallelForDirective>(*S));
273 case Stmt::OMPTaskLoopDirectiveClass:
274 EmitOMPTaskLoopDirective(cast<OMPTaskLoopDirective>(*S));
276 case Stmt::OMPTaskLoopSimdDirectiveClass:
277 EmitOMPTaskLoopSimdDirective(cast<OMPTaskLoopSimdDirective>(*S));
279 case Stmt::OMPDistributeDirectiveClass:
280 EmitOMPDistributeDirective(cast<OMPDistributeDirective>(*S));
282 case Stmt::OMPTargetUpdateDirectiveClass:
283 EmitOMPTargetUpdateDirective(cast<OMPTargetUpdateDirective>(*S));
285 case Stmt::OMPDistributeParallelForDirectiveClass:
286 EmitOMPDistributeParallelForDirective(
287 cast<OMPDistributeParallelForDirective>(*S));
289 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
290 EmitOMPDistributeParallelForSimdDirective(
291 cast<OMPDistributeParallelForSimdDirective>(*S));
293 case Stmt::OMPDistributeSimdDirectiveClass:
294 EmitOMPDistributeSimdDirective(cast<OMPDistributeSimdDirective>(*S));
296 case Stmt::OMPTargetParallelForSimdDirectiveClass:
297 EmitOMPTargetParallelForSimdDirective(
298 cast<OMPTargetParallelForSimdDirective>(*S));
300 case Stmt::OMPTargetSimdDirectiveClass:
301 EmitOMPTargetSimdDirective(cast<OMPTargetSimdDirective>(*S));
303 case Stmt::OMPTeamsDistributeDirectiveClass:
304 EmitOMPTeamsDistributeDirective(cast<OMPTeamsDistributeDirective>(*S));
306 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
307 EmitOMPTeamsDistributeSimdDirective(
308 cast<OMPTeamsDistributeSimdDirective>(*S));
310 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
311 EmitOMPTeamsDistributeParallelForSimdDirective(
312 cast<OMPTeamsDistributeParallelForSimdDirective>(*S));
314 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
315 EmitOMPTeamsDistributeParallelForDirective(
316 cast<OMPTeamsDistributeParallelForDirective>(*S));
318 case Stmt::OMPTargetTeamsDirectiveClass:
319 EmitOMPTargetTeamsDirective(cast<OMPTargetTeamsDirective>(*S));
321 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
322 EmitOMPTargetTeamsDistributeDirective(
323 cast<OMPTargetTeamsDistributeDirective>(*S));
325 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
326 EmitOMPTargetTeamsDistributeParallelForDirective(
327 cast<OMPTargetTeamsDistributeParallelForDirective>(*S));
329 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
330 EmitOMPTargetTeamsDistributeParallelForSimdDirective(
331 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(*S));
333 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
334 EmitOMPTargetTeamsDistributeSimdDirective(
335 cast<OMPTargetTeamsDistributeSimdDirective>(*S));
340 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
341 switch (S->getStmtClass()) {
342 default: return false;
343 case Stmt::NullStmtClass: break;
344 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
345 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
346 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
347 case Stmt::AttributedStmtClass:
348 EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
349 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
350 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
351 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
352 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
353 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
354 case Stmt::SEHLeaveStmtClass: EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S)); break;
360 /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
361 /// this captures the expression result of the last sub-statement and returns it
362 /// (for use by the statement expression extension).
363 Address CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
364 AggValueSlot AggSlot) {
365 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
366 "LLVM IR generation of compound statement ('{}')");
368 // Keep track of the current cleanup stack depth, including debug scopes.
369 LexicalScope Scope(*this, S.getSourceRange());
371 return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
375 CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S,
377 AggValueSlot AggSlot) {
379 for (CompoundStmt::const_body_iterator I = S.body_begin(),
380 E = S.body_end()-GetLast; I != E; ++I)
383 Address RetAlloca = Address::invalid();
385 // We have to special case labels here. They are statements, but when put
386 // at the end of a statement expression, they yield the value of their
387 // subexpression. Handle this by walking through all labels we encounter,
388 // emitting them before we evaluate the subexpr.
389 const Stmt *LastStmt = S.body_back();
390 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
391 EmitLabel(LS->getDecl());
392 LastStmt = LS->getSubStmt();
397 QualType ExprTy = cast<Expr>(LastStmt)->getType();
398 if (hasAggregateEvaluationKind(ExprTy)) {
399 EmitAggExpr(cast<Expr>(LastStmt), AggSlot);
401 // We can't return an RValue here because there might be cleanups at
402 // the end of the StmtExpr. Because of that, we have to emit the result
403 // here into a temporary alloca.
404 RetAlloca = CreateMemTemp(ExprTy);
405 EmitAnyExprToMem(cast<Expr>(LastStmt), RetAlloca, Qualifiers(),
414 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
415 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
417 // If there is a cleanup stack, then we it isn't worth trying to
418 // simplify this block (we would need to remove it from the scope map
419 // and cleanup entry).
420 if (!EHStack.empty())
423 // Can only simplify direct branches.
424 if (!BI || !BI->isUnconditional())
427 // Can only simplify empty blocks.
428 if (BI->getIterator() != BB->begin())
431 BB->replaceAllUsesWith(BI->getSuccessor(0));
432 BI->eraseFromParent();
433 BB->eraseFromParent();
436 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
437 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
439 // Fall out of the current block (if necessary).
442 if (IsFinished && BB->use_empty()) {
447 // Place the block after the current block, if possible, or else at
448 // the end of the function.
449 if (CurBB && CurBB->getParent())
450 CurFn->getBasicBlockList().insertAfter(CurBB->getIterator(), BB);
452 CurFn->getBasicBlockList().push_back(BB);
453 Builder.SetInsertPoint(BB);
456 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
457 // Emit a branch from the current block to the target one if this
458 // was a real block. If this was just a fall-through block after a
459 // terminator, don't emit it.
460 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
462 if (!CurBB || CurBB->getTerminator()) {
463 // If there is no insert point or the previous block is already
464 // terminated, don't touch it.
466 // Otherwise, create a fall-through branch.
467 Builder.CreateBr(Target);
470 Builder.ClearInsertionPoint();
473 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
474 bool inserted = false;
475 for (llvm::User *u : block->users()) {
476 if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
477 CurFn->getBasicBlockList().insertAfter(insn->getParent()->getIterator(),
485 CurFn->getBasicBlockList().push_back(block);
487 Builder.SetInsertPoint(block);
490 CodeGenFunction::JumpDest
491 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
492 JumpDest &Dest = LabelMap[D];
493 if (Dest.isValid()) return Dest;
495 // Create, but don't insert, the new block.
496 Dest = JumpDest(createBasicBlock(D->getName()),
497 EHScopeStack::stable_iterator::invalid(),
498 NextCleanupDestIndex++);
502 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
503 // Add this label to the current lexical scope if we're within any
504 // normal cleanups. Jumps "in" to this label --- when permitted by
505 // the language --- may need to be routed around such cleanups.
506 if (EHStack.hasNormalCleanups() && CurLexicalScope)
507 CurLexicalScope->addLabel(D);
509 JumpDest &Dest = LabelMap[D];
511 // If we didn't need a forward reference to this label, just go
512 // ahead and create a destination at the current scope.
513 if (!Dest.isValid()) {
514 Dest = getJumpDestInCurrentScope(D->getName());
516 // Otherwise, we need to give this label a target depth and remove
517 // it from the branch-fixups list.
519 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
520 Dest.setScopeDepth(EHStack.stable_begin());
521 ResolveBranchFixups(Dest.getBlock());
524 EmitBlock(Dest.getBlock());
525 incrementProfileCounter(D->getStmt());
528 /// Change the cleanup scope of the labels in this lexical scope to
529 /// match the scope of the enclosing context.
530 void CodeGenFunction::LexicalScope::rescopeLabels() {
531 assert(!Labels.empty());
532 EHScopeStack::stable_iterator innermostScope
533 = CGF.EHStack.getInnermostNormalCleanup();
535 // Change the scope depth of all the labels.
536 for (SmallVectorImpl<const LabelDecl*>::const_iterator
537 i = Labels.begin(), e = Labels.end(); i != e; ++i) {
538 assert(CGF.LabelMap.count(*i));
539 JumpDest &dest = CGF.LabelMap.find(*i)->second;
540 assert(dest.getScopeDepth().isValid());
541 assert(innermostScope.encloses(dest.getScopeDepth()));
542 dest.setScopeDepth(innermostScope);
545 // Reparent the labels if the new scope also has cleanups.
546 if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
547 ParentScope->Labels.append(Labels.begin(), Labels.end());
552 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
553 EmitLabel(S.getDecl());
554 EmitStmt(S.getSubStmt());
557 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
558 const Stmt *SubStmt = S.getSubStmt();
559 switch (SubStmt->getStmtClass()) {
560 case Stmt::DoStmtClass:
561 EmitDoStmt(cast<DoStmt>(*SubStmt), S.getAttrs());
563 case Stmt::ForStmtClass:
564 EmitForStmt(cast<ForStmt>(*SubStmt), S.getAttrs());
566 case Stmt::WhileStmtClass:
567 EmitWhileStmt(cast<WhileStmt>(*SubStmt), S.getAttrs());
569 case Stmt::CXXForRangeStmtClass:
570 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*SubStmt), S.getAttrs());
577 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
578 // If this code is reachable then emit a stop point (if generating
579 // debug info). We have to do this ourselves because we are on the
580 // "simple" statement path.
581 if (HaveInsertPoint())
584 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
588 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
589 if (const LabelDecl *Target = S.getConstantTarget()) {
590 EmitBranchThroughCleanup(getJumpDestForLabel(Target));
594 // Ensure that we have an i8* for our PHI node.
595 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
597 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
599 // Get the basic block for the indirect goto.
600 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
602 // The first instruction in the block has to be the PHI for the switch dest,
603 // add an entry for this branch.
604 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
606 EmitBranch(IndGotoBB);
609 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
610 // C99 6.8.4.1: The first substatement is executed if the expression compares
611 // unequal to 0. The condition must be a scalar type.
612 LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
615 EmitStmt(S.getInit());
617 if (S.getConditionVariable())
618 EmitAutoVarDecl(*S.getConditionVariable());
620 // If the condition constant folds and can be elided, try to avoid emitting
621 // the condition and the dead arm of the if/else.
623 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant,
625 // Figure out which block (then or else) is executed.
626 const Stmt *Executed = S.getThen();
627 const Stmt *Skipped = S.getElse();
628 if (!CondConstant) // Condition false?
629 std::swap(Executed, Skipped);
631 // If the skipped block has no labels in it, just emit the executed block.
632 // This avoids emitting dead code and simplifies the CFG substantially.
633 if (S.isConstexpr() || !ContainsLabel(Skipped)) {
635 incrementProfileCounter(&S);
637 RunCleanupsScope ExecutedScope(*this);
644 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
645 // the conditional branch.
646 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
647 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
648 llvm::BasicBlock *ElseBlock = ContBlock;
650 ElseBlock = createBasicBlock("if.else");
652 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock,
653 getProfileCount(S.getThen()));
655 // Emit the 'then' code.
656 EmitBlock(ThenBlock);
657 incrementProfileCounter(&S);
659 RunCleanupsScope ThenScope(*this);
660 EmitStmt(S.getThen());
662 EmitBranch(ContBlock);
664 // Emit the 'else' code if present.
665 if (const Stmt *Else = S.getElse()) {
667 // There is no need to emit line number for an unconditional branch.
668 auto NL = ApplyDebugLocation::CreateEmpty(*this);
669 EmitBlock(ElseBlock);
672 RunCleanupsScope ElseScope(*this);
676 // There is no need to emit line number for an unconditional branch.
677 auto NL = ApplyDebugLocation::CreateEmpty(*this);
678 EmitBranch(ContBlock);
682 // Emit the continuation block for code after the if.
683 EmitBlock(ContBlock, true);
686 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
687 ArrayRef<const Attr *> WhileAttrs) {
688 // Emit the header for the loop, which will also become
689 // the continue target.
690 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
691 EmitBlock(LoopHeader.getBlock());
693 const SourceRange &R = S.getSourceRange();
694 LoopStack.push(LoopHeader.getBlock(), CGM.getContext(), WhileAttrs,
695 SourceLocToDebugLoc(R.getBegin()),
696 SourceLocToDebugLoc(R.getEnd()));
698 // Create an exit block for when the condition fails, which will
699 // also become the break target.
700 JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
702 // Store the blocks to use for break and continue.
703 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
705 // C++ [stmt.while]p2:
706 // When the condition of a while statement is a declaration, the
707 // scope of the variable that is declared extends from its point
708 // of declaration (3.3.2) to the end of the while statement.
710 // The object created in a condition is destroyed and created
711 // with each iteration of the loop.
712 RunCleanupsScope ConditionScope(*this);
714 if (S.getConditionVariable())
715 EmitAutoVarDecl(*S.getConditionVariable());
717 // Evaluate the conditional in the while header. C99 6.8.5.1: The
718 // evaluation of the controlling expression takes place before each
719 // execution of the loop body.
720 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
722 // while(1) is common, avoid extra exit blocks. Be sure
723 // to correctly handle break/continue though.
724 bool EmitBoolCondBranch = true;
725 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
727 EmitBoolCondBranch = false;
729 // As long as the condition is true, go to the loop body.
730 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
731 if (EmitBoolCondBranch) {
732 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
733 if (ConditionScope.requiresCleanups())
734 ExitBlock = createBasicBlock("while.exit");
735 Builder.CreateCondBr(
736 BoolCondVal, LoopBody, ExitBlock,
737 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
739 if (ExitBlock != LoopExit.getBlock()) {
740 EmitBlock(ExitBlock);
741 EmitBranchThroughCleanup(LoopExit);
745 // Emit the loop body. We have to emit this in a cleanup scope
746 // because it might be a singleton DeclStmt.
748 RunCleanupsScope BodyScope(*this);
750 incrementProfileCounter(&S);
751 EmitStmt(S.getBody());
754 BreakContinueStack.pop_back();
756 // Immediately force cleanup.
757 ConditionScope.ForceCleanup();
760 // Branch to the loop header again.
761 EmitBranch(LoopHeader.getBlock());
765 // Emit the exit block.
766 EmitBlock(LoopExit.getBlock(), true);
768 // The LoopHeader typically is just a branch if we skipped emitting
769 // a branch, try to erase it.
770 if (!EmitBoolCondBranch)
771 SimplifyForwardingBlocks(LoopHeader.getBlock());
774 void CodeGenFunction::EmitDoStmt(const DoStmt &S,
775 ArrayRef<const Attr *> DoAttrs) {
776 JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
777 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
779 uint64_t ParentCount = getCurrentProfileCount();
781 // Store the blocks to use for break and continue.
782 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
784 // Emit the body of the loop.
785 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
787 const SourceRange &R = S.getSourceRange();
788 LoopStack.push(LoopBody, CGM.getContext(), DoAttrs,
789 SourceLocToDebugLoc(R.getBegin()),
790 SourceLocToDebugLoc(R.getEnd()));
792 EmitBlockWithFallThrough(LoopBody, &S);
794 RunCleanupsScope BodyScope(*this);
795 EmitStmt(S.getBody());
798 EmitBlock(LoopCond.getBlock());
800 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
801 // after each execution of the loop body."
803 // Evaluate the conditional in the while header.
804 // C99 6.8.5p2/p4: The first substatement is executed if the expression
805 // compares unequal to 0. The condition must be a scalar type.
806 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
808 BreakContinueStack.pop_back();
810 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
811 // to correctly handle break/continue though.
812 bool EmitBoolCondBranch = true;
813 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
815 EmitBoolCondBranch = false;
817 // As long as the condition is true, iterate the loop.
818 if (EmitBoolCondBranch) {
819 uint64_t BackedgeCount = getProfileCount(S.getBody()) - ParentCount;
820 Builder.CreateCondBr(
821 BoolCondVal, LoopBody, LoopExit.getBlock(),
822 createProfileWeightsForLoop(S.getCond(), BackedgeCount));
827 // Emit the exit block.
828 EmitBlock(LoopExit.getBlock());
830 // The DoCond block typically is just a branch if we skipped
831 // emitting a branch, try to erase it.
832 if (!EmitBoolCondBranch)
833 SimplifyForwardingBlocks(LoopCond.getBlock());
836 void CodeGenFunction::EmitForStmt(const ForStmt &S,
837 ArrayRef<const Attr *> ForAttrs) {
838 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
840 LexicalScope ForScope(*this, S.getSourceRange());
842 // Evaluate the first part before the loop.
844 EmitStmt(S.getInit());
846 // Start the loop with a block that tests the condition.
847 // If there's an increment, the continue scope will be overwritten
849 JumpDest Continue = getJumpDestInCurrentScope("for.cond");
850 llvm::BasicBlock *CondBlock = Continue.getBlock();
851 EmitBlock(CondBlock);
853 const SourceRange &R = S.getSourceRange();
854 LoopStack.push(CondBlock, CGM.getContext(), ForAttrs,
855 SourceLocToDebugLoc(R.getBegin()),
856 SourceLocToDebugLoc(R.getEnd()));
858 // If the for loop doesn't have an increment we can just use the
859 // condition as the continue block. Otherwise we'll need to create
860 // a block for it (in the current scope, i.e. in the scope of the
861 // condition), and that we will become our continue block.
863 Continue = getJumpDestInCurrentScope("for.inc");
865 // Store the blocks to use for break and continue.
866 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
868 // Create a cleanup scope for the condition variable cleanups.
869 LexicalScope ConditionScope(*this, S.getSourceRange());
872 // If the for statement has a condition scope, emit the local variable
874 if (S.getConditionVariable()) {
875 EmitAutoVarDecl(*S.getConditionVariable());
878 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
879 // If there are any cleanups between here and the loop-exit scope,
880 // create a block to stage a loop exit along.
881 if (ForScope.requiresCleanups())
882 ExitBlock = createBasicBlock("for.cond.cleanup");
884 // As long as the condition is true, iterate the loop.
885 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
887 // C99 6.8.5p2/p4: The first substatement is executed if the expression
888 // compares unequal to 0. The condition must be a scalar type.
889 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
890 Builder.CreateCondBr(
891 BoolCondVal, ForBody, ExitBlock,
892 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
894 if (ExitBlock != LoopExit.getBlock()) {
895 EmitBlock(ExitBlock);
896 EmitBranchThroughCleanup(LoopExit);
901 // Treat it as a non-zero constant. Don't even create a new block for the
902 // body, just fall into it.
904 incrementProfileCounter(&S);
907 // Create a separate cleanup scope for the body, in case it is not
908 // a compound statement.
909 RunCleanupsScope BodyScope(*this);
910 EmitStmt(S.getBody());
913 // If there is an increment, emit it next.
915 EmitBlock(Continue.getBlock());
916 EmitStmt(S.getInc());
919 BreakContinueStack.pop_back();
921 ConditionScope.ForceCleanup();
924 EmitBranch(CondBlock);
926 ForScope.ForceCleanup();
930 // Emit the fall-through block.
931 EmitBlock(LoopExit.getBlock(), true);
935 CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
936 ArrayRef<const Attr *> ForAttrs) {
937 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
939 LexicalScope ForScope(*this, S.getSourceRange());
941 // Evaluate the first pieces before the loop.
942 EmitStmt(S.getRangeStmt());
943 EmitStmt(S.getBeginStmt());
944 EmitStmt(S.getEndStmt());
946 // Start the loop with a block that tests the condition.
947 // If there's an increment, the continue scope will be overwritten
949 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
950 EmitBlock(CondBlock);
952 const SourceRange &R = S.getSourceRange();
953 LoopStack.push(CondBlock, CGM.getContext(), ForAttrs,
954 SourceLocToDebugLoc(R.getBegin()),
955 SourceLocToDebugLoc(R.getEnd()));
957 // If there are any cleanups between here and the loop-exit scope,
958 // create a block to stage a loop exit along.
959 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
960 if (ForScope.requiresCleanups())
961 ExitBlock = createBasicBlock("for.cond.cleanup");
963 // The loop body, consisting of the specified body and the loop variable.
964 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
966 // The body is executed if the expression, contextually converted
968 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
969 Builder.CreateCondBr(
970 BoolCondVal, ForBody, ExitBlock,
971 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
973 if (ExitBlock != LoopExit.getBlock()) {
974 EmitBlock(ExitBlock);
975 EmitBranchThroughCleanup(LoopExit);
979 incrementProfileCounter(&S);
981 // Create a block for the increment. In case of a 'continue', we jump there.
982 JumpDest Continue = getJumpDestInCurrentScope("for.inc");
984 // Store the blocks to use for break and continue.
985 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
988 // Create a separate cleanup scope for the loop variable and body.
989 LexicalScope BodyScope(*this, S.getSourceRange());
990 EmitStmt(S.getLoopVarStmt());
991 EmitStmt(S.getBody());
995 // If there is an increment, emit it next.
996 EmitBlock(Continue.getBlock());
997 EmitStmt(S.getInc());
999 BreakContinueStack.pop_back();
1001 EmitBranch(CondBlock);
1003 ForScope.ForceCleanup();
1007 // Emit the fall-through block.
1008 EmitBlock(LoopExit.getBlock(), true);
1011 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
1012 if (RV.isScalar()) {
1013 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
1014 } else if (RV.isAggregate()) {
1015 EmitAggregateCopy(ReturnValue, RV.getAggregateAddress(), Ty);
1017 EmitStoreOfComplex(RV.getComplexVal(), MakeAddrLValue(ReturnValue, Ty),
1020 EmitBranchThroughCleanup(ReturnBlock);
1023 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
1024 /// if the function returns void, or may be missing one if the function returns
1025 /// non-void. Fun stuff :).
1026 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
1027 // Returning from an outlined SEH helper is UB, and we already warn on it.
1028 if (IsOutlinedSEHHelper) {
1029 Builder.CreateUnreachable();
1030 Builder.ClearInsertionPoint();
1033 // Emit the result value, even if unused, to evalute the side effects.
1034 const Expr *RV = S.getRetValue();
1036 // Treat block literals in a return expression as if they appeared
1037 // in their own scope. This permits a small, easily-implemented
1038 // exception to our over-conservative rules about not jumping to
1039 // statements following block literals with non-trivial cleanups.
1040 RunCleanupsScope cleanupScope(*this);
1041 if (const ExprWithCleanups *cleanups =
1042 dyn_cast_or_null<ExprWithCleanups>(RV)) {
1043 enterFullExpression(cleanups);
1044 RV = cleanups->getSubExpr();
1047 // FIXME: Clean this up by using an LValue for ReturnTemp,
1048 // EmitStoreThroughLValue, and EmitAnyExpr.
1049 if (getLangOpts().ElideConstructors &&
1050 S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
1051 // Apply the named return value optimization for this return statement,
1052 // which means doing nothing: the appropriate result has already been
1053 // constructed into the NRVO variable.
1055 // If there is an NRVO flag for this variable, set it to 1 into indicate
1056 // that the cleanup code should not destroy the variable.
1057 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
1058 Builder.CreateFlagStore(Builder.getTrue(), NRVOFlag);
1059 } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) {
1060 // Make sure not to return anything, but evaluate the expression
1061 // for side effects.
1065 // Do nothing (return value is left uninitialized)
1066 } else if (FnRetTy->isReferenceType()) {
1067 // If this function returns a reference, take the address of the expression
1068 // rather than the value.
1069 RValue Result = EmitReferenceBindingToExpr(RV);
1070 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
1072 switch (getEvaluationKind(RV->getType())) {
1074 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
1077 EmitComplexExprIntoLValue(RV, MakeAddrLValue(ReturnValue, RV->getType()),
1081 EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue,
1083 AggValueSlot::IsDestructed,
1084 AggValueSlot::DoesNotNeedGCBarriers,
1085 AggValueSlot::IsNotAliased));
1091 if (!RV || RV->isEvaluatable(getContext()))
1092 ++NumSimpleReturnExprs;
1094 cleanupScope.ForceCleanup();
1095 EmitBranchThroughCleanup(ReturnBlock);
1098 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
1099 // As long as debug info is modeled with instructions, we have to ensure we
1100 // have a place to insert here and write the stop point here.
1101 if (HaveInsertPoint())
1104 for (const auto *I : S.decls())
1108 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
1109 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1111 // If this code is reachable then emit a stop point (if generating
1112 // debug info). We have to do this ourselves because we are on the
1113 // "simple" statement path.
1114 if (HaveInsertPoint())
1117 EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
1120 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
1121 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1123 // If this code is reachable then emit a stop point (if generating
1124 // debug info). We have to do this ourselves because we are on the
1125 // "simple" statement path.
1126 if (HaveInsertPoint())
1129 EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
1132 /// EmitCaseStmtRange - If case statement range is not too big then
1133 /// add multiple cases to switch instruction, one for each value within
1134 /// the range. If range is too big then emit "if" condition check.
1135 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
1136 assert(S.getRHS() && "Expected RHS value in CaseStmt");
1138 llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
1139 llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
1141 // Emit the code for this case. We do this first to make sure it is
1142 // properly chained from our predecessor before generating the
1143 // switch machinery to enter this block.
1144 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1145 EmitBlockWithFallThrough(CaseDest, &S);
1146 EmitStmt(S.getSubStmt());
1148 // If range is empty, do nothing.
1149 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
1152 llvm::APInt Range = RHS - LHS;
1153 // FIXME: parameters such as this should not be hardcoded.
1154 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
1155 // Range is small enough to add multiple switch instruction cases.
1156 uint64_t Total = getProfileCount(&S);
1157 unsigned NCases = Range.getZExtValue() + 1;
1158 // We only have one region counter for the entire set of cases here, so we
1159 // need to divide the weights evenly between the generated cases, ensuring
1160 // that the total weight is preserved. E.g., a weight of 5 over three cases
1161 // will be distributed as weights of 2, 2, and 1.
1162 uint64_t Weight = Total / NCases, Rem = Total % NCases;
1163 for (unsigned I = 0; I != NCases; ++I) {
1165 SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
1168 SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
1174 // The range is too big. Emit "if" condition into a new block,
1175 // making sure to save and restore the current insertion point.
1176 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
1178 // Push this test onto the chain of range checks (which terminates
1179 // in the default basic block). The switch's default will be changed
1180 // to the top of this chain after switch emission is complete.
1181 llvm::BasicBlock *FalseDest = CaseRangeBlock;
1182 CaseRangeBlock = createBasicBlock("sw.caserange");
1184 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
1185 Builder.SetInsertPoint(CaseRangeBlock);
1187 // Emit range check.
1189 Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
1191 Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
1193 llvm::MDNode *Weights = nullptr;
1194 if (SwitchWeights) {
1195 uint64_t ThisCount = getProfileCount(&S);
1196 uint64_t DefaultCount = (*SwitchWeights)[0];
1197 Weights = createProfileWeights(ThisCount, DefaultCount);
1199 // Since we're chaining the switch default through each large case range, we
1200 // need to update the weight for the default, ie, the first case, to include
1202 (*SwitchWeights)[0] += ThisCount;
1204 Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
1206 // Restore the appropriate insertion point.
1208 Builder.SetInsertPoint(RestoreBB);
1210 Builder.ClearInsertionPoint();
1213 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
1214 // If there is no enclosing switch instance that we're aware of, then this
1215 // case statement and its block can be elided. This situation only happens
1216 // when we've constant-folded the switch, are emitting the constant case,
1217 // and part of the constant case includes another case statement. For
1218 // instance: switch (4) { case 4: do { case 5: } while (1); }
1220 EmitStmt(S.getSubStmt());
1224 // Handle case ranges.
1226 EmitCaseStmtRange(S);
1230 llvm::ConstantInt *CaseVal =
1231 Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
1233 // If the body of the case is just a 'break', try to not emit an empty block.
1234 // If we're profiling or we're not optimizing, leave the block in for better
1235 // debug and coverage analysis.
1236 if (!CGM.getCodeGenOpts().hasProfileClangInstr() &&
1237 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1238 isa<BreakStmt>(S.getSubStmt())) {
1239 JumpDest Block = BreakContinueStack.back().BreakBlock;
1241 // Only do this optimization if there are no cleanups that need emitting.
1242 if (isObviouslyBranchWithoutCleanups(Block)) {
1244 SwitchWeights->push_back(getProfileCount(&S));
1245 SwitchInsn->addCase(CaseVal, Block.getBlock());
1247 // If there was a fallthrough into this case, make sure to redirect it to
1248 // the end of the switch as well.
1249 if (Builder.GetInsertBlock()) {
1250 Builder.CreateBr(Block.getBlock());
1251 Builder.ClearInsertionPoint();
1257 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1258 EmitBlockWithFallThrough(CaseDest, &S);
1260 SwitchWeights->push_back(getProfileCount(&S));
1261 SwitchInsn->addCase(CaseVal, CaseDest);
1263 // Recursively emitting the statement is acceptable, but is not wonderful for
1264 // code where we have many case statements nested together, i.e.:
1268 // Handling this recursively will create a new block for each case statement
1269 // that falls through to the next case which is IR intensive. It also causes
1270 // deep recursion which can run into stack depth limitations. Handle
1271 // sequential non-range case statements specially.
1272 const CaseStmt *CurCase = &S;
1273 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1275 // Otherwise, iteratively add consecutive cases to this switch stmt.
1276 while (NextCase && NextCase->getRHS() == nullptr) {
1278 llvm::ConstantInt *CaseVal =
1279 Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1282 SwitchWeights->push_back(getProfileCount(NextCase));
1283 if (CGM.getCodeGenOpts().hasProfileClangInstr()) {
1284 CaseDest = createBasicBlock("sw.bb");
1285 EmitBlockWithFallThrough(CaseDest, &S);
1288 SwitchInsn->addCase(CaseVal, CaseDest);
1289 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1292 // Normal default recursion for non-cases.
1293 EmitStmt(CurCase->getSubStmt());
1296 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
1297 // If there is no enclosing switch instance that we're aware of, then this
1298 // default statement can be elided. This situation only happens when we've
1299 // constant-folded the switch.
1301 EmitStmt(S.getSubStmt());
1305 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1306 assert(DefaultBlock->empty() &&
1307 "EmitDefaultStmt: Default block already defined?");
1309 EmitBlockWithFallThrough(DefaultBlock, &S);
1311 EmitStmt(S.getSubStmt());
1314 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
1315 /// constant value that is being switched on, see if we can dead code eliminate
1316 /// the body of the switch to a simple series of statements to emit. Basically,
1317 /// on a switch (5) we want to find these statements:
1319 /// printf(...); <--
1323 /// and add them to the ResultStmts vector. If it is unsafe to do this
1324 /// transformation (for example, one of the elided statements contains a label
1325 /// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
1326 /// should include statements after it (e.g. the printf() line is a substmt of
1327 /// the case) then return CSFC_FallThrough. If we handled it and found a break
1328 /// statement, then return CSFC_Success.
1330 /// If Case is non-null, then we are looking for the specified case, checking
1331 /// that nothing we jump over contains labels. If Case is null, then we found
1332 /// the case and are looking for the break.
1334 /// If the recursive walk actually finds our Case, then we set FoundCase to
1337 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
1338 static CSFC_Result CollectStatementsForCase(const Stmt *S,
1339 const SwitchCase *Case,
1341 SmallVectorImpl<const Stmt*> &ResultStmts) {
1342 // If this is a null statement, just succeed.
1344 return Case ? CSFC_Success : CSFC_FallThrough;
1346 // If this is the switchcase (case 4: or default) that we're looking for, then
1347 // we're in business. Just add the substatement.
1348 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1351 return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
1355 // Otherwise, this is some other case or default statement, just ignore it.
1356 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1360 // If we are in the live part of the code and we found our break statement,
1361 // return a success!
1362 if (!Case && isa<BreakStmt>(S))
1363 return CSFC_Success;
1365 // If this is a switch statement, then it might contain the SwitchCase, the
1366 // break, or neither.
1367 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1368 // Handle this as two cases: we might be looking for the SwitchCase (if so
1369 // the skipped statements must be skippable) or we might already have it.
1370 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1371 bool StartedInLiveCode = FoundCase;
1372 unsigned StartSize = ResultStmts.size();
1374 // If we've not found the case yet, scan through looking for it.
1376 // Keep track of whether we see a skipped declaration. The code could be
1377 // using the declaration even if it is skipped, so we can't optimize out
1378 // the decl if the kept statements might refer to it.
1379 bool HadSkippedDecl = false;
1381 // If we're looking for the case, just see if we can skip each of the
1383 for (; Case && I != E; ++I) {
1384 HadSkippedDecl |= CodeGenFunction::mightAddDeclToScope(*I);
1386 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1387 case CSFC_Failure: return CSFC_Failure;
1389 // A successful result means that either 1) that the statement doesn't
1390 // have the case and is skippable, or 2) does contain the case value
1391 // and also contains the break to exit the switch. In the later case,
1392 // we just verify the rest of the statements are elidable.
1394 // If we found the case and skipped declarations, we can't do the
1397 return CSFC_Failure;
1399 for (++I; I != E; ++I)
1400 if (CodeGenFunction::ContainsLabel(*I, true))
1401 return CSFC_Failure;
1402 return CSFC_Success;
1405 case CSFC_FallThrough:
1406 // If we have a fallthrough condition, then we must have found the
1407 // case started to include statements. Consider the rest of the
1408 // statements in the compound statement as candidates for inclusion.
1409 assert(FoundCase && "Didn't find case but returned fallthrough?");
1410 // We recursively found Case, so we're not looking for it anymore.
1413 // If we found the case and skipped declarations, we can't do the
1416 return CSFC_Failure;
1422 return CSFC_Success;
1424 assert(!HadSkippedDecl && "fallthrough after skipping decl");
1427 // If we have statements in our range, then we know that the statements are
1428 // live and need to be added to the set of statements we're tracking.
1429 bool AnyDecls = false;
1430 for (; I != E; ++I) {
1431 AnyDecls |= CodeGenFunction::mightAddDeclToScope(*I);
1433 switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
1434 case CSFC_Failure: return CSFC_Failure;
1435 case CSFC_FallThrough:
1436 // A fallthrough result means that the statement was simple and just
1437 // included in ResultStmt, keep adding them afterwards.
1440 // A successful result means that we found the break statement and
1441 // stopped statement inclusion. We just ensure that any leftover stmts
1442 // are skippable and return success ourselves.
1443 for (++I; I != E; ++I)
1444 if (CodeGenFunction::ContainsLabel(*I, true))
1445 return CSFC_Failure;
1446 return CSFC_Success;
1450 // If we're about to fall out of a scope without hitting a 'break;', we
1451 // can't perform the optimization if there were any decls in that scope
1452 // (we'd lose their end-of-lifetime).
1454 // If the entire compound statement was live, there's one more thing we
1455 // can try before giving up: emit the whole thing as a single statement.
1456 // We can do that unless the statement contains a 'break;'.
1457 // FIXME: Such a break must be at the end of a construct within this one.
1458 // We could emit this by just ignoring the BreakStmts entirely.
1459 if (StartedInLiveCode && !CodeGenFunction::containsBreak(S)) {
1460 ResultStmts.resize(StartSize);
1461 ResultStmts.push_back(S);
1463 return CSFC_Failure;
1467 return CSFC_FallThrough;
1470 // Okay, this is some other statement that we don't handle explicitly, like a
1471 // for statement or increment etc. If we are skipping over this statement,
1472 // just verify it doesn't have labels, which would make it invalid to elide.
1474 if (CodeGenFunction::ContainsLabel(S, true))
1475 return CSFC_Failure;
1476 return CSFC_Success;
1479 // Otherwise, we want to include this statement. Everything is cool with that
1480 // so long as it doesn't contain a break out of the switch we're in.
1481 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1483 // Otherwise, everything is great. Include the statement and tell the caller
1484 // that we fall through and include the next statement as well.
1485 ResultStmts.push_back(S);
1486 return CSFC_FallThrough;
1489 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1490 /// then invoke CollectStatementsForCase to find the list of statements to emit
1491 /// for a switch on constant. See the comment above CollectStatementsForCase
1492 /// for more details.
1493 static bool FindCaseStatementsForValue(const SwitchStmt &S,
1494 const llvm::APSInt &ConstantCondValue,
1495 SmallVectorImpl<const Stmt*> &ResultStmts,
1497 const SwitchCase *&ResultCase) {
1498 // First step, find the switch case that is being branched to. We can do this
1499 // efficiently by scanning the SwitchCase list.
1500 const SwitchCase *Case = S.getSwitchCaseList();
1501 const DefaultStmt *DefaultCase = nullptr;
1503 for (; Case; Case = Case->getNextSwitchCase()) {
1504 // It's either a default or case. Just remember the default statement in
1505 // case we're not jumping to any numbered cases.
1506 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1511 // Check to see if this case is the one we're looking for.
1512 const CaseStmt *CS = cast<CaseStmt>(Case);
1513 // Don't handle case ranges yet.
1514 if (CS->getRHS()) return false;
1516 // If we found our case, remember it as 'case'.
1517 if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
1521 // If we didn't find a matching case, we use a default if it exists, or we
1522 // elide the whole switch body!
1524 // It is safe to elide the body of the switch if it doesn't contain labels
1525 // etc. If it is safe, return successfully with an empty ResultStmts list.
1527 return !CodeGenFunction::ContainsLabel(&S);
1531 // Ok, we know which case is being jumped to, try to collect all the
1532 // statements that follow it. This can fail for a variety of reasons. Also,
1533 // check to see that the recursive walk actually found our case statement.
1534 // Insane cases like this can fail to find it in the recursive walk since we
1535 // don't handle every stmt kind:
1539 bool FoundCase = false;
1541 return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1542 ResultStmts) != CSFC_Failure &&
1546 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1547 // Handle nested switch statements.
1548 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1549 SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
1550 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1552 // See if we can constant fold the condition of the switch and therefore only
1553 // emit the live case statement (if any) of the switch.
1554 llvm::APSInt ConstantCondValue;
1555 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1556 SmallVector<const Stmt*, 4> CaseStmts;
1557 const SwitchCase *Case = nullptr;
1558 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1559 getContext(), Case)) {
1561 incrementProfileCounter(Case);
1562 RunCleanupsScope ExecutedScope(*this);
1565 EmitStmt(S.getInit());
1567 // Emit the condition variable if needed inside the entire cleanup scope
1568 // used by this special case for constant folded switches.
1569 if (S.getConditionVariable())
1570 EmitAutoVarDecl(*S.getConditionVariable());
1572 // At this point, we are no longer "within" a switch instance, so
1573 // we can temporarily enforce this to ensure that any embedded case
1574 // statements are not emitted.
1575 SwitchInsn = nullptr;
1577 // Okay, we can dead code eliminate everything except this case. Emit the
1578 // specified series of statements and we're good.
1579 for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1580 EmitStmt(CaseStmts[i]);
1581 incrementProfileCounter(&S);
1583 // Now we want to restore the saved switch instance so that nested
1584 // switches continue to function properly
1585 SwitchInsn = SavedSwitchInsn;
1591 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1593 RunCleanupsScope ConditionScope(*this);
1596 EmitStmt(S.getInit());
1598 if (S.getConditionVariable())
1599 EmitAutoVarDecl(*S.getConditionVariable());
1600 llvm::Value *CondV = EmitScalarExpr(S.getCond());
1602 // Create basic block to hold stuff that comes after switch
1603 // statement. We also need to create a default block now so that
1604 // explicit case ranges tests can have a place to jump to on
1606 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1607 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1608 if (PGO.haveRegionCounts()) {
1609 // Walk the SwitchCase list to find how many there are.
1610 uint64_t DefaultCount = 0;
1611 unsigned NumCases = 0;
1612 for (const SwitchCase *Case = S.getSwitchCaseList();
1614 Case = Case->getNextSwitchCase()) {
1615 if (isa<DefaultStmt>(Case))
1616 DefaultCount = getProfileCount(Case);
1619 SwitchWeights = new SmallVector<uint64_t, 16>();
1620 SwitchWeights->reserve(NumCases);
1621 // The default needs to be first. We store the edge count, so we already
1622 // know the right weight.
1623 SwitchWeights->push_back(DefaultCount);
1625 CaseRangeBlock = DefaultBlock;
1627 // Clear the insertion point to indicate we are in unreachable code.
1628 Builder.ClearInsertionPoint();
1630 // All break statements jump to NextBlock. If BreakContinueStack is non-empty
1631 // then reuse last ContinueBlock.
1632 JumpDest OuterContinue;
1633 if (!BreakContinueStack.empty())
1634 OuterContinue = BreakContinueStack.back().ContinueBlock;
1636 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1638 // Emit switch body.
1639 EmitStmt(S.getBody());
1641 BreakContinueStack.pop_back();
1643 // Update the default block in case explicit case range tests have
1644 // been chained on top.
1645 SwitchInsn->setDefaultDest(CaseRangeBlock);
1647 // If a default was never emitted:
1648 if (!DefaultBlock->getParent()) {
1649 // If we have cleanups, emit the default block so that there's a
1650 // place to jump through the cleanups from.
1651 if (ConditionScope.requiresCleanups()) {
1652 EmitBlock(DefaultBlock);
1654 // Otherwise, just forward the default block to the switch end.
1656 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1657 delete DefaultBlock;
1661 ConditionScope.ForceCleanup();
1663 // Emit continuation.
1664 EmitBlock(SwitchExit.getBlock(), true);
1665 incrementProfileCounter(&S);
1667 // If the switch has a condition wrapped by __builtin_unpredictable,
1668 // create metadata that specifies that the switch is unpredictable.
1669 // Don't bother if not optimizing because that metadata would not be used.
1670 auto *Call = dyn_cast<CallExpr>(S.getCond());
1671 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1672 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1673 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1674 llvm::MDBuilder MDHelper(getLLVMContext());
1675 SwitchInsn->setMetadata(llvm::LLVMContext::MD_unpredictable,
1676 MDHelper.createUnpredictable());
1680 if (SwitchWeights) {
1681 assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
1682 "switch weights do not match switch cases");
1683 // If there's only one jump destination there's no sense weighting it.
1684 if (SwitchWeights->size() > 1)
1685 SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
1686 createProfileWeights(*SwitchWeights));
1687 delete SwitchWeights;
1689 SwitchInsn = SavedSwitchInsn;
1690 SwitchWeights = SavedSwitchWeights;
1691 CaseRangeBlock = SavedCRBlock;
1695 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1696 SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) {
1699 while (*Constraint) {
1700 switch (*Constraint) {
1702 Result += Target.convertConstraint(Constraint);
1708 case '=': // Will see this and the following in mult-alt constraints.
1711 case '#': // Ignore the rest of the constraint alternative.
1712 while (Constraint[1] && Constraint[1] != ',')
1717 Result += *Constraint;
1718 while (Constraint[1] && Constraint[1] == *Constraint)
1729 "Must pass output names to constraints with a symbolic name");
1731 bool result = Target.resolveSymbolicName(Constraint, *OutCons, Index);
1732 assert(result && "Could not resolve symbolic name"); (void)result;
1733 Result += llvm::utostr(Index);
1744 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1745 /// as using a particular register add that as a constraint that will be used
1746 /// in this asm stmt.
1748 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1749 const TargetInfo &Target, CodeGenModule &CGM,
1750 const AsmStmt &Stmt, const bool EarlyClobber) {
1751 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1754 const ValueDecl &Value = *AsmDeclRef->getDecl();
1755 const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1758 if (Variable->getStorageClass() != SC_Register)
1760 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1763 StringRef Register = Attr->getLabel();
1764 assert(Target.isValidGCCRegisterName(Register));
1765 // We're using validateOutputConstraint here because we only care if
1766 // this is a register constraint.
1767 TargetInfo::ConstraintInfo Info(Constraint, "");
1768 if (Target.validateOutputConstraint(Info) &&
1769 !Info.allowsRegister()) {
1770 CGM.ErrorUnsupported(&Stmt, "__asm__");
1773 // Canonicalize the register here before returning it.
1774 Register = Target.getNormalizedGCCRegisterName(Register);
1775 return (EarlyClobber ? "&{" : "{") + Register.str() + "}";
1779 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
1780 LValue InputValue, QualType InputType,
1781 std::string &ConstraintStr,
1782 SourceLocation Loc) {
1784 if (Info.allowsRegister() || !Info.allowsMemory()) {
1785 if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
1786 Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
1788 llvm::Type *Ty = ConvertType(InputType);
1789 uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
1790 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1791 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1792 Ty = llvm::PointerType::getUnqual(Ty);
1794 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1797 Arg = InputValue.getPointer();
1798 ConstraintStr += '*';
1802 Arg = InputValue.getPointer();
1803 ConstraintStr += '*';
1809 llvm::Value* CodeGenFunction::EmitAsmInput(
1810 const TargetInfo::ConstraintInfo &Info,
1811 const Expr *InputExpr,
1812 std::string &ConstraintStr) {
1813 // If this can't be a register or memory, i.e., has to be a constant
1814 // (immediate or symbolic), try to emit it as such.
1815 if (!Info.allowsRegister() && !Info.allowsMemory()) {
1816 llvm::APSInt Result;
1817 if (InputExpr->EvaluateAsInt(Result, getContext()))
1818 return llvm::ConstantInt::get(getLLVMContext(), Result);
1819 assert(!Info.requiresImmediateConstant() &&
1820 "Required-immediate inlineasm arg isn't constant?");
1823 if (Info.allowsRegister() || !Info.allowsMemory())
1824 if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
1825 return EmitScalarExpr(InputExpr);
1826 if (InputExpr->getStmtClass() == Expr::CXXThisExprClass)
1827 return EmitScalarExpr(InputExpr);
1828 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1829 LValue Dest = EmitLValue(InputExpr);
1830 return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
1831 InputExpr->getExprLoc());
1834 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1835 /// asm call instruction. The !srcloc MDNode contains a list of constant
1836 /// integers which are the source locations of the start of each line in the
1838 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1839 CodeGenFunction &CGF) {
1840 SmallVector<llvm::Metadata *, 8> Locs;
1841 // Add the location of the first line to the MDNode.
1842 Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1843 CGF.Int32Ty, Str->getLocStart().getRawEncoding())));
1844 StringRef StrVal = Str->getString();
1845 if (!StrVal.empty()) {
1846 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1847 const LangOptions &LangOpts = CGF.CGM.getLangOpts();
1848 unsigned StartToken = 0;
1849 unsigned ByteOffset = 0;
1851 // Add the location of the start of each subsequent line of the asm to the
1853 for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) {
1854 if (StrVal[i] != '\n') continue;
1855 SourceLocation LineLoc = Str->getLocationOfByte(
1856 i + 1, SM, LangOpts, CGF.getTarget(), &StartToken, &ByteOffset);
1857 Locs.push_back(llvm::ConstantAsMetadata::get(
1858 llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding())));
1862 return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1865 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1866 // Assemble the final asm string.
1867 std::string AsmString = S.generateAsmString(getContext());
1869 // Get all the output and input constraints together.
1870 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1871 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1873 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1875 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1876 Name = GAS->getOutputName(i);
1877 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
1878 bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
1879 assert(IsValid && "Failed to parse output constraint");
1880 OutputConstraintInfos.push_back(Info);
1883 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1885 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1886 Name = GAS->getInputName(i);
1887 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
1889 getTarget().validateInputConstraint(OutputConstraintInfos, Info);
1890 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1891 InputConstraintInfos.push_back(Info);
1894 std::string Constraints;
1896 std::vector<LValue> ResultRegDests;
1897 std::vector<QualType> ResultRegQualTys;
1898 std::vector<llvm::Type *> ResultRegTypes;
1899 std::vector<llvm::Type *> ResultTruncRegTypes;
1900 std::vector<llvm::Type *> ArgTypes;
1901 std::vector<llvm::Value*> Args;
1903 // Keep track of inout constraints.
1904 std::string InOutConstraints;
1905 std::vector<llvm::Value*> InOutArgs;
1906 std::vector<llvm::Type*> InOutArgTypes;
1908 // An inline asm can be marked readonly if it meets the following conditions:
1909 // - it doesn't have any sideeffects
1910 // - it doesn't clobber memory
1911 // - it doesn't return a value by-reference
1912 // It can be marked readnone if it doesn't have any input memory constraints
1913 // in addition to meeting the conditions listed above.
1914 bool ReadOnly = true, ReadNone = true;
1916 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1917 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1919 // Simplify the output constraint.
1920 std::string OutputConstraint(S.getOutputConstraint(i));
1921 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
1924 const Expr *OutExpr = S.getOutputExpr(i);
1925 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1927 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1928 getTarget(), CGM, S,
1929 Info.earlyClobber());
1931 LValue Dest = EmitLValue(OutExpr);
1932 if (!Constraints.empty())
1935 // If this is a register output, then make the inline asm return it
1936 // by-value. If this is a memory result, return the value by-reference.
1937 if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
1938 Constraints += "=" + OutputConstraint;
1939 ResultRegQualTys.push_back(OutExpr->getType());
1940 ResultRegDests.push_back(Dest);
1941 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1942 ResultTruncRegTypes.push_back(ResultRegTypes.back());
1944 // If this output is tied to an input, and if the input is larger, then
1945 // we need to set the actual result type of the inline asm node to be the
1946 // same as the input type.
1947 if (Info.hasMatchingInput()) {
1949 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1950 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1951 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1954 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1956 QualType InputTy = S.getInputExpr(InputNo)->getType();
1957 QualType OutputType = OutExpr->getType();
1959 uint64_t InputSize = getContext().getTypeSize(InputTy);
1960 if (getContext().getTypeSize(OutputType) < InputSize) {
1961 // Form the asm to return the value as a larger integer or fp type.
1962 ResultRegTypes.back() = ConvertType(InputTy);
1965 if (llvm::Type* AdjTy =
1966 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1967 ResultRegTypes.back()))
1968 ResultRegTypes.back() = AdjTy;
1970 CGM.getDiags().Report(S.getAsmLoc(),
1971 diag::err_asm_invalid_type_in_input)
1972 << OutExpr->getType() << OutputConstraint;
1975 ArgTypes.push_back(Dest.getAddress().getType());
1976 Args.push_back(Dest.getPointer());
1977 Constraints += "=*";
1978 Constraints += OutputConstraint;
1979 ReadOnly = ReadNone = false;
1982 if (Info.isReadWrite()) {
1983 InOutConstraints += ',';
1985 const Expr *InputExpr = S.getOutputExpr(i);
1986 llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
1988 InputExpr->getExprLoc());
1990 if (llvm::Type* AdjTy =
1991 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1993 Arg = Builder.CreateBitCast(Arg, AdjTy);
1995 if (Info.allowsRegister())
1996 InOutConstraints += llvm::utostr(i);
1998 InOutConstraints += OutputConstraint;
2000 InOutArgTypes.push_back(Arg->getType());
2001 InOutArgs.push_back(Arg);
2005 // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
2006 // to the return value slot. Only do this when returning in registers.
2007 if (isa<MSAsmStmt>(&S)) {
2008 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
2009 if (RetAI.isDirect() || RetAI.isExtend()) {
2010 // Make a fake lvalue for the return value slot.
2011 LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy);
2012 CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
2013 *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
2014 ResultRegDests, AsmString, S.getNumOutputs());
2019 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
2020 const Expr *InputExpr = S.getInputExpr(i);
2022 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
2024 if (Info.allowsMemory())
2027 if (!Constraints.empty())
2030 // Simplify the input constraint.
2031 std::string InputConstraint(S.getInputConstraint(i));
2032 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
2033 &OutputConstraintInfos);
2035 InputConstraint = AddVariableConstraints(
2036 InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
2037 getTarget(), CGM, S, false /* No EarlyClobber */);
2039 llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
2041 // If this input argument is tied to a larger output result, extend the
2042 // input to be the same size as the output. The LLVM backend wants to see
2043 // the input and output of a matching constraint be the same size. Note
2044 // that GCC does not define what the top bits are here. We use zext because
2045 // that is usually cheaper, but LLVM IR should really get an anyext someday.
2046 if (Info.hasTiedOperand()) {
2047 unsigned Output = Info.getTiedOperand();
2048 QualType OutputType = S.getOutputExpr(Output)->getType();
2049 QualType InputTy = InputExpr->getType();
2051 if (getContext().getTypeSize(OutputType) >
2052 getContext().getTypeSize(InputTy)) {
2053 // Use ptrtoint as appropriate so that we can do our extension.
2054 if (isa<llvm::PointerType>(Arg->getType()))
2055 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
2056 llvm::Type *OutputTy = ConvertType(OutputType);
2057 if (isa<llvm::IntegerType>(OutputTy))
2058 Arg = Builder.CreateZExt(Arg, OutputTy);
2059 else if (isa<llvm::PointerType>(OutputTy))
2060 Arg = Builder.CreateZExt(Arg, IntPtrTy);
2062 assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
2063 Arg = Builder.CreateFPExt(Arg, OutputTy);
2067 if (llvm::Type* AdjTy =
2068 getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
2070 Arg = Builder.CreateBitCast(Arg, AdjTy);
2072 CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
2073 << InputExpr->getType() << InputConstraint;
2075 ArgTypes.push_back(Arg->getType());
2076 Args.push_back(Arg);
2077 Constraints += InputConstraint;
2080 // Append the "input" part of inout constraints last.
2081 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
2082 ArgTypes.push_back(InOutArgTypes[i]);
2083 Args.push_back(InOutArgs[i]);
2085 Constraints += InOutConstraints;
2088 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
2089 StringRef Clobber = S.getClobber(i);
2091 if (Clobber == "memory")
2092 ReadOnly = ReadNone = false;
2093 else if (Clobber != "cc")
2094 Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
2096 if (!Constraints.empty())
2099 Constraints += "~{";
2100 Constraints += Clobber;
2104 // Add machine specific clobbers
2105 std::string MachineClobbers = getTarget().getClobbers();
2106 if (!MachineClobbers.empty()) {
2107 if (!Constraints.empty())
2109 Constraints += MachineClobbers;
2112 llvm::Type *ResultType;
2113 if (ResultRegTypes.empty())
2114 ResultType = VoidTy;
2115 else if (ResultRegTypes.size() == 1)
2116 ResultType = ResultRegTypes[0];
2118 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
2120 llvm::FunctionType *FTy =
2121 llvm::FunctionType::get(ResultType, ArgTypes, false);
2123 bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
2124 llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
2125 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
2126 llvm::InlineAsm *IA =
2127 llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
2128 /* IsAlignStack */ false, AsmDialect);
2129 llvm::CallInst *Result = Builder.CreateCall(IA, Args);
2130 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2131 llvm::Attribute::NoUnwind);
2133 // Attach readnone and readonly attributes.
2134 if (!HasSideEffect) {
2136 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2137 llvm::Attribute::ReadNone);
2139 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2140 llvm::Attribute::ReadOnly);
2143 // Slap the source location of the inline asm into a !srcloc metadata on the
2145 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S)) {
2146 Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
2149 // At least put the line number on MS inline asm blobs.
2150 auto Loc = llvm::ConstantInt::get(Int32Ty, S.getAsmLoc().getRawEncoding());
2151 Result->setMetadata("srcloc",
2152 llvm::MDNode::get(getLLVMContext(),
2153 llvm::ConstantAsMetadata::get(Loc)));
2156 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
2157 // Conservatively, mark all inline asm blocks in CUDA as convergent
2158 // (meaning, they may call an intrinsically convergent op, such as bar.sync,
2159 // and so can't have certain optimizations applied around them).
2160 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2161 llvm::Attribute::Convergent);
2164 // Extract all of the register value results from the asm.
2165 std::vector<llvm::Value*> RegResults;
2166 if (ResultRegTypes.size() == 1) {
2167 RegResults.push_back(Result);
2169 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
2170 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
2171 RegResults.push_back(Tmp);
2175 assert(RegResults.size() == ResultRegTypes.size());
2176 assert(RegResults.size() == ResultTruncRegTypes.size());
2177 assert(RegResults.size() == ResultRegDests.size());
2178 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
2179 llvm::Value *Tmp = RegResults[i];
2181 // If the result type of the LLVM IR asm doesn't match the result type of
2182 // the expression, do the conversion.
2183 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
2184 llvm::Type *TruncTy = ResultTruncRegTypes[i];
2186 // Truncate the integer result to the right size, note that TruncTy can be
2188 if (TruncTy->isFloatingPointTy())
2189 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
2190 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
2191 uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
2192 Tmp = Builder.CreateTrunc(Tmp,
2193 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
2194 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
2195 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
2196 uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
2197 Tmp = Builder.CreatePtrToInt(Tmp,
2198 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
2199 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2200 } else if (TruncTy->isIntegerTy()) {
2201 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2202 } else if (TruncTy->isVectorTy()) {
2203 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
2207 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
2211 LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) {
2212 const RecordDecl *RD = S.getCapturedRecordDecl();
2213 QualType RecordTy = getContext().getRecordType(RD);
2215 // Initialize the captured struct.
2217 MakeAddrLValue(CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
2219 RecordDecl::field_iterator CurField = RD->field_begin();
2220 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
2221 E = S.capture_init_end();
2222 I != E; ++I, ++CurField) {
2223 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
2224 if (CurField->hasCapturedVLAType()) {
2225 auto VAT = CurField->getCapturedVLAType();
2226 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2228 EmitInitializerForField(*CurField, LV, *I);
2235 /// Generate an outlined function for the body of a CapturedStmt, store any
2236 /// captured variables into the captured struct, and call the outlined function.
2238 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
2239 LValue CapStruct = InitCapturedStruct(S);
2241 // Emit the CapturedDecl
2242 CodeGenFunction CGF(CGM, true);
2243 CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K));
2244 llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
2245 delete CGF.CapturedStmtInfo;
2247 // Emit call to the helper function.
2248 EmitCallOrInvoke(F, CapStruct.getPointer());
2253 Address CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
2254 LValue CapStruct = InitCapturedStruct(S);
2255 return CapStruct.getAddress();
2258 /// Creates the outlined function for a CapturedStmt.
2260 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
2261 assert(CapturedStmtInfo &&
2262 "CapturedStmtInfo should be set when generating the captured function");
2263 const CapturedDecl *CD = S.getCapturedDecl();
2264 const RecordDecl *RD = S.getCapturedRecordDecl();
2265 SourceLocation Loc = S.getLocStart();
2266 assert(CD->hasBody() && "missing CapturedDecl body");
2268 // Build the argument list.
2269 ASTContext &Ctx = CGM.getContext();
2270 FunctionArgList Args;
2271 Args.append(CD->param_begin(), CD->param_end());
2273 // Create the function declaration.
2274 FunctionType::ExtInfo ExtInfo;
2275 const CGFunctionInfo &FuncInfo =
2276 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
2277 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
2280 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
2281 CapturedStmtInfo->getHelperName(), &CGM.getModule());
2282 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
2283 if (CD->isNothrow())
2284 F->addFnAttr(llvm::Attribute::NoUnwind);
2286 // Generate the function.
2287 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args,
2289 CD->getBody()->getLocStart());
2290 // Set the context parameter in CapturedStmtInfo.
2291 Address DeclPtr = GetAddrOfLocalVar(CD->getContextParam());
2292 CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
2294 // Initialize variable-length arrays.
2295 LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
2296 Ctx.getTagDeclType(RD));
2297 for (auto *FD : RD->fields()) {
2298 if (FD->hasCapturedVLAType()) {
2299 auto *ExprArg = EmitLoadOfLValue(EmitLValueForField(Base, FD),
2300 S.getLocStart()).getScalarVal();
2301 auto VAT = FD->getCapturedVLAType();
2302 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
2306 // If 'this' is captured, load it into CXXThisValue.
2307 if (CapturedStmtInfo->isCXXThisExprCaptured()) {
2308 FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
2309 LValue ThisLValue = EmitLValueForField(Base, FD);
2310 CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
2313 PGO.assignRegionCounters(GlobalDecl(CD), F);
2314 CapturedStmtInfo->EmitBody(*this, CD->getBody());
2315 FinishFunction(CD->getBodyRBrace());