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/PrettyStackTrace.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Sema/LoopHint.h"
22 #include "clang/Sema/SemaDiagnostic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/IR/CallSite.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/InlineAsm.h"
27 #include "llvm/IR/Intrinsics.h"
28 using namespace clang;
29 using namespace CodeGen;
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
36 if (CGDebugInfo *DI = getDebugInfo()) {
38 Loc = S->getLocStart();
39 DI->EmitLocation(Builder, Loc);
45 void CodeGenFunction::EmitStmt(const Stmt *S) {
46 assert(S && "Null statement?");
47 PGO.setCurrentStmt(S);
49 // These statements have their own debug info handling.
50 if (EmitSimpleStmt(S))
53 // Check if we are generating unreachable code.
54 if (!HaveInsertPoint()) {
55 // If so, and the statement doesn't contain a label, then we do not need to
56 // generate actual code. This is safe because (1) the current point is
57 // unreachable, so we don't need to execute the code, and (2) we've already
58 // handled the statements which update internal data structures (like the
59 // local variable map) which could be used by subsequent statements.
60 if (!ContainsLabel(S)) {
61 // Verify that any decl statements were handled as simple, they may be in
62 // scope of subsequent reachable statements.
63 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
67 // Otherwise, make a new block to hold the code.
71 // Generate a stoppoint if we are emitting debug info.
74 switch (S->getStmtClass()) {
75 case Stmt::NoStmtClass:
76 case Stmt::CXXCatchStmtClass:
77 case Stmt::SEHExceptStmtClass:
78 case Stmt::SEHFinallyStmtClass:
79 case Stmt::MSDependentExistsStmtClass:
80 llvm_unreachable("invalid statement class to emit generically");
81 case Stmt::NullStmtClass:
82 case Stmt::CompoundStmtClass:
83 case Stmt::DeclStmtClass:
84 case Stmt::LabelStmtClass:
85 case Stmt::AttributedStmtClass:
86 case Stmt::GotoStmtClass:
87 case Stmt::BreakStmtClass:
88 case Stmt::ContinueStmtClass:
89 case Stmt::DefaultStmtClass:
90 case Stmt::CaseStmtClass:
91 case Stmt::SEHLeaveStmtClass:
92 llvm_unreachable("should have emitted these statements as simple");
94 #define STMT(Type, Base)
95 #define ABSTRACT_STMT(Op)
96 #define EXPR(Type, Base) \
97 case Stmt::Type##Class:
98 #include "clang/AST/StmtNodes.inc"
100 // Remember the block we came in on.
101 llvm::BasicBlock *incoming = Builder.GetInsertBlock();
102 assert(incoming && "expression emission must have an insertion point");
104 EmitIgnoredExpr(cast<Expr>(S));
106 llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
107 assert(outgoing && "expression emission cleared block!");
109 // The expression emitters assume (reasonably!) that the insertion
110 // point is always set. To maintain that, the call-emission code
111 // for noreturn functions has to enter a new block with no
112 // predecessors. We want to kill that block and mark the current
113 // insertion point unreachable in the common case of a call like
114 // "exit();". Since expression emission doesn't otherwise create
115 // blocks with no predecessors, we can just test for that.
116 // However, we must be careful not to do this to our incoming
117 // block, because *statement* emission does sometimes create
118 // reachable blocks which will have no predecessors until later in
119 // the function. This occurs with, e.g., labels that are not
120 // reachable by fallthrough.
121 if (incoming != outgoing && outgoing->use_empty()) {
122 outgoing->eraseFromParent();
123 Builder.ClearInsertionPoint();
128 case Stmt::IndirectGotoStmtClass:
129 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
131 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
132 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
133 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
134 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
136 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
138 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
139 case Stmt::GCCAsmStmtClass: // Intentional fall-through.
140 case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
141 case Stmt::CapturedStmtClass: {
142 const CapturedStmt *CS = cast<CapturedStmt>(S);
143 EmitCapturedStmt(*CS, CS->getCapturedRegionKind());
146 case Stmt::ObjCAtTryStmtClass:
147 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
149 case Stmt::ObjCAtCatchStmtClass:
151 "@catch statements should be handled by EmitObjCAtTryStmt");
152 case Stmt::ObjCAtFinallyStmtClass:
154 "@finally statements should be handled by EmitObjCAtTryStmt");
155 case Stmt::ObjCAtThrowStmtClass:
156 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
158 case Stmt::ObjCAtSynchronizedStmtClass:
159 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
161 case Stmt::ObjCForCollectionStmtClass:
162 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
164 case Stmt::ObjCAutoreleasePoolStmtClass:
165 EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
168 case Stmt::CXXTryStmtClass:
169 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
171 case Stmt::CXXForRangeStmtClass:
172 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
174 case Stmt::SEHTryStmtClass:
175 EmitSEHTryStmt(cast<SEHTryStmt>(*S));
177 case Stmt::OMPParallelDirectiveClass:
178 EmitOMPParallelDirective(cast<OMPParallelDirective>(*S));
180 case Stmt::OMPSimdDirectiveClass:
181 EmitOMPSimdDirective(cast<OMPSimdDirective>(*S));
183 case Stmt::OMPForDirectiveClass:
184 EmitOMPForDirective(cast<OMPForDirective>(*S));
186 case Stmt::OMPForSimdDirectiveClass:
187 EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S));
189 case Stmt::OMPSectionsDirectiveClass:
190 EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S));
192 case Stmt::OMPSectionDirectiveClass:
193 EmitOMPSectionDirective(cast<OMPSectionDirective>(*S));
195 case Stmt::OMPSingleDirectiveClass:
196 EmitOMPSingleDirective(cast<OMPSingleDirective>(*S));
198 case Stmt::OMPMasterDirectiveClass:
199 EmitOMPMasterDirective(cast<OMPMasterDirective>(*S));
201 case Stmt::OMPCriticalDirectiveClass:
202 EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S));
204 case Stmt::OMPParallelForDirectiveClass:
205 EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S));
207 case Stmt::OMPParallelForSimdDirectiveClass:
208 EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S));
210 case Stmt::OMPParallelSectionsDirectiveClass:
211 EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S));
213 case Stmt::OMPTaskDirectiveClass:
214 EmitOMPTaskDirective(cast<OMPTaskDirective>(*S));
216 case Stmt::OMPTaskyieldDirectiveClass:
217 EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S));
219 case Stmt::OMPBarrierDirectiveClass:
220 EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S));
222 case Stmt::OMPTaskwaitDirectiveClass:
223 EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S));
225 case Stmt::OMPTaskgroupDirectiveClass:
226 EmitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*S));
228 case Stmt::OMPFlushDirectiveClass:
229 EmitOMPFlushDirective(cast<OMPFlushDirective>(*S));
231 case Stmt::OMPOrderedDirectiveClass:
232 EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S));
234 case Stmt::OMPAtomicDirectiveClass:
235 EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S));
237 case Stmt::OMPTargetDirectiveClass:
238 EmitOMPTargetDirective(cast<OMPTargetDirective>(*S));
240 case Stmt::OMPTeamsDirectiveClass:
241 EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S));
243 case Stmt::OMPCancellationPointDirectiveClass:
244 EmitOMPCancellationPointDirective(cast<OMPCancellationPointDirective>(*S));
246 case Stmt::OMPCancelDirectiveClass:
247 EmitOMPCancelDirective(cast<OMPCancelDirective>(*S));
252 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
253 switch (S->getStmtClass()) {
254 default: return false;
255 case Stmt::NullStmtClass: break;
256 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
257 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
258 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
259 case Stmt::AttributedStmtClass:
260 EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
261 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
262 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
263 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
264 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
265 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
266 case Stmt::SEHLeaveStmtClass: EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S)); break;
272 /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
273 /// this captures the expression result of the last sub-statement and returns it
274 /// (for use by the statement expression extension).
275 llvm::Value* CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
276 AggValueSlot AggSlot) {
277 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
278 "LLVM IR generation of compound statement ('{}')");
280 // Keep track of the current cleanup stack depth, including debug scopes.
281 LexicalScope Scope(*this, S.getSourceRange());
283 return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
287 CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S,
289 AggValueSlot AggSlot) {
291 for (CompoundStmt::const_body_iterator I = S.body_begin(),
292 E = S.body_end()-GetLast; I != E; ++I)
295 llvm::Value *RetAlloca = nullptr;
297 // We have to special case labels here. They are statements, but when put
298 // at the end of a statement expression, they yield the value of their
299 // subexpression. Handle this by walking through all labels we encounter,
300 // emitting them before we evaluate the subexpr.
301 const Stmt *LastStmt = S.body_back();
302 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
303 EmitLabel(LS->getDecl());
304 LastStmt = LS->getSubStmt();
309 QualType ExprTy = cast<Expr>(LastStmt)->getType();
310 if (hasAggregateEvaluationKind(ExprTy)) {
311 EmitAggExpr(cast<Expr>(LastStmt), AggSlot);
313 // We can't return an RValue here because there might be cleanups at
314 // the end of the StmtExpr. Because of that, we have to emit the result
315 // here into a temporary alloca.
316 RetAlloca = CreateMemTemp(ExprTy);
317 EmitAnyExprToMem(cast<Expr>(LastStmt), RetAlloca, Qualifiers(),
326 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
327 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
329 // If there is a cleanup stack, then we it isn't worth trying to
330 // simplify this block (we would need to remove it from the scope map
331 // and cleanup entry).
332 if (!EHStack.empty())
335 // Can only simplify direct branches.
336 if (!BI || !BI->isUnconditional())
339 // Can only simplify empty blocks.
340 if (BI != BB->begin())
343 BB->replaceAllUsesWith(BI->getSuccessor(0));
344 BI->eraseFromParent();
345 BB->eraseFromParent();
348 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
349 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
351 // Fall out of the current block (if necessary).
354 if (IsFinished && BB->use_empty()) {
359 // Place the block after the current block, if possible, or else at
360 // the end of the function.
361 if (CurBB && CurBB->getParent())
362 CurFn->getBasicBlockList().insertAfter(CurBB, BB);
364 CurFn->getBasicBlockList().push_back(BB);
365 Builder.SetInsertPoint(BB);
368 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
369 // Emit a branch from the current block to the target one if this
370 // was a real block. If this was just a fall-through block after a
371 // terminator, don't emit it.
372 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
374 if (!CurBB || CurBB->getTerminator()) {
375 // If there is no insert point or the previous block is already
376 // terminated, don't touch it.
378 // Otherwise, create a fall-through branch.
379 Builder.CreateBr(Target);
382 Builder.ClearInsertionPoint();
385 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
386 bool inserted = false;
387 for (llvm::User *u : block->users()) {
388 if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
389 CurFn->getBasicBlockList().insertAfter(insn->getParent(), block);
396 CurFn->getBasicBlockList().push_back(block);
398 Builder.SetInsertPoint(block);
401 CodeGenFunction::JumpDest
402 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
403 JumpDest &Dest = LabelMap[D];
404 if (Dest.isValid()) return Dest;
406 // Create, but don't insert, the new block.
407 Dest = JumpDest(createBasicBlock(D->getName()),
408 EHScopeStack::stable_iterator::invalid(),
409 NextCleanupDestIndex++);
413 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
414 // Add this label to the current lexical scope if we're within any
415 // normal cleanups. Jumps "in" to this label --- when permitted by
416 // the language --- may need to be routed around such cleanups.
417 if (EHStack.hasNormalCleanups() && CurLexicalScope)
418 CurLexicalScope->addLabel(D);
420 JumpDest &Dest = LabelMap[D];
422 // If we didn't need a forward reference to this label, just go
423 // ahead and create a destination at the current scope.
424 if (!Dest.isValid()) {
425 Dest = getJumpDestInCurrentScope(D->getName());
427 // Otherwise, we need to give this label a target depth and remove
428 // it from the branch-fixups list.
430 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
431 Dest.setScopeDepth(EHStack.stable_begin());
432 ResolveBranchFixups(Dest.getBlock());
435 EmitBlock(Dest.getBlock());
436 incrementProfileCounter(D->getStmt());
439 /// Change the cleanup scope of the labels in this lexical scope to
440 /// match the scope of the enclosing context.
441 void CodeGenFunction::LexicalScope::rescopeLabels() {
442 assert(!Labels.empty());
443 EHScopeStack::stable_iterator innermostScope
444 = CGF.EHStack.getInnermostNormalCleanup();
446 // Change the scope depth of all the labels.
447 for (SmallVectorImpl<const LabelDecl*>::const_iterator
448 i = Labels.begin(), e = Labels.end(); i != e; ++i) {
449 assert(CGF.LabelMap.count(*i));
450 JumpDest &dest = CGF.LabelMap.find(*i)->second;
451 assert(dest.getScopeDepth().isValid());
452 assert(innermostScope.encloses(dest.getScopeDepth()));
453 dest.setScopeDepth(innermostScope);
456 // Reparent the labels if the new scope also has cleanups.
457 if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
458 ParentScope->Labels.append(Labels.begin(), Labels.end());
463 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
464 EmitLabel(S.getDecl());
465 EmitStmt(S.getSubStmt());
468 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
469 const Stmt *SubStmt = S.getSubStmt();
470 switch (SubStmt->getStmtClass()) {
471 case Stmt::DoStmtClass:
472 EmitDoStmt(cast<DoStmt>(*SubStmt), S.getAttrs());
474 case Stmt::ForStmtClass:
475 EmitForStmt(cast<ForStmt>(*SubStmt), S.getAttrs());
477 case Stmt::WhileStmtClass:
478 EmitWhileStmt(cast<WhileStmt>(*SubStmt), S.getAttrs());
480 case Stmt::CXXForRangeStmtClass:
481 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*SubStmt), S.getAttrs());
488 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
489 // If this code is reachable then emit a stop point (if generating
490 // debug info). We have to do this ourselves because we are on the
491 // "simple" statement path.
492 if (HaveInsertPoint())
495 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
499 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
500 if (const LabelDecl *Target = S.getConstantTarget()) {
501 EmitBranchThroughCleanup(getJumpDestForLabel(Target));
505 // Ensure that we have an i8* for our PHI node.
506 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
508 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
510 // Get the basic block for the indirect goto.
511 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
513 // The first instruction in the block has to be the PHI for the switch dest,
514 // add an entry for this branch.
515 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
517 EmitBranch(IndGotoBB);
520 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
521 // C99 6.8.4.1: The first substatement is executed if the expression compares
522 // unequal to 0. The condition must be a scalar type.
523 LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
525 if (S.getConditionVariable())
526 EmitAutoVarDecl(*S.getConditionVariable());
528 // If the condition constant folds and can be elided, try to avoid emitting
529 // the condition and the dead arm of the if/else.
531 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) {
532 // Figure out which block (then or else) is executed.
533 const Stmt *Executed = S.getThen();
534 const Stmt *Skipped = S.getElse();
535 if (!CondConstant) // Condition false?
536 std::swap(Executed, Skipped);
538 // If the skipped block has no labels in it, just emit the executed block.
539 // This avoids emitting dead code and simplifies the CFG substantially.
540 if (!ContainsLabel(Skipped)) {
542 incrementProfileCounter(&S);
544 RunCleanupsScope ExecutedScope(*this);
551 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
552 // the conditional branch.
553 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
554 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
555 llvm::BasicBlock *ElseBlock = ContBlock;
557 ElseBlock = createBasicBlock("if.else");
559 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock,
560 getProfileCount(S.getThen()));
562 // Emit the 'then' code.
563 EmitBlock(ThenBlock);
564 incrementProfileCounter(&S);
566 RunCleanupsScope ThenScope(*this);
567 EmitStmt(S.getThen());
569 EmitBranch(ContBlock);
571 // Emit the 'else' code if present.
572 if (const Stmt *Else = S.getElse()) {
574 // There is no need to emit line number for an unconditional branch.
575 auto NL = ApplyDebugLocation::CreateEmpty(*this);
576 EmitBlock(ElseBlock);
579 RunCleanupsScope ElseScope(*this);
583 // There is no need to emit line number for an unconditional branch.
584 auto NL = ApplyDebugLocation::CreateEmpty(*this);
585 EmitBranch(ContBlock);
589 // Emit the continuation block for code after the if.
590 EmitBlock(ContBlock, true);
593 void CodeGenFunction::EmitCondBrHints(llvm::LLVMContext &Context,
594 llvm::BranchInst *CondBr,
595 ArrayRef<const Attr *> Attrs) {
596 // Return if there are no hints.
600 // Add vectorize and unroll hints to the metadata on the conditional branch.
602 // FIXME: Should this really start with a size of 1?
603 SmallVector<llvm::Metadata *, 2> Metadata(1);
604 for (const auto *Attr : Attrs) {
605 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(Attr);
607 // Skip non loop hint attributes
611 LoopHintAttr::OptionType Option = LH->getOption();
612 LoopHintAttr::LoopHintState State = LH->getState();
613 const char *MetadataName;
615 case LoopHintAttr::Vectorize:
616 case LoopHintAttr::VectorizeWidth:
617 MetadataName = "llvm.loop.vectorize.width";
619 case LoopHintAttr::Interleave:
620 case LoopHintAttr::InterleaveCount:
621 MetadataName = "llvm.loop.interleave.count";
623 case LoopHintAttr::Unroll:
624 // With the unroll loop hint, a non-zero value indicates full unrolling.
625 MetadataName = State == LoopHintAttr::Disable ? "llvm.loop.unroll.disable"
626 : "llvm.loop.unroll.full";
628 case LoopHintAttr::UnrollCount:
629 MetadataName = "llvm.loop.unroll.count";
633 Expr *ValueExpr = LH->getValue();
636 llvm::APSInt ValueAPS =
637 ValueExpr->EvaluateKnownConstInt(CGM.getContext());
638 ValueInt = static_cast<int>(ValueAPS.getSExtValue());
641 llvm::Constant *Value;
642 llvm::MDString *Name;
644 case LoopHintAttr::Vectorize:
645 case LoopHintAttr::Interleave:
646 if (State != LoopHintAttr::Disable) {
647 // FIXME: In the future I will modifiy the behavior of the metadata
648 // so we can enable/disable vectorization and interleaving separately.
649 Name = llvm::MDString::get(Context, "llvm.loop.vectorize.enable");
650 Value = Builder.getTrue();
653 // Vectorization/interleaving is disabled, set width/count to 1.
656 case LoopHintAttr::VectorizeWidth:
657 case LoopHintAttr::InterleaveCount:
658 case LoopHintAttr::UnrollCount:
659 Name = llvm::MDString::get(Context, MetadataName);
660 Value = llvm::ConstantInt::get(Int32Ty, ValueInt);
662 case LoopHintAttr::Unroll:
663 Name = llvm::MDString::get(Context, MetadataName);
668 SmallVector<llvm::Metadata *, 2> OpValues;
669 OpValues.push_back(Name);
671 OpValues.push_back(llvm::ConstantAsMetadata::get(Value));
673 // Set or overwrite metadata indicated by Name.
674 Metadata.push_back(llvm::MDNode::get(Context, OpValues));
677 // FIXME: This condition is never false. Should it be an assert?
678 if (!Metadata.empty()) {
679 // Add llvm.loop MDNode to CondBr.
680 llvm::MDNode *LoopID = llvm::MDNode::get(Context, Metadata);
681 LoopID->replaceOperandWith(0, LoopID); // First op points to itself.
683 CondBr->setMetadata("llvm.loop", LoopID);
687 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
688 ArrayRef<const Attr *> WhileAttrs) {
689 // Emit the header for the loop, which will also become
690 // the continue target.
691 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
692 EmitBlock(LoopHeader.getBlock());
694 LoopStack.push(LoopHeader.getBlock(), WhileAttrs);
696 // Create an exit block for when the condition fails, which will
697 // also become the break target.
698 JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
700 // Store the blocks to use for break and continue.
701 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
703 // C++ [stmt.while]p2:
704 // When the condition of a while statement is a declaration, the
705 // scope of the variable that is declared extends from its point
706 // of declaration (3.3.2) to the end of the while statement.
708 // The object created in a condition is destroyed and created
709 // with each iteration of the loop.
710 RunCleanupsScope ConditionScope(*this);
712 if (S.getConditionVariable())
713 EmitAutoVarDecl(*S.getConditionVariable());
715 // Evaluate the conditional in the while header. C99 6.8.5.1: The
716 // evaluation of the controlling expression takes place before each
717 // execution of the loop body.
718 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
720 // while(1) is common, avoid extra exit blocks. Be sure
721 // to correctly handle break/continue though.
722 bool EmitBoolCondBranch = true;
723 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
725 EmitBoolCondBranch = false;
727 // As long as the condition is true, go to the loop body.
728 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
729 if (EmitBoolCondBranch) {
730 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
731 if (ConditionScope.requiresCleanups())
732 ExitBlock = createBasicBlock("while.exit");
733 llvm::BranchInst *CondBr = Builder.CreateCondBr(
734 BoolCondVal, LoopBody, ExitBlock,
735 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
737 if (ExitBlock != LoopExit.getBlock()) {
738 EmitBlock(ExitBlock);
739 EmitBranchThroughCleanup(LoopExit);
742 // Attach metadata to loop body conditional branch.
743 EmitCondBrHints(LoopBody->getContext(), CondBr, WhileAttrs);
746 // Emit the loop body. We have to emit this in a cleanup scope
747 // because it might be a singleton DeclStmt.
749 RunCleanupsScope BodyScope(*this);
751 incrementProfileCounter(&S);
752 EmitStmt(S.getBody());
755 BreakContinueStack.pop_back();
757 // Immediately force cleanup.
758 ConditionScope.ForceCleanup();
761 // Branch to the loop header again.
762 EmitBranch(LoopHeader.getBlock());
766 // Emit the exit block.
767 EmitBlock(LoopExit.getBlock(), true);
769 // The LoopHeader typically is just a branch if we skipped emitting
770 // a branch, try to erase it.
771 if (!EmitBoolCondBranch)
772 SimplifyForwardingBlocks(LoopHeader.getBlock());
775 void CodeGenFunction::EmitDoStmt(const DoStmt &S,
776 ArrayRef<const Attr *> DoAttrs) {
777 JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
778 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
780 uint64_t ParentCount = getCurrentProfileCount();
782 // Store the blocks to use for break and continue.
783 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
785 // Emit the body of the loop.
786 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
788 LoopStack.push(LoopBody, DoAttrs);
790 EmitBlockWithFallThrough(LoopBody, &S);
792 RunCleanupsScope BodyScope(*this);
793 EmitStmt(S.getBody());
796 EmitBlock(LoopCond.getBlock());
798 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
799 // after each execution of the loop body."
801 // Evaluate the conditional in the while header.
802 // C99 6.8.5p2/p4: The first substatement is executed if the expression
803 // compares unequal to 0. The condition must be a scalar type.
804 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
806 BreakContinueStack.pop_back();
808 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
809 // to correctly handle break/continue though.
810 bool EmitBoolCondBranch = true;
811 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
813 EmitBoolCondBranch = false;
815 // As long as the condition is true, iterate the loop.
816 if (EmitBoolCondBranch) {
817 uint64_t BackedgeCount = getProfileCount(S.getBody()) - ParentCount;
818 llvm::BranchInst *CondBr = Builder.CreateCondBr(
819 BoolCondVal, LoopBody, LoopExit.getBlock(),
820 createProfileWeightsForLoop(S.getCond(), BackedgeCount));
822 // Attach metadata to loop body conditional branch.
823 EmitCondBrHints(LoopBody->getContext(), CondBr, DoAttrs);
828 // Emit the exit block.
829 EmitBlock(LoopExit.getBlock());
831 // The DoCond block typically is just a branch if we skipped
832 // emitting a branch, try to erase it.
833 if (!EmitBoolCondBranch)
834 SimplifyForwardingBlocks(LoopCond.getBlock());
837 void CodeGenFunction::EmitForStmt(const ForStmt &S,
838 ArrayRef<const Attr *> ForAttrs) {
839 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
841 LexicalScope ForScope(*this, S.getSourceRange());
843 // Evaluate the first part before the loop.
845 EmitStmt(S.getInit());
847 // Start the loop with a block that tests the condition.
848 // If there's an increment, the continue scope will be overwritten
850 JumpDest Continue = getJumpDestInCurrentScope("for.cond");
851 llvm::BasicBlock *CondBlock = Continue.getBlock();
852 EmitBlock(CondBlock);
854 LoopStack.push(CondBlock, ForAttrs);
856 // If the for loop doesn't have an increment we can just use the
857 // condition as the continue block. Otherwise we'll need to create
858 // a block for it (in the current scope, i.e. in the scope of the
859 // condition), and that we will become our continue block.
861 Continue = getJumpDestInCurrentScope("for.inc");
863 // Store the blocks to use for break and continue.
864 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
866 // Create a cleanup scope for the condition variable cleanups.
867 LexicalScope ConditionScope(*this, S.getSourceRange());
870 // If the for statement has a condition scope, emit the local variable
872 if (S.getConditionVariable()) {
873 EmitAutoVarDecl(*S.getConditionVariable());
876 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
877 // If there are any cleanups between here and the loop-exit scope,
878 // create a block to stage a loop exit along.
879 if (ForScope.requiresCleanups())
880 ExitBlock = createBasicBlock("for.cond.cleanup");
882 // As long as the condition is true, iterate the loop.
883 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
885 // C99 6.8.5p2/p4: The first substatement is executed if the expression
886 // compares unequal to 0. The condition must be a scalar type.
887 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
888 llvm::BranchInst *CondBr = Builder.CreateCondBr(
889 BoolCondVal, ForBody, ExitBlock,
890 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
892 // Attach metadata to loop body conditional branch.
893 EmitCondBrHints(ForBody->getContext(), CondBr, ForAttrs);
895 if (ExitBlock != LoopExit.getBlock()) {
896 EmitBlock(ExitBlock);
897 EmitBranchThroughCleanup(LoopExit);
902 // Treat it as a non-zero constant. Don't even create a new block for the
903 // body, just fall into it.
905 incrementProfileCounter(&S);
908 // Create a separate cleanup scope for the body, in case it is not
909 // a compound statement.
910 RunCleanupsScope BodyScope(*this);
911 EmitStmt(S.getBody());
914 // If there is an increment, emit it next.
916 EmitBlock(Continue.getBlock());
917 EmitStmt(S.getInc());
920 BreakContinueStack.pop_back();
922 ConditionScope.ForceCleanup();
925 EmitBranch(CondBlock);
927 ForScope.ForceCleanup();
931 // Emit the fall-through block.
932 EmitBlock(LoopExit.getBlock(), true);
936 CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
937 ArrayRef<const Attr *> ForAttrs) {
938 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
940 LexicalScope ForScope(*this, S.getSourceRange());
942 // Evaluate the first pieces before the loop.
943 EmitStmt(S.getRangeStmt());
944 EmitStmt(S.getBeginEndStmt());
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 LoopStack.push(CondBlock, ForAttrs);
954 // If there are any cleanups between here and the loop-exit scope,
955 // create a block to stage a loop exit along.
956 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
957 if (ForScope.requiresCleanups())
958 ExitBlock = createBasicBlock("for.cond.cleanup");
960 // The loop body, consisting of the specified body and the loop variable.
961 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
963 // The body is executed if the expression, contextually converted
965 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
966 llvm::BranchInst *CondBr = Builder.CreateCondBr(
967 BoolCondVal, ForBody, ExitBlock,
968 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
970 // Attach metadata to loop body conditional branch.
971 EmitCondBrHints(ForBody->getContext(), CondBr, ForAttrs);
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.getAggregateAddr(), Ty);
1017 EmitStoreOfComplex(RV.getComplexVal(),
1018 MakeNaturalAlignAddrLValue(ReturnValue, Ty),
1021 EmitBranchThroughCleanup(ReturnBlock);
1024 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
1025 /// if the function returns void, or may be missing one if the function returns
1026 /// non-void. Fun stuff :).
1027 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
1028 // Returning from an outlined SEH helper is UB, and we already warn on it.
1029 if (IsOutlinedSEHHelper) {
1030 Builder.CreateUnreachable();
1031 Builder.ClearInsertionPoint();
1034 // Emit the result value, even if unused, to evalute the side effects.
1035 const Expr *RV = S.getRetValue();
1037 // Treat block literals in a return expression as if they appeared
1038 // in their own scope. This permits a small, easily-implemented
1039 // exception to our over-conservative rules about not jumping to
1040 // statements following block literals with non-trivial cleanups.
1041 RunCleanupsScope cleanupScope(*this);
1042 if (const ExprWithCleanups *cleanups =
1043 dyn_cast_or_null<ExprWithCleanups>(RV)) {
1044 enterFullExpression(cleanups);
1045 RV = cleanups->getSubExpr();
1048 // FIXME: Clean this up by using an LValue for ReturnTemp,
1049 // EmitStoreThroughLValue, and EmitAnyExpr.
1050 if (getLangOpts().ElideConstructors &&
1051 S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
1052 // Apply the named return value optimization for this return statement,
1053 // which means doing nothing: the appropriate result has already been
1054 // constructed into the NRVO variable.
1056 // If there is an NRVO flag for this variable, set it to 1 into indicate
1057 // that the cleanup code should not destroy the variable.
1058 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
1059 Builder.CreateStore(Builder.getTrue(), NRVOFlag);
1060 } else if (!ReturnValue || (RV && RV->getType()->isVoidType())) {
1061 // Make sure not to return anything, but evaluate the expression
1062 // for side effects.
1066 // Do nothing (return value is left uninitialized)
1067 } else if (FnRetTy->isReferenceType()) {
1068 // If this function returns a reference, take the address of the expression
1069 // rather than the value.
1070 RValue Result = EmitReferenceBindingToExpr(RV);
1071 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
1073 switch (getEvaluationKind(RV->getType())) {
1075 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
1078 EmitComplexExprIntoLValue(RV,
1079 MakeNaturalAlignAddrLValue(ReturnValue, RV->getType()),
1082 case TEK_Aggregate: {
1083 CharUnits Alignment = getContext().getTypeAlignInChars(RV->getType());
1084 EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Alignment,
1086 AggValueSlot::IsDestructed,
1087 AggValueSlot::DoesNotNeedGCBarriers,
1088 AggValueSlot::IsNotAliased));
1095 if (!RV || RV->isEvaluatable(getContext()))
1096 ++NumSimpleReturnExprs;
1098 cleanupScope.ForceCleanup();
1099 EmitBranchThroughCleanup(ReturnBlock);
1102 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
1103 // As long as debug info is modeled with instructions, we have to ensure we
1104 // have a place to insert here and write the stop point here.
1105 if (HaveInsertPoint())
1108 for (const auto *I : S.decls())
1112 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
1113 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1115 // If this code is reachable then emit a stop point (if generating
1116 // debug info). We have to do this ourselves because we are on the
1117 // "simple" statement path.
1118 if (HaveInsertPoint())
1121 EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
1124 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
1125 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1127 // If this code is reachable then emit a stop point (if generating
1128 // debug info). We have to do this ourselves because we are on the
1129 // "simple" statement path.
1130 if (HaveInsertPoint())
1133 EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
1136 /// EmitCaseStmtRange - If case statement range is not too big then
1137 /// add multiple cases to switch instruction, one for each value within
1138 /// the range. If range is too big then emit "if" condition check.
1139 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
1140 assert(S.getRHS() && "Expected RHS value in CaseStmt");
1142 llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
1143 llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
1145 // Emit the code for this case. We do this first to make sure it is
1146 // properly chained from our predecessor before generating the
1147 // switch machinery to enter this block.
1148 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1149 EmitBlockWithFallThrough(CaseDest, &S);
1150 EmitStmt(S.getSubStmt());
1152 // If range is empty, do nothing.
1153 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
1156 llvm::APInt Range = RHS - LHS;
1157 // FIXME: parameters such as this should not be hardcoded.
1158 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
1159 // Range is small enough to add multiple switch instruction cases.
1160 uint64_t Total = getProfileCount(&S);
1161 unsigned NCases = Range.getZExtValue() + 1;
1162 // We only have one region counter for the entire set of cases here, so we
1163 // need to divide the weights evenly between the generated cases, ensuring
1164 // that the total weight is preserved. E.g., a weight of 5 over three cases
1165 // will be distributed as weights of 2, 2, and 1.
1166 uint64_t Weight = Total / NCases, Rem = Total % NCases;
1167 for (unsigned I = 0; I != NCases; ++I) {
1169 SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
1172 SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
1178 // The range is too big. Emit "if" condition into a new block,
1179 // making sure to save and restore the current insertion point.
1180 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
1182 // Push this test onto the chain of range checks (which terminates
1183 // in the default basic block). The switch's default will be changed
1184 // to the top of this chain after switch emission is complete.
1185 llvm::BasicBlock *FalseDest = CaseRangeBlock;
1186 CaseRangeBlock = createBasicBlock("sw.caserange");
1188 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
1189 Builder.SetInsertPoint(CaseRangeBlock);
1191 // Emit range check.
1193 Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
1195 Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
1197 llvm::MDNode *Weights = nullptr;
1198 if (SwitchWeights) {
1199 uint64_t ThisCount = getProfileCount(&S);
1200 uint64_t DefaultCount = (*SwitchWeights)[0];
1201 Weights = createProfileWeights(ThisCount, DefaultCount);
1203 // Since we're chaining the switch default through each large case range, we
1204 // need to update the weight for the default, ie, the first case, to include
1206 (*SwitchWeights)[0] += ThisCount;
1208 Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
1210 // Restore the appropriate insertion point.
1212 Builder.SetInsertPoint(RestoreBB);
1214 Builder.ClearInsertionPoint();
1217 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
1218 // If there is no enclosing switch instance that we're aware of, then this
1219 // case statement and its block can be elided. This situation only happens
1220 // when we've constant-folded the switch, are emitting the constant case,
1221 // and part of the constant case includes another case statement. For
1222 // instance: switch (4) { case 4: do { case 5: } while (1); }
1224 EmitStmt(S.getSubStmt());
1228 // Handle case ranges.
1230 EmitCaseStmtRange(S);
1234 llvm::ConstantInt *CaseVal =
1235 Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
1237 // If the body of the case is just a 'break', try to not emit an empty block.
1238 // If we're profiling or we're not optimizing, leave the block in for better
1239 // debug and coverage analysis.
1240 if (!CGM.getCodeGenOpts().ProfileInstrGenerate &&
1241 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1242 isa<BreakStmt>(S.getSubStmt())) {
1243 JumpDest Block = BreakContinueStack.back().BreakBlock;
1245 // Only do this optimization if there are no cleanups that need emitting.
1246 if (isObviouslyBranchWithoutCleanups(Block)) {
1248 SwitchWeights->push_back(getProfileCount(&S));
1249 SwitchInsn->addCase(CaseVal, Block.getBlock());
1251 // If there was a fallthrough into this case, make sure to redirect it to
1252 // the end of the switch as well.
1253 if (Builder.GetInsertBlock()) {
1254 Builder.CreateBr(Block.getBlock());
1255 Builder.ClearInsertionPoint();
1261 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1262 EmitBlockWithFallThrough(CaseDest, &S);
1264 SwitchWeights->push_back(getProfileCount(&S));
1265 SwitchInsn->addCase(CaseVal, CaseDest);
1267 // Recursively emitting the statement is acceptable, but is not wonderful for
1268 // code where we have many case statements nested together, i.e.:
1272 // Handling this recursively will create a new block for each case statement
1273 // that falls through to the next case which is IR intensive. It also causes
1274 // deep recursion which can run into stack depth limitations. Handle
1275 // sequential non-range case statements specially.
1276 const CaseStmt *CurCase = &S;
1277 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1279 // Otherwise, iteratively add consecutive cases to this switch stmt.
1280 while (NextCase && NextCase->getRHS() == nullptr) {
1282 llvm::ConstantInt *CaseVal =
1283 Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1286 SwitchWeights->push_back(getProfileCount(NextCase));
1287 if (CGM.getCodeGenOpts().ProfileInstrGenerate) {
1288 CaseDest = createBasicBlock("sw.bb");
1289 EmitBlockWithFallThrough(CaseDest, &S);
1292 SwitchInsn->addCase(CaseVal, CaseDest);
1293 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1296 // Normal default recursion for non-cases.
1297 EmitStmt(CurCase->getSubStmt());
1300 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
1301 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1302 assert(DefaultBlock->empty() &&
1303 "EmitDefaultStmt: Default block already defined?");
1305 EmitBlockWithFallThrough(DefaultBlock, &S);
1307 EmitStmt(S.getSubStmt());
1310 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
1311 /// constant value that is being switched on, see if we can dead code eliminate
1312 /// the body of the switch to a simple series of statements to emit. Basically,
1313 /// on a switch (5) we want to find these statements:
1315 /// printf(...); <--
1319 /// and add them to the ResultStmts vector. If it is unsafe to do this
1320 /// transformation (for example, one of the elided statements contains a label
1321 /// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
1322 /// should include statements after it (e.g. the printf() line is a substmt of
1323 /// the case) then return CSFC_FallThrough. If we handled it and found a break
1324 /// statement, then return CSFC_Success.
1326 /// If Case is non-null, then we are looking for the specified case, checking
1327 /// that nothing we jump over contains labels. If Case is null, then we found
1328 /// the case and are looking for the break.
1330 /// If the recursive walk actually finds our Case, then we set FoundCase to
1333 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
1334 static CSFC_Result CollectStatementsForCase(const Stmt *S,
1335 const SwitchCase *Case,
1337 SmallVectorImpl<const Stmt*> &ResultStmts) {
1338 // If this is a null statement, just succeed.
1340 return Case ? CSFC_Success : CSFC_FallThrough;
1342 // If this is the switchcase (case 4: or default) that we're looking for, then
1343 // we're in business. Just add the substatement.
1344 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1347 return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
1351 // Otherwise, this is some other case or default statement, just ignore it.
1352 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1356 // If we are in the live part of the code and we found our break statement,
1357 // return a success!
1358 if (!Case && isa<BreakStmt>(S))
1359 return CSFC_Success;
1361 // If this is a switch statement, then it might contain the SwitchCase, the
1362 // break, or neither.
1363 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1364 // Handle this as two cases: we might be looking for the SwitchCase (if so
1365 // the skipped statements must be skippable) or we might already have it.
1366 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1368 // Keep track of whether we see a skipped declaration. The code could be
1369 // using the declaration even if it is skipped, so we can't optimize out
1370 // the decl if the kept statements might refer to it.
1371 bool HadSkippedDecl = false;
1373 // If we're looking for the case, just see if we can skip each of the
1375 for (; Case && I != E; ++I) {
1376 HadSkippedDecl |= isa<DeclStmt>(*I);
1378 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1379 case CSFC_Failure: return CSFC_Failure;
1381 // A successful result means that either 1) that the statement doesn't
1382 // have the case and is skippable, or 2) does contain the case value
1383 // and also contains the break to exit the switch. In the later case,
1384 // we just verify the rest of the statements are elidable.
1386 // If we found the case and skipped declarations, we can't do the
1389 return CSFC_Failure;
1391 for (++I; I != E; ++I)
1392 if (CodeGenFunction::ContainsLabel(*I, true))
1393 return CSFC_Failure;
1394 return CSFC_Success;
1397 case CSFC_FallThrough:
1398 // If we have a fallthrough condition, then we must have found the
1399 // case started to include statements. Consider the rest of the
1400 // statements in the compound statement as candidates for inclusion.
1401 assert(FoundCase && "Didn't find case but returned fallthrough?");
1402 // We recursively found Case, so we're not looking for it anymore.
1405 // If we found the case and skipped declarations, we can't do the
1408 return CSFC_Failure;
1414 // If we have statements in our range, then we know that the statements are
1415 // live and need to be added to the set of statements we're tracking.
1416 for (; I != E; ++I) {
1417 switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
1418 case CSFC_Failure: return CSFC_Failure;
1419 case CSFC_FallThrough:
1420 // A fallthrough result means that the statement was simple and just
1421 // included in ResultStmt, keep adding them afterwards.
1424 // A successful result means that we found the break statement and
1425 // stopped statement inclusion. We just ensure that any leftover stmts
1426 // are skippable and return success ourselves.
1427 for (++I; I != E; ++I)
1428 if (CodeGenFunction::ContainsLabel(*I, true))
1429 return CSFC_Failure;
1430 return CSFC_Success;
1434 return Case ? CSFC_Success : CSFC_FallThrough;
1437 // Okay, this is some other statement that we don't handle explicitly, like a
1438 // for statement or increment etc. If we are skipping over this statement,
1439 // just verify it doesn't have labels, which would make it invalid to elide.
1441 if (CodeGenFunction::ContainsLabel(S, true))
1442 return CSFC_Failure;
1443 return CSFC_Success;
1446 // Otherwise, we want to include this statement. Everything is cool with that
1447 // so long as it doesn't contain a break out of the switch we're in.
1448 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1450 // Otherwise, everything is great. Include the statement and tell the caller
1451 // that we fall through and include the next statement as well.
1452 ResultStmts.push_back(S);
1453 return CSFC_FallThrough;
1456 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1457 /// then invoke CollectStatementsForCase to find the list of statements to emit
1458 /// for a switch on constant. See the comment above CollectStatementsForCase
1459 /// for more details.
1460 static bool FindCaseStatementsForValue(const SwitchStmt &S,
1461 const llvm::APSInt &ConstantCondValue,
1462 SmallVectorImpl<const Stmt*> &ResultStmts,
1464 const SwitchCase *&ResultCase) {
1465 // First step, find the switch case that is being branched to. We can do this
1466 // efficiently by scanning the SwitchCase list.
1467 const SwitchCase *Case = S.getSwitchCaseList();
1468 const DefaultStmt *DefaultCase = nullptr;
1470 for (; Case; Case = Case->getNextSwitchCase()) {
1471 // It's either a default or case. Just remember the default statement in
1472 // case we're not jumping to any numbered cases.
1473 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1478 // Check to see if this case is the one we're looking for.
1479 const CaseStmt *CS = cast<CaseStmt>(Case);
1480 // Don't handle case ranges yet.
1481 if (CS->getRHS()) return false;
1483 // If we found our case, remember it as 'case'.
1484 if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
1488 // If we didn't find a matching case, we use a default if it exists, or we
1489 // elide the whole switch body!
1491 // It is safe to elide the body of the switch if it doesn't contain labels
1492 // etc. If it is safe, return successfully with an empty ResultStmts list.
1494 return !CodeGenFunction::ContainsLabel(&S);
1498 // Ok, we know which case is being jumped to, try to collect all the
1499 // statements that follow it. This can fail for a variety of reasons. Also,
1500 // check to see that the recursive walk actually found our case statement.
1501 // Insane cases like this can fail to find it in the recursive walk since we
1502 // don't handle every stmt kind:
1506 bool FoundCase = false;
1508 return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1509 ResultStmts) != CSFC_Failure &&
1513 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1514 // Handle nested switch statements.
1515 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1516 SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
1517 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1519 // See if we can constant fold the condition of the switch and therefore only
1520 // emit the live case statement (if any) of the switch.
1521 llvm::APSInt ConstantCondValue;
1522 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1523 SmallVector<const Stmt*, 4> CaseStmts;
1524 const SwitchCase *Case = nullptr;
1525 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1526 getContext(), Case)) {
1528 incrementProfileCounter(Case);
1529 RunCleanupsScope ExecutedScope(*this);
1531 // Emit the condition variable if needed inside the entire cleanup scope
1532 // used by this special case for constant folded switches.
1533 if (S.getConditionVariable())
1534 EmitAutoVarDecl(*S.getConditionVariable());
1536 // At this point, we are no longer "within" a switch instance, so
1537 // we can temporarily enforce this to ensure that any embedded case
1538 // statements are not emitted.
1539 SwitchInsn = nullptr;
1541 // Okay, we can dead code eliminate everything except this case. Emit the
1542 // specified series of statements and we're good.
1543 for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1544 EmitStmt(CaseStmts[i]);
1545 incrementProfileCounter(&S);
1547 // Now we want to restore the saved switch instance so that nested
1548 // switches continue to function properly
1549 SwitchInsn = SavedSwitchInsn;
1555 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1557 RunCleanupsScope ConditionScope(*this);
1558 if (S.getConditionVariable())
1559 EmitAutoVarDecl(*S.getConditionVariable());
1560 llvm::Value *CondV = EmitScalarExpr(S.getCond());
1562 // Create basic block to hold stuff that comes after switch
1563 // statement. We also need to create a default block now so that
1564 // explicit case ranges tests can have a place to jump to on
1566 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1567 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1568 if (PGO.haveRegionCounts()) {
1569 // Walk the SwitchCase list to find how many there are.
1570 uint64_t DefaultCount = 0;
1571 unsigned NumCases = 0;
1572 for (const SwitchCase *Case = S.getSwitchCaseList();
1574 Case = Case->getNextSwitchCase()) {
1575 if (isa<DefaultStmt>(Case))
1576 DefaultCount = getProfileCount(Case);
1579 SwitchWeights = new SmallVector<uint64_t, 16>();
1580 SwitchWeights->reserve(NumCases);
1581 // The default needs to be first. We store the edge count, so we already
1582 // know the right weight.
1583 SwitchWeights->push_back(DefaultCount);
1585 CaseRangeBlock = DefaultBlock;
1587 // Clear the insertion point to indicate we are in unreachable code.
1588 Builder.ClearInsertionPoint();
1590 // All break statements jump to NextBlock. If BreakContinueStack is non-empty
1591 // then reuse last ContinueBlock.
1592 JumpDest OuterContinue;
1593 if (!BreakContinueStack.empty())
1594 OuterContinue = BreakContinueStack.back().ContinueBlock;
1596 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1598 // Emit switch body.
1599 EmitStmt(S.getBody());
1601 BreakContinueStack.pop_back();
1603 // Update the default block in case explicit case range tests have
1604 // been chained on top.
1605 SwitchInsn->setDefaultDest(CaseRangeBlock);
1607 // If a default was never emitted:
1608 if (!DefaultBlock->getParent()) {
1609 // If we have cleanups, emit the default block so that there's a
1610 // place to jump through the cleanups from.
1611 if (ConditionScope.requiresCleanups()) {
1612 EmitBlock(DefaultBlock);
1614 // Otherwise, just forward the default block to the switch end.
1616 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1617 delete DefaultBlock;
1621 ConditionScope.ForceCleanup();
1623 // Emit continuation.
1624 EmitBlock(SwitchExit.getBlock(), true);
1625 incrementProfileCounter(&S);
1627 if (SwitchWeights) {
1628 assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
1629 "switch weights do not match switch cases");
1630 // If there's only one jump destination there's no sense weighting it.
1631 if (SwitchWeights->size() > 1)
1632 SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
1633 createProfileWeights(*SwitchWeights));
1634 delete SwitchWeights;
1636 SwitchInsn = SavedSwitchInsn;
1637 SwitchWeights = SavedSwitchWeights;
1638 CaseRangeBlock = SavedCRBlock;
1642 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1643 SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) {
1646 while (*Constraint) {
1647 switch (*Constraint) {
1649 Result += Target.convertConstraint(Constraint);
1655 case '=': // Will see this and the following in mult-alt constraints.
1658 case '#': // Ignore the rest of the constraint alternative.
1659 while (Constraint[1] && Constraint[1] != ',')
1664 Result += *Constraint;
1665 while (Constraint[1] && Constraint[1] == *Constraint)
1676 "Must pass output names to constraints with a symbolic name");
1678 bool result = Target.resolveSymbolicName(Constraint,
1680 OutCons->size(), Index);
1681 assert(result && "Could not resolve symbolic name"); (void)result;
1682 Result += llvm::utostr(Index);
1693 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1694 /// as using a particular register add that as a constraint that will be used
1695 /// in this asm stmt.
1697 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1698 const TargetInfo &Target, CodeGenModule &CGM,
1699 const AsmStmt &Stmt, const bool EarlyClobber) {
1700 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1703 const ValueDecl &Value = *AsmDeclRef->getDecl();
1704 const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1707 if (Variable->getStorageClass() != SC_Register)
1709 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1712 StringRef Register = Attr->getLabel();
1713 assert(Target.isValidGCCRegisterName(Register));
1714 // We're using validateOutputConstraint here because we only care if
1715 // this is a register constraint.
1716 TargetInfo::ConstraintInfo Info(Constraint, "");
1717 if (Target.validateOutputConstraint(Info) &&
1718 !Info.allowsRegister()) {
1719 CGM.ErrorUnsupported(&Stmt, "__asm__");
1722 // Canonicalize the register here before returning it.
1723 Register = Target.getNormalizedGCCRegisterName(Register);
1724 return (EarlyClobber ? "&{" : "{") + Register.str() + "}";
1728 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
1729 LValue InputValue, QualType InputType,
1730 std::string &ConstraintStr,
1731 SourceLocation Loc) {
1733 if (Info.allowsRegister() || !Info.allowsMemory()) {
1734 if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
1735 Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
1737 llvm::Type *Ty = ConvertType(InputType);
1738 uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
1739 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1740 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1741 Ty = llvm::PointerType::getUnqual(Ty);
1743 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1746 Arg = InputValue.getAddress();
1747 ConstraintStr += '*';
1751 Arg = InputValue.getAddress();
1752 ConstraintStr += '*';
1758 llvm::Value* CodeGenFunction::EmitAsmInput(
1759 const TargetInfo::ConstraintInfo &Info,
1760 const Expr *InputExpr,
1761 std::string &ConstraintStr) {
1762 // If this can't be a register or memory, i.e., has to be a constant
1763 // (immediate or symbolic), try to emit it as such.
1764 if (!Info.allowsRegister() && !Info.allowsMemory()) {
1765 llvm::APSInt Result;
1766 if (InputExpr->EvaluateAsInt(Result, getContext()))
1767 return llvm::ConstantInt::get(getLLVMContext(), Result);
1768 assert(!Info.requiresImmediateConstant() &&
1769 "Required-immediate inlineasm arg isn't constant?");
1772 if (Info.allowsRegister() || !Info.allowsMemory())
1773 if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
1774 return EmitScalarExpr(InputExpr);
1776 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1777 LValue Dest = EmitLValue(InputExpr);
1778 return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
1779 InputExpr->getExprLoc());
1782 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1783 /// asm call instruction. The !srcloc MDNode contains a list of constant
1784 /// integers which are the source locations of the start of each line in the
1786 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1787 CodeGenFunction &CGF) {
1788 SmallVector<llvm::Metadata *, 8> Locs;
1789 // Add the location of the first line to the MDNode.
1790 Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1791 CGF.Int32Ty, Str->getLocStart().getRawEncoding())));
1792 StringRef StrVal = Str->getString();
1793 if (!StrVal.empty()) {
1794 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1795 const LangOptions &LangOpts = CGF.CGM.getLangOpts();
1797 // Add the location of the start of each subsequent line of the asm to the
1799 for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
1800 if (StrVal[i] != '\n') continue;
1801 SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
1803 Locs.push_back(llvm::ConstantAsMetadata::get(
1804 llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding())));
1808 return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1811 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1812 // Assemble the final asm string.
1813 std::string AsmString = S.generateAsmString(getContext());
1815 // Get all the output and input constraints together.
1816 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1817 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1819 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1821 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1822 Name = GAS->getOutputName(i);
1823 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
1824 bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
1825 assert(IsValid && "Failed to parse output constraint");
1826 OutputConstraintInfos.push_back(Info);
1829 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1831 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1832 Name = GAS->getInputName(i);
1833 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
1835 getTarget().validateInputConstraint(OutputConstraintInfos.data(),
1836 S.getNumOutputs(), Info);
1837 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1838 InputConstraintInfos.push_back(Info);
1841 std::string Constraints;
1843 std::vector<LValue> ResultRegDests;
1844 std::vector<QualType> ResultRegQualTys;
1845 std::vector<llvm::Type *> ResultRegTypes;
1846 std::vector<llvm::Type *> ResultTruncRegTypes;
1847 std::vector<llvm::Type *> ArgTypes;
1848 std::vector<llvm::Value*> Args;
1850 // Keep track of inout constraints.
1851 std::string InOutConstraints;
1852 std::vector<llvm::Value*> InOutArgs;
1853 std::vector<llvm::Type*> InOutArgTypes;
1855 // An inline asm can be marked readonly if it meets the following conditions:
1856 // - it doesn't have any sideeffects
1857 // - it doesn't clobber memory
1858 // - it doesn't return a value by-reference
1859 // It can be marked readnone if it doesn't have any input memory constraints
1860 // in addition to meeting the conditions listed above.
1861 bool ReadOnly = true, ReadNone = true;
1863 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1864 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1866 // Simplify the output constraint.
1867 std::string OutputConstraint(S.getOutputConstraint(i));
1868 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
1871 const Expr *OutExpr = S.getOutputExpr(i);
1872 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1874 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1875 getTarget(), CGM, S,
1876 Info.earlyClobber());
1878 LValue Dest = EmitLValue(OutExpr);
1879 if (!Constraints.empty())
1882 // If this is a register output, then make the inline asm return it
1883 // by-value. If this is a memory result, return the value by-reference.
1884 if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
1885 Constraints += "=" + OutputConstraint;
1886 ResultRegQualTys.push_back(OutExpr->getType());
1887 ResultRegDests.push_back(Dest);
1888 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1889 ResultTruncRegTypes.push_back(ResultRegTypes.back());
1891 // If this output is tied to an input, and if the input is larger, then
1892 // we need to set the actual result type of the inline asm node to be the
1893 // same as the input type.
1894 if (Info.hasMatchingInput()) {
1896 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1897 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1898 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1901 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1903 QualType InputTy = S.getInputExpr(InputNo)->getType();
1904 QualType OutputType = OutExpr->getType();
1906 uint64_t InputSize = getContext().getTypeSize(InputTy);
1907 if (getContext().getTypeSize(OutputType) < InputSize) {
1908 // Form the asm to return the value as a larger integer or fp type.
1909 ResultRegTypes.back() = ConvertType(InputTy);
1912 if (llvm::Type* AdjTy =
1913 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1914 ResultRegTypes.back()))
1915 ResultRegTypes.back() = AdjTy;
1917 CGM.getDiags().Report(S.getAsmLoc(),
1918 diag::err_asm_invalid_type_in_input)
1919 << OutExpr->getType() << OutputConstraint;
1922 ArgTypes.push_back(Dest.getAddress()->getType());
1923 Args.push_back(Dest.getAddress());
1924 Constraints += "=*";
1925 Constraints += OutputConstraint;
1926 ReadOnly = ReadNone = false;
1929 if (Info.isReadWrite()) {
1930 InOutConstraints += ',';
1932 const Expr *InputExpr = S.getOutputExpr(i);
1933 llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
1935 InputExpr->getExprLoc());
1937 if (llvm::Type* AdjTy =
1938 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1940 Arg = Builder.CreateBitCast(Arg, AdjTy);
1942 if (Info.allowsRegister())
1943 InOutConstraints += llvm::utostr(i);
1945 InOutConstraints += OutputConstraint;
1947 InOutArgTypes.push_back(Arg->getType());
1948 InOutArgs.push_back(Arg);
1952 // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
1953 // to the return value slot. Only do this when returning in registers.
1954 if (isa<MSAsmStmt>(&S)) {
1955 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
1956 if (RetAI.isDirect() || RetAI.isExtend()) {
1957 // Make a fake lvalue for the return value slot.
1958 LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy);
1959 CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
1960 *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
1961 ResultRegDests, AsmString, S.getNumOutputs());
1966 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1967 const Expr *InputExpr = S.getInputExpr(i);
1969 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1971 if (Info.allowsMemory())
1974 if (!Constraints.empty())
1977 // Simplify the input constraint.
1978 std::string InputConstraint(S.getInputConstraint(i));
1979 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
1980 &OutputConstraintInfos);
1982 InputConstraint = AddVariableConstraints(
1983 InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
1984 getTarget(), CGM, S, false /* No EarlyClobber */);
1986 llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
1988 // If this input argument is tied to a larger output result, extend the
1989 // input to be the same size as the output. The LLVM backend wants to see
1990 // the input and output of a matching constraint be the same size. Note
1991 // that GCC does not define what the top bits are here. We use zext because
1992 // that is usually cheaper, but LLVM IR should really get an anyext someday.
1993 if (Info.hasTiedOperand()) {
1994 unsigned Output = Info.getTiedOperand();
1995 QualType OutputType = S.getOutputExpr(Output)->getType();
1996 QualType InputTy = InputExpr->getType();
1998 if (getContext().getTypeSize(OutputType) >
1999 getContext().getTypeSize(InputTy)) {
2000 // Use ptrtoint as appropriate so that we can do our extension.
2001 if (isa<llvm::PointerType>(Arg->getType()))
2002 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
2003 llvm::Type *OutputTy = ConvertType(OutputType);
2004 if (isa<llvm::IntegerType>(OutputTy))
2005 Arg = Builder.CreateZExt(Arg, OutputTy);
2006 else if (isa<llvm::PointerType>(OutputTy))
2007 Arg = Builder.CreateZExt(Arg, IntPtrTy);
2009 assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
2010 Arg = Builder.CreateFPExt(Arg, OutputTy);
2014 if (llvm::Type* AdjTy =
2015 getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
2017 Arg = Builder.CreateBitCast(Arg, AdjTy);
2019 CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
2020 << InputExpr->getType() << InputConstraint;
2022 ArgTypes.push_back(Arg->getType());
2023 Args.push_back(Arg);
2024 Constraints += InputConstraint;
2027 // Append the "input" part of inout constraints last.
2028 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
2029 ArgTypes.push_back(InOutArgTypes[i]);
2030 Args.push_back(InOutArgs[i]);
2032 Constraints += InOutConstraints;
2035 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
2036 StringRef Clobber = S.getClobber(i);
2038 if (Clobber == "memory")
2039 ReadOnly = ReadNone = false;
2040 else if (Clobber != "cc")
2041 Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
2043 if (!Constraints.empty())
2046 Constraints += "~{";
2047 Constraints += Clobber;
2051 // Add machine specific clobbers
2052 std::string MachineClobbers = getTarget().getClobbers();
2053 if (!MachineClobbers.empty()) {
2054 if (!Constraints.empty())
2056 Constraints += MachineClobbers;
2059 llvm::Type *ResultType;
2060 if (ResultRegTypes.empty())
2061 ResultType = VoidTy;
2062 else if (ResultRegTypes.size() == 1)
2063 ResultType = ResultRegTypes[0];
2065 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
2067 llvm::FunctionType *FTy =
2068 llvm::FunctionType::get(ResultType, ArgTypes, false);
2070 bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
2071 llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
2072 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
2073 llvm::InlineAsm *IA =
2074 llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
2075 /* IsAlignStack */ false, AsmDialect);
2076 llvm::CallInst *Result = Builder.CreateCall(IA, Args);
2077 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2078 llvm::Attribute::NoUnwind);
2080 // Attach readnone and readonly attributes.
2081 if (!HasSideEffect) {
2083 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2084 llvm::Attribute::ReadNone);
2086 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2087 llvm::Attribute::ReadOnly);
2090 // Slap the source location of the inline asm into a !srcloc metadata on the
2092 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S)) {
2093 Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
2096 // At least put the line number on MS inline asm blobs.
2097 auto Loc = llvm::ConstantInt::get(Int32Ty, S.getAsmLoc().getRawEncoding());
2098 Result->setMetadata("srcloc",
2099 llvm::MDNode::get(getLLVMContext(),
2100 llvm::ConstantAsMetadata::get(Loc)));
2103 // Extract all of the register value results from the asm.
2104 std::vector<llvm::Value*> RegResults;
2105 if (ResultRegTypes.size() == 1) {
2106 RegResults.push_back(Result);
2108 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
2109 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
2110 RegResults.push_back(Tmp);
2114 assert(RegResults.size() == ResultRegTypes.size());
2115 assert(RegResults.size() == ResultTruncRegTypes.size());
2116 assert(RegResults.size() == ResultRegDests.size());
2117 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
2118 llvm::Value *Tmp = RegResults[i];
2120 // If the result type of the LLVM IR asm doesn't match the result type of
2121 // the expression, do the conversion.
2122 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
2123 llvm::Type *TruncTy = ResultTruncRegTypes[i];
2125 // Truncate the integer result to the right size, note that TruncTy can be
2127 if (TruncTy->isFloatingPointTy())
2128 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
2129 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
2130 uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
2131 Tmp = Builder.CreateTrunc(Tmp,
2132 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
2133 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
2134 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
2135 uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
2136 Tmp = Builder.CreatePtrToInt(Tmp,
2137 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
2138 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2139 } else if (TruncTy->isIntegerTy()) {
2140 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2141 } else if (TruncTy->isVectorTy()) {
2142 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
2146 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
2150 LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) {
2151 const RecordDecl *RD = S.getCapturedRecordDecl();
2152 QualType RecordTy = getContext().getRecordType(RD);
2154 // Initialize the captured struct.
2155 LValue SlotLV = MakeNaturalAlignAddrLValue(
2156 CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
2158 RecordDecl::field_iterator CurField = RD->field_begin();
2159 for (CapturedStmt::capture_init_iterator I = S.capture_init_begin(),
2160 E = S.capture_init_end();
2161 I != E; ++I, ++CurField) {
2162 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
2163 if (CurField->hasCapturedVLAType()) {
2164 auto VAT = CurField->getCapturedVLAType();
2165 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2167 EmitInitializerForField(*CurField, LV, *I, None);
2174 /// Generate an outlined function for the body of a CapturedStmt, store any
2175 /// captured variables into the captured struct, and call the outlined function.
2177 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
2178 LValue CapStruct = InitCapturedStruct(S);
2180 // Emit the CapturedDecl
2181 CodeGenFunction CGF(CGM, true);
2182 CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K));
2183 llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
2184 delete CGF.CapturedStmtInfo;
2186 // Emit call to the helper function.
2187 EmitCallOrInvoke(F, CapStruct.getAddress());
2193 CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
2194 LValue CapStruct = InitCapturedStruct(S);
2195 return CapStruct.getAddress();
2198 /// Creates the outlined function for a CapturedStmt.
2200 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
2201 assert(CapturedStmtInfo &&
2202 "CapturedStmtInfo should be set when generating the captured function");
2203 const CapturedDecl *CD = S.getCapturedDecl();
2204 const RecordDecl *RD = S.getCapturedRecordDecl();
2205 SourceLocation Loc = S.getLocStart();
2206 assert(CD->hasBody() && "missing CapturedDecl body");
2208 // Build the argument list.
2209 ASTContext &Ctx = CGM.getContext();
2210 FunctionArgList Args;
2211 Args.append(CD->param_begin(), CD->param_end());
2213 // Create the function declaration.
2214 FunctionType::ExtInfo ExtInfo;
2215 const CGFunctionInfo &FuncInfo =
2216 CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
2217 /*IsVariadic=*/false);
2218 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
2221 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
2222 CapturedStmtInfo->getHelperName(), &CGM.getModule());
2223 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
2224 if (CD->isNothrow())
2225 F->addFnAttr(llvm::Attribute::NoUnwind);
2227 // Generate the function.
2228 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args,
2230 CD->getBody()->getLocStart());
2231 // Set the context parameter in CapturedStmtInfo.
2232 llvm::Value *DeclPtr = LocalDeclMap[CD->getContextParam()];
2233 assert(DeclPtr && "missing context parameter for CapturedStmt");
2234 CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
2236 // Initialize variable-length arrays.
2237 LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
2238 Ctx.getTagDeclType(RD));
2239 for (auto *FD : RD->fields()) {
2240 if (FD->hasCapturedVLAType()) {
2241 auto *ExprArg = EmitLoadOfLValue(EmitLValueForField(Base, FD),
2242 S.getLocStart()).getScalarVal();
2243 auto VAT = FD->getCapturedVLAType();
2244 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
2248 // If 'this' is captured, load it into CXXThisValue.
2249 if (CapturedStmtInfo->isCXXThisExprCaptured()) {
2250 FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
2251 LValue ThisLValue = EmitLValueForField(Base, FD);
2252 CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
2255 PGO.assignRegionCounters(CD, F);
2256 CapturedStmtInfo->EmitBody(*this, CD->getBody());
2257 FinishFunction(CD->getBodyRBrace());