clang API Documentation

CGStmt.cpp
Go to the documentation of this file.
00001 //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This contains code to emit Stmt nodes as LLVM code.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CodeGenFunction.h"
00015 #include "CGDebugInfo.h"
00016 #include "CodeGenModule.h"
00017 #include "TargetInfo.h"
00018 #include "clang/AST/StmtVisitor.h"
00019 #include "clang/Basic/PrettyStackTrace.h"
00020 #include "clang/Basic/TargetInfo.h"
00021 #include "clang/Sema/LoopHint.h"
00022 #include "clang/Sema/SemaDiagnostic.h"
00023 #include "llvm/ADT/StringExtras.h"
00024 #include "llvm/IR/CallSite.h"
00025 #include "llvm/IR/DataLayout.h"
00026 #include "llvm/IR/InlineAsm.h"
00027 #include "llvm/IR/Intrinsics.h"
00028 using namespace clang;
00029 using namespace CodeGen;
00030 
00031 //===----------------------------------------------------------------------===//
00032 //                              Statement Emission
00033 //===----------------------------------------------------------------------===//
00034 
00035 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
00036   if (CGDebugInfo *DI = getDebugInfo()) {
00037     SourceLocation Loc;
00038     Loc = S->getLocStart();
00039     DI->EmitLocation(Builder, Loc);
00040 
00041     LastStopPoint = Loc;
00042   }
00043 }
00044 
00045 void CodeGenFunction::EmitStmt(const Stmt *S) {
00046   assert(S && "Null statement?");
00047   PGO.setCurrentStmt(S);
00048 
00049   // These statements have their own debug info handling.
00050   if (EmitSimpleStmt(S))
00051     return;
00052 
00053   // Check if we are generating unreachable code.
00054   if (!HaveInsertPoint()) {
00055     // If so, and the statement doesn't contain a label, then we do not need to
00056     // generate actual code. This is safe because (1) the current point is
00057     // unreachable, so we don't need to execute the code, and (2) we've already
00058     // handled the statements which update internal data structures (like the
00059     // local variable map) which could be used by subsequent statements.
00060     if (!ContainsLabel(S)) {
00061       // Verify that any decl statements were handled as simple, they may be in
00062       // scope of subsequent reachable statements.
00063       assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
00064       return;
00065     }
00066 
00067     // Otherwise, make a new block to hold the code.
00068     EnsureInsertPoint();
00069   }
00070 
00071   // Generate a stoppoint if we are emitting debug info.
00072   EmitStopPoint(S);
00073 
00074   switch (S->getStmtClass()) {
00075   case Stmt::NoStmtClass:
00076   case Stmt::CXXCatchStmtClass:
00077   case Stmt::SEHExceptStmtClass:
00078   case Stmt::SEHFinallyStmtClass:
00079   case Stmt::MSDependentExistsStmtClass:
00080     llvm_unreachable("invalid statement class to emit generically");
00081   case Stmt::NullStmtClass:
00082   case Stmt::CompoundStmtClass:
00083   case Stmt::DeclStmtClass:
00084   case Stmt::LabelStmtClass:
00085   case Stmt::AttributedStmtClass:
00086   case Stmt::GotoStmtClass:
00087   case Stmt::BreakStmtClass:
00088   case Stmt::ContinueStmtClass:
00089   case Stmt::DefaultStmtClass:
00090   case Stmt::CaseStmtClass:
00091     llvm_unreachable("should have emitted these statements as simple");
00092 
00093 #define STMT(Type, Base)
00094 #define ABSTRACT_STMT(Op)
00095 #define EXPR(Type, Base) \
00096   case Stmt::Type##Class:
00097 #include "clang/AST/StmtNodes.inc"
00098   {
00099     // Remember the block we came in on.
00100     llvm::BasicBlock *incoming = Builder.GetInsertBlock();
00101     assert(incoming && "expression emission must have an insertion point");
00102 
00103     EmitIgnoredExpr(cast<Expr>(S));
00104 
00105     llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
00106     assert(outgoing && "expression emission cleared block!");
00107 
00108     // The expression emitters assume (reasonably!) that the insertion
00109     // point is always set.  To maintain that, the call-emission code
00110     // for noreturn functions has to enter a new block with no
00111     // predecessors.  We want to kill that block and mark the current
00112     // insertion point unreachable in the common case of a call like
00113     // "exit();".  Since expression emission doesn't otherwise create
00114     // blocks with no predecessors, we can just test for that.
00115     // However, we must be careful not to do this to our incoming
00116     // block, because *statement* emission does sometimes create
00117     // reachable blocks which will have no predecessors until later in
00118     // the function.  This occurs with, e.g., labels that are not
00119     // reachable by fallthrough.
00120     if (incoming != outgoing && outgoing->use_empty()) {
00121       outgoing->eraseFromParent();
00122       Builder.ClearInsertionPoint();
00123     }
00124     break;
00125   }
00126 
00127   case Stmt::IndirectGotoStmtClass:
00128     EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
00129 
00130   case Stmt::IfStmtClass:       EmitIfStmt(cast<IfStmt>(*S));             break;
00131   case Stmt::WhileStmtClass:    EmitWhileStmt(cast<WhileStmt>(*S));       break;
00132   case Stmt::DoStmtClass:       EmitDoStmt(cast<DoStmt>(*S));             break;
00133   case Stmt::ForStmtClass:      EmitForStmt(cast<ForStmt>(*S));           break;
00134 
00135   case Stmt::ReturnStmtClass:   EmitReturnStmt(cast<ReturnStmt>(*S));     break;
00136 
00137   case Stmt::SwitchStmtClass:   EmitSwitchStmt(cast<SwitchStmt>(*S));     break;
00138   case Stmt::GCCAsmStmtClass:   // Intentional fall-through.
00139   case Stmt::MSAsmStmtClass:    EmitAsmStmt(cast<AsmStmt>(*S));           break;
00140   case Stmt::CapturedStmtClass: {
00141     const CapturedStmt *CS = cast<CapturedStmt>(S);
00142     EmitCapturedStmt(*CS, CS->getCapturedRegionKind());
00143     }
00144     break;
00145   case Stmt::ObjCAtTryStmtClass:
00146     EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
00147     break;
00148   case Stmt::ObjCAtCatchStmtClass:
00149     llvm_unreachable(
00150                     "@catch statements should be handled by EmitObjCAtTryStmt");
00151   case Stmt::ObjCAtFinallyStmtClass:
00152     llvm_unreachable(
00153                   "@finally statements should be handled by EmitObjCAtTryStmt");
00154   case Stmt::ObjCAtThrowStmtClass:
00155     EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
00156     break;
00157   case Stmt::ObjCAtSynchronizedStmtClass:
00158     EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
00159     break;
00160   case Stmt::ObjCForCollectionStmtClass:
00161     EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
00162     break;
00163   case Stmt::ObjCAutoreleasePoolStmtClass:
00164     EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
00165     break;
00166 
00167   case Stmt::CXXTryStmtClass:
00168     EmitCXXTryStmt(cast<CXXTryStmt>(*S));
00169     break;
00170   case Stmt::CXXForRangeStmtClass:
00171     EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
00172     break;
00173   case Stmt::SEHTryStmtClass:
00174     EmitSEHTryStmt(cast<SEHTryStmt>(*S));
00175     break;
00176   case Stmt::SEHLeaveStmtClass:
00177     EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S));
00178     break;
00179   case Stmt::OMPParallelDirectiveClass:
00180     EmitOMPParallelDirective(cast<OMPParallelDirective>(*S));
00181     break;
00182   case Stmt::OMPSimdDirectiveClass:
00183     EmitOMPSimdDirective(cast<OMPSimdDirective>(*S));
00184     break;
00185   case Stmt::OMPForDirectiveClass:
00186     EmitOMPForDirective(cast<OMPForDirective>(*S));
00187     break;
00188   case Stmt::OMPForSimdDirectiveClass:
00189     EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S));
00190     break;
00191   case Stmt::OMPSectionsDirectiveClass:
00192     EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S));
00193     break;
00194   case Stmt::OMPSectionDirectiveClass:
00195     EmitOMPSectionDirective(cast<OMPSectionDirective>(*S));
00196     break;
00197   case Stmt::OMPSingleDirectiveClass:
00198     EmitOMPSingleDirective(cast<OMPSingleDirective>(*S));
00199     break;
00200   case Stmt::OMPMasterDirectiveClass:
00201     EmitOMPMasterDirective(cast<OMPMasterDirective>(*S));
00202     break;
00203   case Stmt::OMPCriticalDirectiveClass:
00204     EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S));
00205     break;
00206   case Stmt::OMPParallelForDirectiveClass:
00207     EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S));
00208     break;
00209   case Stmt::OMPParallelForSimdDirectiveClass:
00210     EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S));
00211     break;
00212   case Stmt::OMPParallelSectionsDirectiveClass:
00213     EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S));
00214     break;
00215   case Stmt::OMPTaskDirectiveClass:
00216     EmitOMPTaskDirective(cast<OMPTaskDirective>(*S));
00217     break;
00218   case Stmt::OMPTaskyieldDirectiveClass:
00219     EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S));
00220     break;
00221   case Stmt::OMPBarrierDirectiveClass:
00222     EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S));
00223     break;
00224   case Stmt::OMPTaskwaitDirectiveClass:
00225     EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S));
00226     break;
00227   case Stmt::OMPFlushDirectiveClass:
00228     EmitOMPFlushDirective(cast<OMPFlushDirective>(*S));
00229     break;
00230   case Stmt::OMPOrderedDirectiveClass:
00231     EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S));
00232     break;
00233   case Stmt::OMPAtomicDirectiveClass:
00234     EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S));
00235     break;
00236   case Stmt::OMPTargetDirectiveClass:
00237     EmitOMPTargetDirective(cast<OMPTargetDirective>(*S));
00238     break;
00239   case Stmt::OMPTeamsDirectiveClass:
00240     EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S));
00241     break;
00242   }
00243 }
00244 
00245 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
00246   switch (S->getStmtClass()) {
00247   default: return false;
00248   case Stmt::NullStmtClass: break;
00249   case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
00250   case Stmt::DeclStmtClass:     EmitDeclStmt(cast<DeclStmt>(*S));         break;
00251   case Stmt::LabelStmtClass:    EmitLabelStmt(cast<LabelStmt>(*S));       break;
00252   case Stmt::AttributedStmtClass:
00253                             EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
00254   case Stmt::GotoStmtClass:     EmitGotoStmt(cast<GotoStmt>(*S));         break;
00255   case Stmt::BreakStmtClass:    EmitBreakStmt(cast<BreakStmt>(*S));       break;
00256   case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
00257   case Stmt::DefaultStmtClass:  EmitDefaultStmt(cast<DefaultStmt>(*S));   break;
00258   case Stmt::CaseStmtClass:     EmitCaseStmt(cast<CaseStmt>(*S));         break;
00259   }
00260 
00261   return true;
00262 }
00263 
00264 /// EmitCompoundStmt - Emit a compound statement {..} node.  If GetLast is true,
00265 /// this captures the expression result of the last sub-statement and returns it
00266 /// (for use by the statement expression extension).
00267 llvm::Value* CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
00268                                                AggValueSlot AggSlot) {
00269   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
00270                              "LLVM IR generation of compound statement ('{}')");
00271 
00272   // Keep track of the current cleanup stack depth, including debug scopes.
00273   LexicalScope Scope(*this, S.getSourceRange());
00274 
00275   return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
00276 }
00277 
00278 llvm::Value*
00279 CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S,
00280                                               bool GetLast,
00281                                               AggValueSlot AggSlot) {
00282 
00283   for (CompoundStmt::const_body_iterator I = S.body_begin(),
00284        E = S.body_end()-GetLast; I != E; ++I)
00285     EmitStmt(*I);
00286 
00287   llvm::Value *RetAlloca = nullptr;
00288   if (GetLast) {
00289     // We have to special case labels here.  They are statements, but when put
00290     // at the end of a statement expression, they yield the value of their
00291     // subexpression.  Handle this by walking through all labels we encounter,
00292     // emitting them before we evaluate the subexpr.
00293     const Stmt *LastStmt = S.body_back();
00294     while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
00295       EmitLabel(LS->getDecl());
00296       LastStmt = LS->getSubStmt();
00297     }
00298 
00299     EnsureInsertPoint();
00300 
00301     QualType ExprTy = cast<Expr>(LastStmt)->getType();
00302     if (hasAggregateEvaluationKind(ExprTy)) {
00303       EmitAggExpr(cast<Expr>(LastStmt), AggSlot);
00304     } else {
00305       // We can't return an RValue here because there might be cleanups at
00306       // the end of the StmtExpr.  Because of that, we have to emit the result
00307       // here into a temporary alloca.
00308       RetAlloca = CreateMemTemp(ExprTy);
00309       EmitAnyExprToMem(cast<Expr>(LastStmt), RetAlloca, Qualifiers(),
00310                        /*IsInit*/false);
00311     }
00312 
00313   }
00314 
00315   return RetAlloca;
00316 }
00317 
00318 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
00319   llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
00320 
00321   // If there is a cleanup stack, then we it isn't worth trying to
00322   // simplify this block (we would need to remove it from the scope map
00323   // and cleanup entry).
00324   if (!EHStack.empty())
00325     return;
00326 
00327   // Can only simplify direct branches.
00328   if (!BI || !BI->isUnconditional())
00329     return;
00330 
00331   // Can only simplify empty blocks.
00332   if (BI != BB->begin())
00333     return;
00334 
00335   BB->replaceAllUsesWith(BI->getSuccessor(0));
00336   BI->eraseFromParent();
00337   BB->eraseFromParent();
00338 }
00339 
00340 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
00341   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
00342 
00343   // Fall out of the current block (if necessary).
00344   EmitBranch(BB);
00345 
00346   if (IsFinished && BB->use_empty()) {
00347     delete BB;
00348     return;
00349   }
00350 
00351   // Place the block after the current block, if possible, or else at
00352   // the end of the function.
00353   if (CurBB && CurBB->getParent())
00354     CurFn->getBasicBlockList().insertAfter(CurBB, BB);
00355   else
00356     CurFn->getBasicBlockList().push_back(BB);
00357   Builder.SetInsertPoint(BB);
00358 }
00359 
00360 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
00361   // Emit a branch from the current block to the target one if this
00362   // was a real block.  If this was just a fall-through block after a
00363   // terminator, don't emit it.
00364   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
00365 
00366   if (!CurBB || CurBB->getTerminator()) {
00367     // If there is no insert point or the previous block is already
00368     // terminated, don't touch it.
00369   } else {
00370     // Otherwise, create a fall-through branch.
00371     Builder.CreateBr(Target);
00372   }
00373 
00374   Builder.ClearInsertionPoint();
00375 }
00376 
00377 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
00378   bool inserted = false;
00379   for (llvm::User *u : block->users()) {
00380     if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
00381       CurFn->getBasicBlockList().insertAfter(insn->getParent(), block);
00382       inserted = true;
00383       break;
00384     }
00385   }
00386 
00387   if (!inserted)
00388     CurFn->getBasicBlockList().push_back(block);
00389 
00390   Builder.SetInsertPoint(block);
00391 }
00392 
00393 CodeGenFunction::JumpDest
00394 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
00395   JumpDest &Dest = LabelMap[D];
00396   if (Dest.isValid()) return Dest;
00397 
00398   // Create, but don't insert, the new block.
00399   Dest = JumpDest(createBasicBlock(D->getName()),
00400                   EHScopeStack::stable_iterator::invalid(),
00401                   NextCleanupDestIndex++);
00402   return Dest;
00403 }
00404 
00405 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
00406   // Add this label to the current lexical scope if we're within any
00407   // normal cleanups.  Jumps "in" to this label --- when permitted by
00408   // the language --- may need to be routed around such cleanups.
00409   if (EHStack.hasNormalCleanups() && CurLexicalScope)
00410     CurLexicalScope->addLabel(D);
00411 
00412   JumpDest &Dest = LabelMap[D];
00413 
00414   // If we didn't need a forward reference to this label, just go
00415   // ahead and create a destination at the current scope.
00416   if (!Dest.isValid()) {
00417     Dest = getJumpDestInCurrentScope(D->getName());
00418 
00419   // Otherwise, we need to give this label a target depth and remove
00420   // it from the branch-fixups list.
00421   } else {
00422     assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
00423     Dest.setScopeDepth(EHStack.stable_begin());
00424     ResolveBranchFixups(Dest.getBlock());
00425   }
00426 
00427   RegionCounter Cnt = getPGORegionCounter(D->getStmt());
00428   EmitBlock(Dest.getBlock());
00429   Cnt.beginRegion(Builder);
00430 }
00431 
00432 /// Change the cleanup scope of the labels in this lexical scope to
00433 /// match the scope of the enclosing context.
00434 void CodeGenFunction::LexicalScope::rescopeLabels() {
00435   assert(!Labels.empty());
00436   EHScopeStack::stable_iterator innermostScope
00437     = CGF.EHStack.getInnermostNormalCleanup();
00438 
00439   // Change the scope depth of all the labels.
00440   for (SmallVectorImpl<const LabelDecl*>::const_iterator
00441          i = Labels.begin(), e = Labels.end(); i != e; ++i) {
00442     assert(CGF.LabelMap.count(*i));
00443     JumpDest &dest = CGF.LabelMap.find(*i)->second;
00444     assert(dest.getScopeDepth().isValid());
00445     assert(innermostScope.encloses(dest.getScopeDepth()));
00446     dest.setScopeDepth(innermostScope);
00447   }
00448 
00449   // Reparent the labels if the new scope also has cleanups.
00450   if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
00451     ParentScope->Labels.append(Labels.begin(), Labels.end());
00452   }
00453 }
00454 
00455 
00456 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
00457   EmitLabel(S.getDecl());
00458   EmitStmt(S.getSubStmt());
00459 }
00460 
00461 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
00462   const Stmt *SubStmt = S.getSubStmt();
00463   switch (SubStmt->getStmtClass()) {
00464   case Stmt::DoStmtClass:
00465     EmitDoStmt(cast<DoStmt>(*SubStmt), S.getAttrs());
00466     break;
00467   case Stmt::ForStmtClass:
00468     EmitForStmt(cast<ForStmt>(*SubStmt), S.getAttrs());
00469     break;
00470   case Stmt::WhileStmtClass:
00471     EmitWhileStmt(cast<WhileStmt>(*SubStmt), S.getAttrs());
00472     break;
00473   case Stmt::CXXForRangeStmtClass:
00474     EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*SubStmt), S.getAttrs());
00475     break;
00476   default:
00477     EmitStmt(SubStmt);
00478   }
00479 }
00480 
00481 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
00482   // If this code is reachable then emit a stop point (if generating
00483   // debug info). We have to do this ourselves because we are on the
00484   // "simple" statement path.
00485   if (HaveInsertPoint())
00486     EmitStopPoint(&S);
00487 
00488   EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
00489 }
00490 
00491 
00492 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
00493   if (const LabelDecl *Target = S.getConstantTarget()) {
00494     EmitBranchThroughCleanup(getJumpDestForLabel(Target));
00495     return;
00496   }
00497 
00498   // Ensure that we have an i8* for our PHI node.
00499   llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
00500                                          Int8PtrTy, "addr");
00501   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
00502 
00503   // Get the basic block for the indirect goto.
00504   llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
00505 
00506   // The first instruction in the block has to be the PHI for the switch dest,
00507   // add an entry for this branch.
00508   cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
00509 
00510   EmitBranch(IndGotoBB);
00511 }
00512 
00513 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
00514   // C99 6.8.4.1: The first substatement is executed if the expression compares
00515   // unequal to 0.  The condition must be a scalar type.
00516   LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
00517   RegionCounter Cnt = getPGORegionCounter(&S);
00518 
00519   if (S.getConditionVariable())
00520     EmitAutoVarDecl(*S.getConditionVariable());
00521 
00522   // If the condition constant folds and can be elided, try to avoid emitting
00523   // the condition and the dead arm of the if/else.
00524   bool CondConstant;
00525   if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) {
00526     // Figure out which block (then or else) is executed.
00527     const Stmt *Executed = S.getThen();
00528     const Stmt *Skipped  = S.getElse();
00529     if (!CondConstant)  // Condition false?
00530       std::swap(Executed, Skipped);
00531 
00532     // If the skipped block has no labels in it, just emit the executed block.
00533     // This avoids emitting dead code and simplifies the CFG substantially.
00534     if (!ContainsLabel(Skipped)) {
00535       if (CondConstant)
00536         Cnt.beginRegion(Builder);
00537       if (Executed) {
00538         RunCleanupsScope ExecutedScope(*this);
00539         EmitStmt(Executed);
00540       }
00541       return;
00542     }
00543   }
00544 
00545   // Otherwise, the condition did not fold, or we couldn't elide it.  Just emit
00546   // the conditional branch.
00547   llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
00548   llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
00549   llvm::BasicBlock *ElseBlock = ContBlock;
00550   if (S.getElse())
00551     ElseBlock = createBasicBlock("if.else");
00552 
00553   EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock, Cnt.getCount());
00554 
00555   // Emit the 'then' code.
00556   EmitBlock(ThenBlock);
00557   Cnt.beginRegion(Builder);
00558   {
00559     RunCleanupsScope ThenScope(*this);
00560     EmitStmt(S.getThen());
00561   }
00562   EmitBranch(ContBlock);
00563 
00564   // Emit the 'else' code if present.
00565   if (const Stmt *Else = S.getElse()) {
00566     {
00567       // There is no need to emit line number for unconditional branch.
00568       SuppressDebugLocation S(Builder);
00569       EmitBlock(ElseBlock);
00570     }
00571     {
00572       RunCleanupsScope ElseScope(*this);
00573       EmitStmt(Else);
00574     }
00575     {
00576       // There is no need to emit line number for unconditional branch.
00577       SuppressDebugLocation S(Builder);
00578       EmitBranch(ContBlock);
00579     }
00580   }
00581 
00582   // Emit the continuation block for code after the if.
00583   EmitBlock(ContBlock, true);
00584 }
00585 
00586 void CodeGenFunction::EmitCondBrHints(llvm::LLVMContext &Context,
00587                                       llvm::BranchInst *CondBr,
00588                                       ArrayRef<const Attr *> Attrs) {
00589   // Return if there are no hints.
00590   if (Attrs.empty())
00591     return;
00592 
00593   // Add vectorize and unroll hints to the metadata on the conditional branch.
00594   SmallVector<llvm::Value *, 2> Metadata(1);
00595   for (const auto *Attr : Attrs) {
00596     const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(Attr);
00597 
00598     // Skip non loop hint attributes
00599     if (!LH)
00600       continue;
00601 
00602     LoopHintAttr::OptionType Option = LH->getOption();
00603     LoopHintAttr::LoopHintState State = LH->getState();
00604     const char *MetadataName;
00605     switch (Option) {
00606     case LoopHintAttr::Vectorize:
00607     case LoopHintAttr::VectorizeWidth:
00608       MetadataName = "llvm.loop.vectorize.width";
00609       break;
00610     case LoopHintAttr::Interleave:
00611     case LoopHintAttr::InterleaveCount:
00612       MetadataName = "llvm.loop.interleave.count";
00613       break;
00614     case LoopHintAttr::Unroll:
00615       // With the unroll loop hint, a non-zero value indicates full unrolling.
00616       MetadataName = State == LoopHintAttr::Disable ? "llvm.loop.unroll.disable"
00617                                                     : "llvm.loop.unroll.full";
00618       break;
00619     case LoopHintAttr::UnrollCount:
00620       MetadataName = "llvm.loop.unroll.count";
00621       break;
00622     }
00623 
00624     Expr *ValueExpr = LH->getValue();
00625     int ValueInt = 1;
00626     if (ValueExpr) {
00627       llvm::APSInt ValueAPS =
00628           ValueExpr->EvaluateKnownConstInt(CGM.getContext());
00629       ValueInt = static_cast<int>(ValueAPS.getSExtValue());
00630     }
00631 
00632     llvm::Value *Value;
00633     llvm::MDString *Name;
00634     switch (Option) {
00635     case LoopHintAttr::Vectorize:
00636     case LoopHintAttr::Interleave:
00637       if (State != LoopHintAttr::Disable) {
00638         // FIXME: In the future I will modifiy the behavior of the metadata
00639         // so we can enable/disable vectorization and interleaving separately.
00640         Name = llvm::MDString::get(Context, "llvm.loop.vectorize.enable");
00641         Value = Builder.getTrue();
00642         break;
00643       }
00644       // Vectorization/interleaving is disabled, set width/count to 1.
00645       ValueInt = 1;
00646       // Fallthrough.
00647     case LoopHintAttr::VectorizeWidth:
00648     case LoopHintAttr::InterleaveCount:
00649     case LoopHintAttr::UnrollCount:
00650       Name = llvm::MDString::get(Context, MetadataName);
00651       Value = llvm::ConstantInt::get(Int32Ty, ValueInt);
00652       break;
00653     case LoopHintAttr::Unroll:
00654       Name = llvm::MDString::get(Context, MetadataName);
00655       Value = nullptr;
00656       break;
00657     }
00658 
00659     SmallVector<llvm::Value *, 2> OpValues;
00660     OpValues.push_back(Name);
00661     if (Value)
00662       OpValues.push_back(Value);
00663 
00664     // Set or overwrite metadata indicated by Name.
00665     Metadata.push_back(llvm::MDNode::get(Context, OpValues));
00666   }
00667 
00668   if (!Metadata.empty()) {
00669     // Add llvm.loop MDNode to CondBr.
00670     llvm::MDNode *LoopID = llvm::MDNode::get(Context, Metadata);
00671     LoopID->replaceOperandWith(0, LoopID); // First op points to itself.
00672 
00673     CondBr->setMetadata("llvm.loop", LoopID);
00674   }
00675 }
00676 
00677 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
00678                                     ArrayRef<const Attr *> WhileAttrs) {
00679   RegionCounter Cnt = getPGORegionCounter(&S);
00680 
00681   // Emit the header for the loop, which will also become
00682   // the continue target.
00683   JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
00684   EmitBlock(LoopHeader.getBlock());
00685 
00686   LoopStack.push(LoopHeader.getBlock());
00687 
00688   // Create an exit block for when the condition fails, which will
00689   // also become the break target.
00690   JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
00691 
00692   // Store the blocks to use for break and continue.
00693   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
00694 
00695   // C++ [stmt.while]p2:
00696   //   When the condition of a while statement is a declaration, the
00697   //   scope of the variable that is declared extends from its point
00698   //   of declaration (3.3.2) to the end of the while statement.
00699   //   [...]
00700   //   The object created in a condition is destroyed and created
00701   //   with each iteration of the loop.
00702   RunCleanupsScope ConditionScope(*this);
00703 
00704   if (S.getConditionVariable())
00705     EmitAutoVarDecl(*S.getConditionVariable());
00706 
00707   // Evaluate the conditional in the while header.  C99 6.8.5.1: The
00708   // evaluation of the controlling expression takes place before each
00709   // execution of the loop body.
00710   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
00711 
00712   // while(1) is common, avoid extra exit blocks.  Be sure
00713   // to correctly handle break/continue though.
00714   bool EmitBoolCondBranch = true;
00715   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
00716     if (C->isOne())
00717       EmitBoolCondBranch = false;
00718 
00719   // As long as the condition is true, go to the loop body.
00720   llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
00721   if (EmitBoolCondBranch) {
00722     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
00723     if (ConditionScope.requiresCleanups())
00724       ExitBlock = createBasicBlock("while.exit");
00725     llvm::BranchInst *CondBr =
00726         Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock,
00727                              PGO.createLoopWeights(S.getCond(), Cnt));
00728 
00729     if (ExitBlock != LoopExit.getBlock()) {
00730       EmitBlock(ExitBlock);
00731       EmitBranchThroughCleanup(LoopExit);
00732     }
00733 
00734     // Attach metadata to loop body conditional branch.
00735     EmitCondBrHints(LoopBody->getContext(), CondBr, WhileAttrs);
00736   }
00737 
00738   // Emit the loop body.  We have to emit this in a cleanup scope
00739   // because it might be a singleton DeclStmt.
00740   {
00741     RunCleanupsScope BodyScope(*this);
00742     EmitBlock(LoopBody);
00743     Cnt.beginRegion(Builder);
00744     EmitStmt(S.getBody());
00745   }
00746 
00747   BreakContinueStack.pop_back();
00748 
00749   // Immediately force cleanup.
00750   ConditionScope.ForceCleanup();
00751 
00752   EmitStopPoint(&S);
00753   // Branch to the loop header again.
00754   EmitBranch(LoopHeader.getBlock());
00755 
00756   LoopStack.pop();
00757 
00758   // Emit the exit block.
00759   EmitBlock(LoopExit.getBlock(), true);
00760 
00761   // The LoopHeader typically is just a branch if we skipped emitting
00762   // a branch, try to erase it.
00763   if (!EmitBoolCondBranch)
00764     SimplifyForwardingBlocks(LoopHeader.getBlock());
00765 }
00766 
00767 void CodeGenFunction::EmitDoStmt(const DoStmt &S,
00768                                  ArrayRef<const Attr *> DoAttrs) {
00769   JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
00770   JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
00771 
00772   RegionCounter Cnt = getPGORegionCounter(&S);
00773 
00774   // Store the blocks to use for break and continue.
00775   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
00776 
00777   // Emit the body of the loop.
00778   llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
00779 
00780   LoopStack.push(LoopBody);
00781 
00782   EmitBlockWithFallThrough(LoopBody, Cnt);
00783   {
00784     RunCleanupsScope BodyScope(*this);
00785     EmitStmt(S.getBody());
00786   }
00787 
00788   EmitBlock(LoopCond.getBlock());
00789 
00790   // C99 6.8.5.2: "The evaluation of the controlling expression takes place
00791   // after each execution of the loop body."
00792 
00793   // Evaluate the conditional in the while header.
00794   // C99 6.8.5p2/p4: The first substatement is executed if the expression
00795   // compares unequal to 0.  The condition must be a scalar type.
00796   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
00797 
00798   BreakContinueStack.pop_back();
00799 
00800   // "do {} while (0)" is common in macros, avoid extra blocks.  Be sure
00801   // to correctly handle break/continue though.
00802   bool EmitBoolCondBranch = true;
00803   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
00804     if (C->isZero())
00805       EmitBoolCondBranch = false;
00806 
00807   // As long as the condition is true, iterate the loop.
00808   if (EmitBoolCondBranch) {
00809     llvm::BranchInst *CondBr =
00810         Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock(),
00811                              PGO.createLoopWeights(S.getCond(), Cnt));
00812 
00813     // Attach metadata to loop body conditional branch.
00814     EmitCondBrHints(LoopBody->getContext(), CondBr, DoAttrs);
00815   }
00816 
00817   LoopStack.pop();
00818 
00819   // Emit the exit block.
00820   EmitBlock(LoopExit.getBlock());
00821 
00822   // The DoCond block typically is just a branch if we skipped
00823   // emitting a branch, try to erase it.
00824   if (!EmitBoolCondBranch)
00825     SimplifyForwardingBlocks(LoopCond.getBlock());
00826 }
00827 
00828 void CodeGenFunction::EmitForStmt(const ForStmt &S,
00829                                   ArrayRef<const Attr *> ForAttrs) {
00830   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
00831 
00832   LexicalScope ForScope(*this, S.getSourceRange());
00833 
00834   // Evaluate the first part before the loop.
00835   if (S.getInit())
00836     EmitStmt(S.getInit());
00837 
00838   RegionCounter Cnt = getPGORegionCounter(&S);
00839 
00840   // Start the loop with a block that tests the condition.
00841   // If there's an increment, the continue scope will be overwritten
00842   // later.
00843   JumpDest Continue = getJumpDestInCurrentScope("for.cond");
00844   llvm::BasicBlock *CondBlock = Continue.getBlock();
00845   EmitBlock(CondBlock);
00846 
00847   LoopStack.push(CondBlock);
00848 
00849   // If the for loop doesn't have an increment we can just use the
00850   // condition as the continue block.  Otherwise we'll need to create
00851   // a block for it (in the current scope, i.e. in the scope of the
00852   // condition), and that we will become our continue block.
00853   if (S.getInc())
00854     Continue = getJumpDestInCurrentScope("for.inc");
00855 
00856   // Store the blocks to use for break and continue.
00857   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
00858 
00859   // Create a cleanup scope for the condition variable cleanups.
00860   LexicalScope ConditionScope(*this, S.getSourceRange());
00861 
00862   if (S.getCond()) {
00863     // If the for statement has a condition scope, emit the local variable
00864     // declaration.
00865     if (S.getConditionVariable()) {
00866       EmitAutoVarDecl(*S.getConditionVariable());
00867     }
00868 
00869     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
00870     // If there are any cleanups between here and the loop-exit scope,
00871     // create a block to stage a loop exit along.
00872     if (ForScope.requiresCleanups())
00873       ExitBlock = createBasicBlock("for.cond.cleanup");
00874 
00875     // As long as the condition is true, iterate the loop.
00876     llvm::BasicBlock *ForBody = createBasicBlock("for.body");
00877 
00878     // C99 6.8.5p2/p4: The first substatement is executed if the expression
00879     // compares unequal to 0.  The condition must be a scalar type.
00880     llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
00881     llvm::BranchInst *CondBr =
00882         Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock,
00883                              PGO.createLoopWeights(S.getCond(), Cnt));
00884 
00885     // Attach metadata to loop body conditional branch.
00886     EmitCondBrHints(ForBody->getContext(), CondBr, ForAttrs);
00887 
00888     if (ExitBlock != LoopExit.getBlock()) {
00889       EmitBlock(ExitBlock);
00890       EmitBranchThroughCleanup(LoopExit);
00891     }
00892 
00893     EmitBlock(ForBody);
00894   } else {
00895     // Treat it as a non-zero constant.  Don't even create a new block for the
00896     // body, just fall into it.
00897   }
00898   Cnt.beginRegion(Builder);
00899 
00900   {
00901     // Create a separate cleanup scope for the body, in case it is not
00902     // a compound statement.
00903     RunCleanupsScope BodyScope(*this);
00904     EmitStmt(S.getBody());
00905   }
00906 
00907   // If there is an increment, emit it next.
00908   if (S.getInc()) {
00909     EmitBlock(Continue.getBlock());
00910     EmitStmt(S.getInc());
00911   }
00912 
00913   BreakContinueStack.pop_back();
00914 
00915   ConditionScope.ForceCleanup();
00916 
00917   EmitStopPoint(&S);
00918   EmitBranch(CondBlock);
00919 
00920   ForScope.ForceCleanup();
00921 
00922   LoopStack.pop();
00923 
00924   // Emit the fall-through block.
00925   EmitBlock(LoopExit.getBlock(), true);
00926 }
00927 
00928 void
00929 CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
00930                                      ArrayRef<const Attr *> ForAttrs) {
00931   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
00932 
00933   LexicalScope ForScope(*this, S.getSourceRange());
00934 
00935   // Evaluate the first pieces before the loop.
00936   EmitStmt(S.getRangeStmt());
00937   EmitStmt(S.getBeginEndStmt());
00938 
00939   RegionCounter Cnt = getPGORegionCounter(&S);
00940 
00941   // Start the loop with a block that tests the condition.
00942   // If there's an increment, the continue scope will be overwritten
00943   // later.
00944   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
00945   EmitBlock(CondBlock);
00946 
00947   LoopStack.push(CondBlock);
00948 
00949   // If there are any cleanups between here and the loop-exit scope,
00950   // create a block to stage a loop exit along.
00951   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
00952   if (ForScope.requiresCleanups())
00953     ExitBlock = createBasicBlock("for.cond.cleanup");
00954 
00955   // The loop body, consisting of the specified body and the loop variable.
00956   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
00957 
00958   // The body is executed if the expression, contextually converted
00959   // to bool, is true.
00960   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
00961   llvm::BranchInst *CondBr = Builder.CreateCondBr(
00962       BoolCondVal, ForBody, ExitBlock, PGO.createLoopWeights(S.getCond(), Cnt));
00963 
00964   // Attach metadata to loop body conditional branch.
00965   EmitCondBrHints(ForBody->getContext(), CondBr, ForAttrs);
00966 
00967   if (ExitBlock != LoopExit.getBlock()) {
00968     EmitBlock(ExitBlock);
00969     EmitBranchThroughCleanup(LoopExit);
00970   }
00971 
00972   EmitBlock(ForBody);
00973   Cnt.beginRegion(Builder);
00974 
00975   // Create a block for the increment. In case of a 'continue', we jump there.
00976   JumpDest Continue = getJumpDestInCurrentScope("for.inc");
00977 
00978   // Store the blocks to use for break and continue.
00979   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
00980 
00981   {
00982     // Create a separate cleanup scope for the loop variable and body.
00983     LexicalScope BodyScope(*this, S.getSourceRange());
00984     EmitStmt(S.getLoopVarStmt());
00985     EmitStmt(S.getBody());
00986   }
00987 
00988   EmitStopPoint(&S);
00989   // If there is an increment, emit it next.
00990   EmitBlock(Continue.getBlock());
00991   EmitStmt(S.getInc());
00992 
00993   BreakContinueStack.pop_back();
00994 
00995   EmitBranch(CondBlock);
00996 
00997   ForScope.ForceCleanup();
00998 
00999   LoopStack.pop();
01000 
01001   // Emit the fall-through block.
01002   EmitBlock(LoopExit.getBlock(), true);
01003 }
01004 
01005 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
01006   if (RV.isScalar()) {
01007     Builder.CreateStore(RV.getScalarVal(), ReturnValue);
01008   } else if (RV.isAggregate()) {
01009     EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
01010   } else {
01011     EmitStoreOfComplex(RV.getComplexVal(),
01012                        MakeNaturalAlignAddrLValue(ReturnValue, Ty),
01013                        /*init*/ true);
01014   }
01015   EmitBranchThroughCleanup(ReturnBlock);
01016 }
01017 
01018 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
01019 /// if the function returns void, or may be missing one if the function returns
01020 /// non-void.  Fun stuff :).
01021 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
01022   // Emit the result value, even if unused, to evalute the side effects.
01023   const Expr *RV = S.getRetValue();
01024 
01025   // Treat block literals in a return expression as if they appeared
01026   // in their own scope.  This permits a small, easily-implemented
01027   // exception to our over-conservative rules about not jumping to
01028   // statements following block literals with non-trivial cleanups.
01029   RunCleanupsScope cleanupScope(*this);
01030   if (const ExprWithCleanups *cleanups =
01031         dyn_cast_or_null<ExprWithCleanups>(RV)) {
01032     enterFullExpression(cleanups);
01033     RV = cleanups->getSubExpr();
01034   }
01035 
01036   // FIXME: Clean this up by using an LValue for ReturnTemp,
01037   // EmitStoreThroughLValue, and EmitAnyExpr.
01038   if (getLangOpts().ElideConstructors &&
01039       S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
01040     // Apply the named return value optimization for this return statement,
01041     // which means doing nothing: the appropriate result has already been
01042     // constructed into the NRVO variable.
01043 
01044     // If there is an NRVO flag for this variable, set it to 1 into indicate
01045     // that the cleanup code should not destroy the variable.
01046     if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
01047       Builder.CreateStore(Builder.getTrue(), NRVOFlag);
01048   } else if (!ReturnValue || (RV && RV->getType()->isVoidType())) {
01049     // Make sure not to return anything, but evaluate the expression
01050     // for side effects.
01051     if (RV)
01052       EmitAnyExpr(RV);
01053   } else if (!RV) {
01054     // Do nothing (return value is left uninitialized)
01055   } else if (FnRetTy->isReferenceType()) {
01056     // If this function returns a reference, take the address of the expression
01057     // rather than the value.
01058     RValue Result = EmitReferenceBindingToExpr(RV);
01059     Builder.CreateStore(Result.getScalarVal(), ReturnValue);
01060   } else {
01061     switch (getEvaluationKind(RV->getType())) {
01062     case TEK_Scalar:
01063       Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
01064       break;
01065     case TEK_Complex:
01066       EmitComplexExprIntoLValue(RV,
01067                      MakeNaturalAlignAddrLValue(ReturnValue, RV->getType()),
01068                                 /*isInit*/ true);
01069       break;
01070     case TEK_Aggregate: {
01071       CharUnits Alignment = getContext().getTypeAlignInChars(RV->getType());
01072       EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Alignment,
01073                                             Qualifiers(),
01074                                             AggValueSlot::IsDestructed,
01075                                             AggValueSlot::DoesNotNeedGCBarriers,
01076                                             AggValueSlot::IsNotAliased));
01077       break;
01078     }
01079     }
01080   }
01081 
01082   ++NumReturnExprs;
01083   if (!RV || RV->isEvaluatable(getContext()))
01084     ++NumSimpleReturnExprs;
01085 
01086   cleanupScope.ForceCleanup();
01087   EmitBranchThroughCleanup(ReturnBlock);
01088 }
01089 
01090 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
01091   // As long as debug info is modeled with instructions, we have to ensure we
01092   // have a place to insert here and write the stop point here.
01093   if (HaveInsertPoint())
01094     EmitStopPoint(&S);
01095 
01096   for (const auto *I : S.decls())
01097     EmitDecl(*I);
01098 }
01099 
01100 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
01101   assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
01102 
01103   // If this code is reachable then emit a stop point (if generating
01104   // debug info). We have to do this ourselves because we are on the
01105   // "simple" statement path.
01106   if (HaveInsertPoint())
01107     EmitStopPoint(&S);
01108 
01109   EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
01110 }
01111 
01112 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
01113   assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
01114 
01115   // If this code is reachable then emit a stop point (if generating
01116   // debug info). We have to do this ourselves because we are on the
01117   // "simple" statement path.
01118   if (HaveInsertPoint())
01119     EmitStopPoint(&S);
01120 
01121   EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
01122 }
01123 
01124 /// EmitCaseStmtRange - If case statement range is not too big then
01125 /// add multiple cases to switch instruction, one for each value within
01126 /// the range. If range is too big then emit "if" condition check.
01127 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
01128   assert(S.getRHS() && "Expected RHS value in CaseStmt");
01129 
01130   llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
01131   llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
01132 
01133   RegionCounter CaseCnt = getPGORegionCounter(&S);
01134 
01135   // Emit the code for this case. We do this first to make sure it is
01136   // properly chained from our predecessor before generating the
01137   // switch machinery to enter this block.
01138   llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
01139   EmitBlockWithFallThrough(CaseDest, CaseCnt);
01140   EmitStmt(S.getSubStmt());
01141 
01142   // If range is empty, do nothing.
01143   if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
01144     return;
01145 
01146   llvm::APInt Range = RHS - LHS;
01147   // FIXME: parameters such as this should not be hardcoded.
01148   if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
01149     // Range is small enough to add multiple switch instruction cases.
01150     uint64_t Total = CaseCnt.getCount();
01151     unsigned NCases = Range.getZExtValue() + 1;
01152     // We only have one region counter for the entire set of cases here, so we
01153     // need to divide the weights evenly between the generated cases, ensuring
01154     // that the total weight is preserved. E.g., a weight of 5 over three cases
01155     // will be distributed as weights of 2, 2, and 1.
01156     uint64_t Weight = Total / NCases, Rem = Total % NCases;
01157     for (unsigned I = 0; I != NCases; ++I) {
01158       if (SwitchWeights)
01159         SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
01160       if (Rem)
01161         Rem--;
01162       SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
01163       LHS++;
01164     }
01165     return;
01166   }
01167 
01168   // The range is too big. Emit "if" condition into a new block,
01169   // making sure to save and restore the current insertion point.
01170   llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
01171 
01172   // Push this test onto the chain of range checks (which terminates
01173   // in the default basic block). The switch's default will be changed
01174   // to the top of this chain after switch emission is complete.
01175   llvm::BasicBlock *FalseDest = CaseRangeBlock;
01176   CaseRangeBlock = createBasicBlock("sw.caserange");
01177 
01178   CurFn->getBasicBlockList().push_back(CaseRangeBlock);
01179   Builder.SetInsertPoint(CaseRangeBlock);
01180 
01181   // Emit range check.
01182   llvm::Value *Diff =
01183     Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
01184   llvm::Value *Cond =
01185     Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
01186 
01187   llvm::MDNode *Weights = nullptr;
01188   if (SwitchWeights) {
01189     uint64_t ThisCount = CaseCnt.getCount();
01190     uint64_t DefaultCount = (*SwitchWeights)[0];
01191     Weights = PGO.createBranchWeights(ThisCount, DefaultCount);
01192 
01193     // Since we're chaining the switch default through each large case range, we
01194     // need to update the weight for the default, ie, the first case, to include
01195     // this case.
01196     (*SwitchWeights)[0] += ThisCount;
01197   }
01198   Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
01199 
01200   // Restore the appropriate insertion point.
01201   if (RestoreBB)
01202     Builder.SetInsertPoint(RestoreBB);
01203   else
01204     Builder.ClearInsertionPoint();
01205 }
01206 
01207 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
01208   // If there is no enclosing switch instance that we're aware of, then this
01209   // case statement and its block can be elided.  This situation only happens
01210   // when we've constant-folded the switch, are emitting the constant case,
01211   // and part of the constant case includes another case statement.  For
01212   // instance: switch (4) { case 4: do { case 5: } while (1); }
01213   if (!SwitchInsn) {
01214     EmitStmt(S.getSubStmt());
01215     return;
01216   }
01217 
01218   // Handle case ranges.
01219   if (S.getRHS()) {
01220     EmitCaseStmtRange(S);
01221     return;
01222   }
01223 
01224   RegionCounter CaseCnt = getPGORegionCounter(&S);
01225   llvm::ConstantInt *CaseVal =
01226     Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
01227 
01228   // If the body of the case is just a 'break', try to not emit an empty block.
01229   // If we're profiling or we're not optimizing, leave the block in for better
01230   // debug and coverage analysis.
01231   if (!CGM.getCodeGenOpts().ProfileInstrGenerate &&
01232       CGM.getCodeGenOpts().OptimizationLevel > 0 &&
01233       isa<BreakStmt>(S.getSubStmt())) {
01234     JumpDest Block = BreakContinueStack.back().BreakBlock;
01235 
01236     // Only do this optimization if there are no cleanups that need emitting.
01237     if (isObviouslyBranchWithoutCleanups(Block)) {
01238       if (SwitchWeights)
01239         SwitchWeights->push_back(CaseCnt.getCount());
01240       SwitchInsn->addCase(CaseVal, Block.getBlock());
01241 
01242       // If there was a fallthrough into this case, make sure to redirect it to
01243       // the end of the switch as well.
01244       if (Builder.GetInsertBlock()) {
01245         Builder.CreateBr(Block.getBlock());
01246         Builder.ClearInsertionPoint();
01247       }
01248       return;
01249     }
01250   }
01251 
01252   llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
01253   EmitBlockWithFallThrough(CaseDest, CaseCnt);
01254   if (SwitchWeights)
01255     SwitchWeights->push_back(CaseCnt.getCount());
01256   SwitchInsn->addCase(CaseVal, CaseDest);
01257 
01258   // Recursively emitting the statement is acceptable, but is not wonderful for
01259   // code where we have many case statements nested together, i.e.:
01260   //  case 1:
01261   //    case 2:
01262   //      case 3: etc.
01263   // Handling this recursively will create a new block for each case statement
01264   // that falls through to the next case which is IR intensive.  It also causes
01265   // deep recursion which can run into stack depth limitations.  Handle
01266   // sequential non-range case statements specially.
01267   const CaseStmt *CurCase = &S;
01268   const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
01269 
01270   // Otherwise, iteratively add consecutive cases to this switch stmt.
01271   while (NextCase && NextCase->getRHS() == nullptr) {
01272     CurCase = NextCase;
01273     llvm::ConstantInt *CaseVal =
01274       Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
01275 
01276     CaseCnt = getPGORegionCounter(NextCase);
01277     if (SwitchWeights)
01278       SwitchWeights->push_back(CaseCnt.getCount());
01279     if (CGM.getCodeGenOpts().ProfileInstrGenerate) {
01280       CaseDest = createBasicBlock("sw.bb");
01281       EmitBlockWithFallThrough(CaseDest, CaseCnt);
01282     }
01283 
01284     SwitchInsn->addCase(CaseVal, CaseDest);
01285     NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
01286   }
01287 
01288   // Normal default recursion for non-cases.
01289   EmitStmt(CurCase->getSubStmt());
01290 }
01291 
01292 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
01293   llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
01294   assert(DefaultBlock->empty() &&
01295          "EmitDefaultStmt: Default block already defined?");
01296 
01297   RegionCounter Cnt = getPGORegionCounter(&S);
01298   EmitBlockWithFallThrough(DefaultBlock, Cnt);
01299 
01300   EmitStmt(S.getSubStmt());
01301 }
01302 
01303 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
01304 /// constant value that is being switched on, see if we can dead code eliminate
01305 /// the body of the switch to a simple series of statements to emit.  Basically,
01306 /// on a switch (5) we want to find these statements:
01307 ///    case 5:
01308 ///      printf(...);    <--
01309 ///      ++i;            <--
01310 ///      break;
01311 ///
01312 /// and add them to the ResultStmts vector.  If it is unsafe to do this
01313 /// transformation (for example, one of the elided statements contains a label
01314 /// that might be jumped to), return CSFC_Failure.  If we handled it and 'S'
01315 /// should include statements after it (e.g. the printf() line is a substmt of
01316 /// the case) then return CSFC_FallThrough.  If we handled it and found a break
01317 /// statement, then return CSFC_Success.
01318 ///
01319 /// If Case is non-null, then we are looking for the specified case, checking
01320 /// that nothing we jump over contains labels.  If Case is null, then we found
01321 /// the case and are looking for the break.
01322 ///
01323 /// If the recursive walk actually finds our Case, then we set FoundCase to
01324 /// true.
01325 ///
01326 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
01327 static CSFC_Result CollectStatementsForCase(const Stmt *S,
01328                                             const SwitchCase *Case,
01329                                             bool &FoundCase,
01330                               SmallVectorImpl<const Stmt*> &ResultStmts) {
01331   // If this is a null statement, just succeed.
01332   if (!S)
01333     return Case ? CSFC_Success : CSFC_FallThrough;
01334 
01335   // If this is the switchcase (case 4: or default) that we're looking for, then
01336   // we're in business.  Just add the substatement.
01337   if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
01338     if (S == Case) {
01339       FoundCase = true;
01340       return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
01341                                       ResultStmts);
01342     }
01343 
01344     // Otherwise, this is some other case or default statement, just ignore it.
01345     return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
01346                                     ResultStmts);
01347   }
01348 
01349   // If we are in the live part of the code and we found our break statement,
01350   // return a success!
01351   if (!Case && isa<BreakStmt>(S))
01352     return CSFC_Success;
01353 
01354   // If this is a switch statement, then it might contain the SwitchCase, the
01355   // break, or neither.
01356   if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
01357     // Handle this as two cases: we might be looking for the SwitchCase (if so
01358     // the skipped statements must be skippable) or we might already have it.
01359     CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
01360     if (Case) {
01361       // Keep track of whether we see a skipped declaration.  The code could be
01362       // using the declaration even if it is skipped, so we can't optimize out
01363       // the decl if the kept statements might refer to it.
01364       bool HadSkippedDecl = false;
01365 
01366       // If we're looking for the case, just see if we can skip each of the
01367       // substatements.
01368       for (; Case && I != E; ++I) {
01369         HadSkippedDecl |= isa<DeclStmt>(*I);
01370 
01371         switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
01372         case CSFC_Failure: return CSFC_Failure;
01373         case CSFC_Success:
01374           // A successful result means that either 1) that the statement doesn't
01375           // have the case and is skippable, or 2) does contain the case value
01376           // and also contains the break to exit the switch.  In the later case,
01377           // we just verify the rest of the statements are elidable.
01378           if (FoundCase) {
01379             // If we found the case and skipped declarations, we can't do the
01380             // optimization.
01381             if (HadSkippedDecl)
01382               return CSFC_Failure;
01383 
01384             for (++I; I != E; ++I)
01385               if (CodeGenFunction::ContainsLabel(*I, true))
01386                 return CSFC_Failure;
01387             return CSFC_Success;
01388           }
01389           break;
01390         case CSFC_FallThrough:
01391           // If we have a fallthrough condition, then we must have found the
01392           // case started to include statements.  Consider the rest of the
01393           // statements in the compound statement as candidates for inclusion.
01394           assert(FoundCase && "Didn't find case but returned fallthrough?");
01395           // We recursively found Case, so we're not looking for it anymore.
01396           Case = nullptr;
01397 
01398           // If we found the case and skipped declarations, we can't do the
01399           // optimization.
01400           if (HadSkippedDecl)
01401             return CSFC_Failure;
01402           break;
01403         }
01404       }
01405     }
01406 
01407     // If we have statements in our range, then we know that the statements are
01408     // live and need to be added to the set of statements we're tracking.
01409     for (; I != E; ++I) {
01410       switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
01411       case CSFC_Failure: return CSFC_Failure;
01412       case CSFC_FallThrough:
01413         // A fallthrough result means that the statement was simple and just
01414         // included in ResultStmt, keep adding them afterwards.
01415         break;
01416       case CSFC_Success:
01417         // A successful result means that we found the break statement and
01418         // stopped statement inclusion.  We just ensure that any leftover stmts
01419         // are skippable and return success ourselves.
01420         for (++I; I != E; ++I)
01421           if (CodeGenFunction::ContainsLabel(*I, true))
01422             return CSFC_Failure;
01423         return CSFC_Success;
01424       }
01425     }
01426 
01427     return Case ? CSFC_Success : CSFC_FallThrough;
01428   }
01429 
01430   // Okay, this is some other statement that we don't handle explicitly, like a
01431   // for statement or increment etc.  If we are skipping over this statement,
01432   // just verify it doesn't have labels, which would make it invalid to elide.
01433   if (Case) {
01434     if (CodeGenFunction::ContainsLabel(S, true))
01435       return CSFC_Failure;
01436     return CSFC_Success;
01437   }
01438 
01439   // Otherwise, we want to include this statement.  Everything is cool with that
01440   // so long as it doesn't contain a break out of the switch we're in.
01441   if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
01442 
01443   // Otherwise, everything is great.  Include the statement and tell the caller
01444   // that we fall through and include the next statement as well.
01445   ResultStmts.push_back(S);
01446   return CSFC_FallThrough;
01447 }
01448 
01449 /// FindCaseStatementsForValue - Find the case statement being jumped to and
01450 /// then invoke CollectStatementsForCase to find the list of statements to emit
01451 /// for a switch on constant.  See the comment above CollectStatementsForCase
01452 /// for more details.
01453 static bool FindCaseStatementsForValue(const SwitchStmt &S,
01454                                        const llvm::APSInt &ConstantCondValue,
01455                                 SmallVectorImpl<const Stmt*> &ResultStmts,
01456                                        ASTContext &C,
01457                                        const SwitchCase *&ResultCase) {
01458   // First step, find the switch case that is being branched to.  We can do this
01459   // efficiently by scanning the SwitchCase list.
01460   const SwitchCase *Case = S.getSwitchCaseList();
01461   const DefaultStmt *DefaultCase = nullptr;
01462 
01463   for (; Case; Case = Case->getNextSwitchCase()) {
01464     // It's either a default or case.  Just remember the default statement in
01465     // case we're not jumping to any numbered cases.
01466     if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
01467       DefaultCase = DS;
01468       continue;
01469     }
01470 
01471     // Check to see if this case is the one we're looking for.
01472     const CaseStmt *CS = cast<CaseStmt>(Case);
01473     // Don't handle case ranges yet.
01474     if (CS->getRHS()) return false;
01475 
01476     // If we found our case, remember it as 'case'.
01477     if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
01478       break;
01479   }
01480 
01481   // If we didn't find a matching case, we use a default if it exists, or we
01482   // elide the whole switch body!
01483   if (!Case) {
01484     // It is safe to elide the body of the switch if it doesn't contain labels
01485     // etc.  If it is safe, return successfully with an empty ResultStmts list.
01486     if (!DefaultCase)
01487       return !CodeGenFunction::ContainsLabel(&S);
01488     Case = DefaultCase;
01489   }
01490 
01491   // Ok, we know which case is being jumped to, try to collect all the
01492   // statements that follow it.  This can fail for a variety of reasons.  Also,
01493   // check to see that the recursive walk actually found our case statement.
01494   // Insane cases like this can fail to find it in the recursive walk since we
01495   // don't handle every stmt kind:
01496   // switch (4) {
01497   //   while (1) {
01498   //     case 4: ...
01499   bool FoundCase = false;
01500   ResultCase = Case;
01501   return CollectStatementsForCase(S.getBody(), Case, FoundCase,
01502                                   ResultStmts) != CSFC_Failure &&
01503          FoundCase;
01504 }
01505 
01506 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
01507   // Handle nested switch statements.
01508   llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
01509   SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
01510   llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
01511 
01512   // See if we can constant fold the condition of the switch and therefore only
01513   // emit the live case statement (if any) of the switch.
01514   llvm::APSInt ConstantCondValue;
01515   if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
01516     SmallVector<const Stmt*, 4> CaseStmts;
01517     const SwitchCase *Case = nullptr;
01518     if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
01519                                    getContext(), Case)) {
01520       if (Case) {
01521         RegionCounter CaseCnt = getPGORegionCounter(Case);
01522         CaseCnt.beginRegion(Builder);
01523       }
01524       RunCleanupsScope ExecutedScope(*this);
01525 
01526       // Emit the condition variable if needed inside the entire cleanup scope
01527       // used by this special case for constant folded switches.
01528       if (S.getConditionVariable())
01529         EmitAutoVarDecl(*S.getConditionVariable());
01530 
01531       // At this point, we are no longer "within" a switch instance, so
01532       // we can temporarily enforce this to ensure that any embedded case
01533       // statements are not emitted.
01534       SwitchInsn = nullptr;
01535 
01536       // Okay, we can dead code eliminate everything except this case.  Emit the
01537       // specified series of statements and we're good.
01538       for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
01539         EmitStmt(CaseStmts[i]);
01540       RegionCounter ExitCnt = getPGORegionCounter(&S);
01541       ExitCnt.beginRegion(Builder);
01542 
01543       // Now we want to restore the saved switch instance so that nested
01544       // switches continue to function properly
01545       SwitchInsn = SavedSwitchInsn;
01546 
01547       return;
01548     }
01549   }
01550 
01551   JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
01552 
01553   RunCleanupsScope ConditionScope(*this);
01554   if (S.getConditionVariable())
01555     EmitAutoVarDecl(*S.getConditionVariable());
01556   llvm::Value *CondV = EmitScalarExpr(S.getCond());
01557 
01558   // Create basic block to hold stuff that comes after switch
01559   // statement. We also need to create a default block now so that
01560   // explicit case ranges tests can have a place to jump to on
01561   // failure.
01562   llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
01563   SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
01564   if (PGO.haveRegionCounts()) {
01565     // Walk the SwitchCase list to find how many there are.
01566     uint64_t DefaultCount = 0;
01567     unsigned NumCases = 0;
01568     for (const SwitchCase *Case = S.getSwitchCaseList();
01569          Case;
01570          Case = Case->getNextSwitchCase()) {
01571       if (isa<DefaultStmt>(Case))
01572         DefaultCount = getPGORegionCounter(Case).getCount();
01573       NumCases += 1;
01574     }
01575     SwitchWeights = new SmallVector<uint64_t, 16>();
01576     SwitchWeights->reserve(NumCases);
01577     // The default needs to be first. We store the edge count, so we already
01578     // know the right weight.
01579     SwitchWeights->push_back(DefaultCount);
01580   }
01581   CaseRangeBlock = DefaultBlock;
01582 
01583   // Clear the insertion point to indicate we are in unreachable code.
01584   Builder.ClearInsertionPoint();
01585 
01586   // All break statements jump to NextBlock. If BreakContinueStack is non-empty
01587   // then reuse last ContinueBlock.
01588   JumpDest OuterContinue;
01589   if (!BreakContinueStack.empty())
01590     OuterContinue = BreakContinueStack.back().ContinueBlock;
01591 
01592   BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
01593 
01594   // Emit switch body.
01595   EmitStmt(S.getBody());
01596 
01597   BreakContinueStack.pop_back();
01598 
01599   // Update the default block in case explicit case range tests have
01600   // been chained on top.
01601   SwitchInsn->setDefaultDest(CaseRangeBlock);
01602 
01603   // If a default was never emitted:
01604   if (!DefaultBlock->getParent()) {
01605     // If we have cleanups, emit the default block so that there's a
01606     // place to jump through the cleanups from.
01607     if (ConditionScope.requiresCleanups()) {
01608       EmitBlock(DefaultBlock);
01609 
01610     // Otherwise, just forward the default block to the switch end.
01611     } else {
01612       DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
01613       delete DefaultBlock;
01614     }
01615   }
01616 
01617   ConditionScope.ForceCleanup();
01618 
01619   // Emit continuation.
01620   EmitBlock(SwitchExit.getBlock(), true);
01621   RegionCounter ExitCnt = getPGORegionCounter(&S);
01622   ExitCnt.beginRegion(Builder);
01623 
01624   if (SwitchWeights) {
01625     assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
01626            "switch weights do not match switch cases");
01627     // If there's only one jump destination there's no sense weighting it.
01628     if (SwitchWeights->size() > 1)
01629       SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
01630                               PGO.createBranchWeights(*SwitchWeights));
01631     delete SwitchWeights;
01632   }
01633   SwitchInsn = SavedSwitchInsn;
01634   SwitchWeights = SavedSwitchWeights;
01635   CaseRangeBlock = SavedCRBlock;
01636 }
01637 
01638 static std::string
01639 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
01640                  SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) {
01641   std::string Result;
01642 
01643   while (*Constraint) {
01644     switch (*Constraint) {
01645     default:
01646       Result += Target.convertConstraint(Constraint);
01647       break;
01648     // Ignore these
01649     case '*':
01650     case '?':
01651     case '!':
01652     case '=': // Will see this and the following in mult-alt constraints.
01653     case '+':
01654       break;
01655     case '#': // Ignore the rest of the constraint alternative.
01656       while (Constraint[1] && Constraint[1] != ',')
01657         Constraint++;
01658       break;
01659     case ',':
01660       Result += "|";
01661       break;
01662     case 'g':
01663       Result += "imr";
01664       break;
01665     case '[': {
01666       assert(OutCons &&
01667              "Must pass output names to constraints with a symbolic name");
01668       unsigned Index;
01669       bool result = Target.resolveSymbolicName(Constraint,
01670                                                &(*OutCons)[0],
01671                                                OutCons->size(), Index);
01672       assert(result && "Could not resolve symbolic name"); (void)result;
01673       Result += llvm::utostr(Index);
01674       break;
01675     }
01676     }
01677 
01678     Constraint++;
01679   }
01680 
01681   return Result;
01682 }
01683 
01684 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
01685 /// as using a particular register add that as a constraint that will be used
01686 /// in this asm stmt.
01687 static std::string
01688 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
01689                        const TargetInfo &Target, CodeGenModule &CGM,
01690                        const AsmStmt &Stmt) {
01691   const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
01692   if (!AsmDeclRef)
01693     return Constraint;
01694   const ValueDecl &Value = *AsmDeclRef->getDecl();
01695   const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
01696   if (!Variable)
01697     return Constraint;
01698   if (Variable->getStorageClass() != SC_Register)
01699     return Constraint;
01700   AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
01701   if (!Attr)
01702     return Constraint;
01703   StringRef Register = Attr->getLabel();
01704   assert(Target.isValidGCCRegisterName(Register));
01705   // We're using validateOutputConstraint here because we only care if
01706   // this is a register constraint.
01707   TargetInfo::ConstraintInfo Info(Constraint, "");
01708   if (Target.validateOutputConstraint(Info) &&
01709       !Info.allowsRegister()) {
01710     CGM.ErrorUnsupported(&Stmt, "__asm__");
01711     return Constraint;
01712   }
01713   // Canonicalize the register here before returning it.
01714   Register = Target.getNormalizedGCCRegisterName(Register);
01715   return "{" + Register.str() + "}";
01716 }
01717 
01718 llvm::Value*
01719 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
01720                                     LValue InputValue, QualType InputType,
01721                                     std::string &ConstraintStr,
01722                                     SourceLocation Loc) {
01723   llvm::Value *Arg;
01724   if (Info.allowsRegister() || !Info.allowsMemory()) {
01725     if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
01726       Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
01727     } else {
01728       llvm::Type *Ty = ConvertType(InputType);
01729       uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
01730       if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
01731         Ty = llvm::IntegerType::get(getLLVMContext(), Size);
01732         Ty = llvm::PointerType::getUnqual(Ty);
01733 
01734         Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
01735                                                        Ty));
01736       } else {
01737         Arg = InputValue.getAddress();
01738         ConstraintStr += '*';
01739       }
01740     }
01741   } else {
01742     Arg = InputValue.getAddress();
01743     ConstraintStr += '*';
01744   }
01745 
01746   return Arg;
01747 }
01748 
01749 llvm::Value* CodeGenFunction::EmitAsmInput(
01750                                          const TargetInfo::ConstraintInfo &Info,
01751                                            const Expr *InputExpr,
01752                                            std::string &ConstraintStr) {
01753   if (Info.allowsRegister() || !Info.allowsMemory())
01754     if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
01755       return EmitScalarExpr(InputExpr);
01756 
01757   InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
01758   LValue Dest = EmitLValue(InputExpr);
01759   return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
01760                             InputExpr->getExprLoc());
01761 }
01762 
01763 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
01764 /// asm call instruction.  The !srcloc MDNode contains a list of constant
01765 /// integers which are the source locations of the start of each line in the
01766 /// asm.
01767 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
01768                                       CodeGenFunction &CGF) {
01769   SmallVector<llvm::Value *, 8> Locs;
01770   // Add the location of the first line to the MDNode.
01771   Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
01772                                         Str->getLocStart().getRawEncoding()));
01773   StringRef StrVal = Str->getString();
01774   if (!StrVal.empty()) {
01775     const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
01776     const LangOptions &LangOpts = CGF.CGM.getLangOpts();
01777 
01778     // Add the location of the start of each subsequent line of the asm to the
01779     // MDNode.
01780     for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
01781       if (StrVal[i] != '\n') continue;
01782       SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
01783                                                       CGF.getTarget());
01784       Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
01785                                             LineLoc.getRawEncoding()));
01786     }
01787   }
01788 
01789   return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
01790 }
01791 
01792 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
01793   // Assemble the final asm string.
01794   std::string AsmString = S.generateAsmString(getContext());
01795 
01796   // Get all the output and input constraints together.
01797   SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
01798   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
01799 
01800   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
01801     StringRef Name;
01802     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
01803       Name = GAS->getOutputName(i);
01804     TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
01805     bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
01806     assert(IsValid && "Failed to parse output constraint");
01807     OutputConstraintInfos.push_back(Info);
01808   }
01809 
01810   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
01811     StringRef Name;
01812     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
01813       Name = GAS->getInputName(i);
01814     TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
01815     bool IsValid =
01816       getTarget().validateInputConstraint(OutputConstraintInfos.data(),
01817                                           S.getNumOutputs(), Info);
01818     assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
01819     InputConstraintInfos.push_back(Info);
01820   }
01821 
01822   std::string Constraints;
01823 
01824   std::vector<LValue> ResultRegDests;
01825   std::vector<QualType> ResultRegQualTys;
01826   std::vector<llvm::Type *> ResultRegTypes;
01827   std::vector<llvm::Type *> ResultTruncRegTypes;
01828   std::vector<llvm::Type *> ArgTypes;
01829   std::vector<llvm::Value*> Args;
01830 
01831   // Keep track of inout constraints.
01832   std::string InOutConstraints;
01833   std::vector<llvm::Value*> InOutArgs;
01834   std::vector<llvm::Type*> InOutArgTypes;
01835 
01836   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
01837     TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
01838 
01839     // Simplify the output constraint.
01840     std::string OutputConstraint(S.getOutputConstraint(i));
01841     OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
01842                                           getTarget());
01843 
01844     const Expr *OutExpr = S.getOutputExpr(i);
01845     OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
01846 
01847     OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
01848                                               getTarget(), CGM, S);
01849 
01850     LValue Dest = EmitLValue(OutExpr);
01851     if (!Constraints.empty())
01852       Constraints += ',';
01853 
01854     // If this is a register output, then make the inline asm return it
01855     // by-value.  If this is a memory result, return the value by-reference.
01856     if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
01857       Constraints += "=" + OutputConstraint;
01858       ResultRegQualTys.push_back(OutExpr->getType());
01859       ResultRegDests.push_back(Dest);
01860       ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
01861       ResultTruncRegTypes.push_back(ResultRegTypes.back());
01862 
01863       // If this output is tied to an input, and if the input is larger, then
01864       // we need to set the actual result type of the inline asm node to be the
01865       // same as the input type.
01866       if (Info.hasMatchingInput()) {
01867         unsigned InputNo;
01868         for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
01869           TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
01870           if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
01871             break;
01872         }
01873         assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
01874 
01875         QualType InputTy = S.getInputExpr(InputNo)->getType();
01876         QualType OutputType = OutExpr->getType();
01877 
01878         uint64_t InputSize = getContext().getTypeSize(InputTy);
01879         if (getContext().getTypeSize(OutputType) < InputSize) {
01880           // Form the asm to return the value as a larger integer or fp type.
01881           ResultRegTypes.back() = ConvertType(InputTy);
01882         }
01883       }
01884       if (llvm::Type* AdjTy =
01885             getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
01886                                                  ResultRegTypes.back()))
01887         ResultRegTypes.back() = AdjTy;
01888       else {
01889         CGM.getDiags().Report(S.getAsmLoc(),
01890                               diag::err_asm_invalid_type_in_input)
01891             << OutExpr->getType() << OutputConstraint;
01892       }
01893     } else {
01894       ArgTypes.push_back(Dest.getAddress()->getType());
01895       Args.push_back(Dest.getAddress());
01896       Constraints += "=*";
01897       Constraints += OutputConstraint;
01898     }
01899 
01900     if (Info.isReadWrite()) {
01901       InOutConstraints += ',';
01902 
01903       const Expr *InputExpr = S.getOutputExpr(i);
01904       llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
01905                                             InOutConstraints,
01906                                             InputExpr->getExprLoc());
01907 
01908       if (llvm::Type* AdjTy =
01909           getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
01910                                                Arg->getType()))
01911         Arg = Builder.CreateBitCast(Arg, AdjTy);
01912 
01913       if (Info.allowsRegister())
01914         InOutConstraints += llvm::utostr(i);
01915       else
01916         InOutConstraints += OutputConstraint;
01917 
01918       InOutArgTypes.push_back(Arg->getType());
01919       InOutArgs.push_back(Arg);
01920     }
01921   }
01922 
01923   // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
01924   // to the return value slot. Only do this when returning in registers.
01925   if (isa<MSAsmStmt>(&S)) {
01926     const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
01927     if (RetAI.isDirect() || RetAI.isExtend()) {
01928       // Make a fake lvalue for the return value slot.
01929       LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy);
01930       CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
01931           *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
01932           ResultRegDests, AsmString, S.getNumOutputs());
01933       SawAsmBlock = true;
01934     }
01935   }
01936 
01937   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
01938     const Expr *InputExpr = S.getInputExpr(i);
01939 
01940     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
01941 
01942     if (!Constraints.empty())
01943       Constraints += ',';
01944 
01945     // Simplify the input constraint.
01946     std::string InputConstraint(S.getInputConstraint(i));
01947     InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
01948                                          &OutputConstraintInfos);
01949 
01950     InputConstraint =
01951       AddVariableConstraints(InputConstraint,
01952                             *InputExpr->IgnoreParenNoopCasts(getContext()),
01953                             getTarget(), CGM, S);
01954 
01955     llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
01956 
01957     // If this input argument is tied to a larger output result, extend the
01958     // input to be the same size as the output.  The LLVM backend wants to see
01959     // the input and output of a matching constraint be the same size.  Note
01960     // that GCC does not define what the top bits are here.  We use zext because
01961     // that is usually cheaper, but LLVM IR should really get an anyext someday.
01962     if (Info.hasTiedOperand()) {
01963       unsigned Output = Info.getTiedOperand();
01964       QualType OutputType = S.getOutputExpr(Output)->getType();
01965       QualType InputTy = InputExpr->getType();
01966 
01967       if (getContext().getTypeSize(OutputType) >
01968           getContext().getTypeSize(InputTy)) {
01969         // Use ptrtoint as appropriate so that we can do our extension.
01970         if (isa<llvm::PointerType>(Arg->getType()))
01971           Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
01972         llvm::Type *OutputTy = ConvertType(OutputType);
01973         if (isa<llvm::IntegerType>(OutputTy))
01974           Arg = Builder.CreateZExt(Arg, OutputTy);
01975         else if (isa<llvm::PointerType>(OutputTy))
01976           Arg = Builder.CreateZExt(Arg, IntPtrTy);
01977         else {
01978           assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
01979           Arg = Builder.CreateFPExt(Arg, OutputTy);
01980         }
01981       }
01982     }
01983     if (llvm::Type* AdjTy =
01984               getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
01985                                                    Arg->getType()))
01986       Arg = Builder.CreateBitCast(Arg, AdjTy);
01987     else
01988       CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
01989           << InputExpr->getType() << InputConstraint;
01990 
01991     ArgTypes.push_back(Arg->getType());
01992     Args.push_back(Arg);
01993     Constraints += InputConstraint;
01994   }
01995 
01996   // Append the "input" part of inout constraints last.
01997   for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
01998     ArgTypes.push_back(InOutArgTypes[i]);
01999     Args.push_back(InOutArgs[i]);
02000   }
02001   Constraints += InOutConstraints;
02002 
02003   // Clobbers
02004   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
02005     StringRef Clobber = S.getClobber(i);
02006 
02007     if (Clobber != "memory" && Clobber != "cc")
02008       Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
02009 
02010     if (!Constraints.empty())
02011       Constraints += ',';
02012 
02013     Constraints += "~{";
02014     Constraints += Clobber;
02015     Constraints += '}';
02016   }
02017 
02018   // Add machine specific clobbers
02019   std::string MachineClobbers = getTarget().getClobbers();
02020   if (!MachineClobbers.empty()) {
02021     if (!Constraints.empty())
02022       Constraints += ',';
02023     Constraints += MachineClobbers;
02024   }
02025 
02026   llvm::Type *ResultType;
02027   if (ResultRegTypes.empty())
02028     ResultType = VoidTy;
02029   else if (ResultRegTypes.size() == 1)
02030     ResultType = ResultRegTypes[0];
02031   else
02032     ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
02033 
02034   llvm::FunctionType *FTy =
02035     llvm::FunctionType::get(ResultType, ArgTypes, false);
02036 
02037   bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
02038   llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
02039     llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
02040   llvm::InlineAsm *IA =
02041     llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
02042                          /* IsAlignStack */ false, AsmDialect);
02043   llvm::CallInst *Result = Builder.CreateCall(IA, Args);
02044   Result->addAttribute(llvm::AttributeSet::FunctionIndex,
02045                        llvm::Attribute::NoUnwind);
02046 
02047   // Slap the source location of the inline asm into a !srcloc metadata on the
02048   // call.
02049   if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S)) {
02050     Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
02051                                                    *this));
02052   } else {
02053     // At least put the line number on MS inline asm blobs.
02054     auto Loc = llvm::ConstantInt::get(Int32Ty, S.getAsmLoc().getRawEncoding());
02055     Result->setMetadata("srcloc", llvm::MDNode::get(getLLVMContext(), Loc));
02056   }
02057 
02058   // Extract all of the register value results from the asm.
02059   std::vector<llvm::Value*> RegResults;
02060   if (ResultRegTypes.size() == 1) {
02061     RegResults.push_back(Result);
02062   } else {
02063     for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
02064       llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
02065       RegResults.push_back(Tmp);
02066     }
02067   }
02068 
02069   assert(RegResults.size() == ResultRegTypes.size());
02070   assert(RegResults.size() == ResultTruncRegTypes.size());
02071   assert(RegResults.size() == ResultRegDests.size());
02072   for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
02073     llvm::Value *Tmp = RegResults[i];
02074 
02075     // If the result type of the LLVM IR asm doesn't match the result type of
02076     // the expression, do the conversion.
02077     if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
02078       llvm::Type *TruncTy = ResultTruncRegTypes[i];
02079 
02080       // Truncate the integer result to the right size, note that TruncTy can be
02081       // a pointer.
02082       if (TruncTy->isFloatingPointTy())
02083         Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
02084       else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
02085         uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
02086         Tmp = Builder.CreateTrunc(Tmp,
02087                    llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
02088         Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
02089       } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
02090         uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
02091         Tmp = Builder.CreatePtrToInt(Tmp,
02092                    llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
02093         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
02094       } else if (TruncTy->isIntegerTy()) {
02095         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
02096       } else if (TruncTy->isVectorTy()) {
02097         Tmp = Builder.CreateBitCast(Tmp, TruncTy);
02098       }
02099     }
02100 
02101     EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
02102   }
02103 }
02104 
02105 LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) {
02106   const RecordDecl *RD = S.getCapturedRecordDecl();
02107   QualType RecordTy = getContext().getRecordType(RD);
02108 
02109   // Initialize the captured struct.
02110   LValue SlotLV = MakeNaturalAlignAddrLValue(
02111       CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
02112 
02113   RecordDecl::field_iterator CurField = RD->field_begin();
02114   for (CapturedStmt::capture_init_iterator I = S.capture_init_begin(),
02115                                            E = S.capture_init_end();
02116        I != E; ++I, ++CurField) {
02117     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
02118     if (CurField->hasCapturedVLAType()) {
02119       auto VAT = CurField->getCapturedVLAType();
02120       EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
02121     } else {
02122       EmitInitializerForField(*CurField, LV, *I, None);
02123     }
02124   }
02125 
02126   return SlotLV;
02127 }
02128 
02129 /// Generate an outlined function for the body of a CapturedStmt, store any
02130 /// captured variables into the captured struct, and call the outlined function.
02131 llvm::Function *
02132 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
02133   LValue CapStruct = InitCapturedStruct(S);
02134 
02135   // Emit the CapturedDecl
02136   CodeGenFunction CGF(CGM, true);
02137   CGF.CapturedStmtInfo = new CGCapturedStmtInfo(S, K);
02138   llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
02139   delete CGF.CapturedStmtInfo;
02140 
02141   // Emit call to the helper function.
02142   EmitCallOrInvoke(F, CapStruct.getAddress());
02143 
02144   return F;
02145 }
02146 
02147 llvm::Value *
02148 CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
02149   LValue CapStruct = InitCapturedStruct(S);
02150   return CapStruct.getAddress();
02151 }
02152 
02153 /// Creates the outlined function for a CapturedStmt.
02154 llvm::Function *
02155 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
02156   assert(CapturedStmtInfo &&
02157     "CapturedStmtInfo should be set when generating the captured function");
02158   const CapturedDecl *CD = S.getCapturedDecl();
02159   const RecordDecl *RD = S.getCapturedRecordDecl();
02160   SourceLocation Loc = S.getLocStart();
02161   assert(CD->hasBody() && "missing CapturedDecl body");
02162 
02163   // Build the argument list.
02164   ASTContext &Ctx = CGM.getContext();
02165   FunctionArgList Args;
02166   Args.append(CD->param_begin(), CD->param_end());
02167 
02168   // Create the function declaration.
02169   FunctionType::ExtInfo ExtInfo;
02170   const CGFunctionInfo &FuncInfo =
02171       CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
02172                                                     /*IsVariadic=*/false);
02173   llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
02174 
02175   llvm::Function *F =
02176     llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
02177                            CapturedStmtInfo->getHelperName(), &CGM.getModule());
02178   CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
02179 
02180   // Generate the function.
02181   StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args,
02182                 CD->getLocation(),
02183                 CD->getBody()->getLocStart());
02184   // Set the context parameter in CapturedStmtInfo.
02185   llvm::Value *DeclPtr = LocalDeclMap[CD->getContextParam()];
02186   assert(DeclPtr && "missing context parameter for CapturedStmt");
02187   CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
02188 
02189   // Initialize variable-length arrays.
02190   LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
02191                                            Ctx.getTagDeclType(RD));
02192   for (auto *FD : RD->fields()) {
02193     if (FD->hasCapturedVLAType()) {
02194       auto *ExprArg = EmitLoadOfLValue(EmitLValueForField(Base, FD),
02195                                        S.getLocStart()).getScalarVal();
02196       auto VAT = FD->getCapturedVLAType();
02197       VLASizeMap[VAT->getSizeExpr()] = ExprArg;
02198     }
02199   }
02200 
02201   // If 'this' is captured, load it into CXXThisValue.
02202   if (CapturedStmtInfo->isCXXThisExprCaptured()) {
02203     FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
02204     LValue ThisLValue = EmitLValueForField(Base, FD);
02205     CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
02206   }
02207 
02208   PGO.assignRegionCounters(CD, F);
02209   CapturedStmtInfo->EmitBody(*this, CD->getBody());
02210   FinishFunction(CD->getBodyRBrace());
02211   PGO.emitInstrumentationData();
02212   PGO.destroyRegionCounters();
02213 
02214   return F;
02215 }