1 //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to emit Stmt nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CGDebugInfo.h"
16 #include "CodeGenModule.h"
17 #include "TargetInfo.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/Basic/PrettyStackTrace.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Sema/LoopHint.h"
22 #include "clang/Sema/SemaDiagnostic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/IR/CallSite.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/InlineAsm.h"
27 #include "llvm/IR/Intrinsics.h"
28 using namespace clang;
29 using namespace CodeGen;
30 
31 //===----------------------------------------------------------------------===//
32 //                              Statement Emission
33 //===----------------------------------------------------------------------===//
34 
35 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
36   if (CGDebugInfo *DI = getDebugInfo()) {
37     SourceLocation Loc;
38     Loc = S->getLocStart();
39     DI->EmitLocation(Builder, Loc);
40 
41     LastStopPoint = Loc;
42   }
43 }
44 
45 void CodeGenFunction::EmitStmt(const Stmt *S) {
46   assert(S && "Null statement?");
47   PGO.setCurrentStmt(S);
48 
49   // These statements have their own debug info handling.
50   if (EmitSimpleStmt(S))
51     return;
52 
53   // Check if we are generating unreachable code.
54   if (!HaveInsertPoint()) {
55     // If so, and the statement doesn't contain a label, then we do not need to
56     // generate actual code. This is safe because (1) the current point is
57     // unreachable, so we don't need to execute the code, and (2) we've already
58     // handled the statements which update internal data structures (like the
59     // local variable map) which could be used by subsequent statements.
60     if (!ContainsLabel(S)) {
61       // Verify that any decl statements were handled as simple, they may be in
62       // scope of subsequent reachable statements.
63       assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
64       return;
65     }
66 
67     // Otherwise, make a new block to hold the code.
68     EnsureInsertPoint();
69   }
70 
71   // Generate a stoppoint if we are emitting debug info.
72   EmitStopPoint(S);
73 
74   switch (S->getStmtClass()) {
75   case Stmt::NoStmtClass:
76   case Stmt::CXXCatchStmtClass:
77   case Stmt::SEHExceptStmtClass:
78   case Stmt::SEHFinallyStmtClass:
79   case Stmt::MSDependentExistsStmtClass:
80     llvm_unreachable("invalid statement class to emit generically");
81   case Stmt::NullStmtClass:
82   case Stmt::CompoundStmtClass:
83   case Stmt::DeclStmtClass:
84   case Stmt::LabelStmtClass:
85   case Stmt::AttributedStmtClass:
86   case Stmt::GotoStmtClass:
87   case Stmt::BreakStmtClass:
88   case Stmt::ContinueStmtClass:
89   case Stmt::DefaultStmtClass:
90   case Stmt::CaseStmtClass:
91   case Stmt::SEHLeaveStmtClass:
92     llvm_unreachable("should have emitted these statements as simple");
93 
94 #define STMT(Type, Base)
95 #define ABSTRACT_STMT(Op)
96 #define EXPR(Type, Base) \
97   case Stmt::Type##Class:
98 #include "clang/AST/StmtNodes.inc"
99   {
100     // Remember the block we came in on.
101     llvm::BasicBlock *incoming = Builder.GetInsertBlock();
102     assert(incoming && "expression emission must have an insertion point");
103 
104     EmitIgnoredExpr(cast<Expr>(S));
105 
106     llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
107     assert(outgoing && "expression emission cleared block!");
108 
109     // The expression emitters assume (reasonably!) that the insertion
110     // point is always set.  To maintain that, the call-emission code
111     // for noreturn functions has to enter a new block with no
112     // predecessors.  We want to kill that block and mark the current
113     // insertion point unreachable in the common case of a call like
114     // "exit();".  Since expression emission doesn't otherwise create
115     // blocks with no predecessors, we can just test for that.
116     // However, we must be careful not to do this to our incoming
117     // block, because *statement* emission does sometimes create
118     // reachable blocks which will have no predecessors until later in
119     // the function.  This occurs with, e.g., labels that are not
120     // reachable by fallthrough.
121     if (incoming != outgoing && outgoing->use_empty()) {
122       outgoing->eraseFromParent();
123       Builder.ClearInsertionPoint();
124     }
125     break;
126   }
127 
128   case Stmt::IndirectGotoStmtClass:
129     EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
130 
131   case Stmt::IfStmtClass:       EmitIfStmt(cast<IfStmt>(*S));             break;
132   case Stmt::WhileStmtClass:    EmitWhileStmt(cast<WhileStmt>(*S));       break;
133   case Stmt::DoStmtClass:       EmitDoStmt(cast<DoStmt>(*S));             break;
134   case Stmt::ForStmtClass:      EmitForStmt(cast<ForStmt>(*S));           break;
135 
136   case Stmt::ReturnStmtClass:   EmitReturnStmt(cast<ReturnStmt>(*S));     break;
137 
138   case Stmt::SwitchStmtClass:   EmitSwitchStmt(cast<SwitchStmt>(*S));     break;
139   case Stmt::GCCAsmStmtClass:   // Intentional fall-through.
140   case Stmt::MSAsmStmtClass:    EmitAsmStmt(cast<AsmStmt>(*S));           break;
141   case Stmt::CapturedStmtClass: {
142     const CapturedStmt *CS = cast<CapturedStmt>(S);
143     EmitCapturedStmt(*CS, CS->getCapturedRegionKind());
144     }
145     break;
146   case Stmt::ObjCAtTryStmtClass:
147     EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
148     break;
149   case Stmt::ObjCAtCatchStmtClass:
150     llvm_unreachable(
151                     "@catch statements should be handled by EmitObjCAtTryStmt");
152   case Stmt::ObjCAtFinallyStmtClass:
153     llvm_unreachable(
154                   "@finally statements should be handled by EmitObjCAtTryStmt");
155   case Stmt::ObjCAtThrowStmtClass:
156     EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
157     break;
158   case Stmt::ObjCAtSynchronizedStmtClass:
159     EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
160     break;
161   case Stmt::ObjCForCollectionStmtClass:
162     EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
163     break;
164   case Stmt::ObjCAutoreleasePoolStmtClass:
165     EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
166     break;
167 
168   case Stmt::CXXTryStmtClass:
169     EmitCXXTryStmt(cast<CXXTryStmt>(*S));
170     break;
171   case Stmt::CXXForRangeStmtClass:
172     EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
173     break;
174   case Stmt::SEHTryStmtClass:
175     EmitSEHTryStmt(cast<SEHTryStmt>(*S));
176     break;
177   case Stmt::OMPParallelDirectiveClass:
178     EmitOMPParallelDirective(cast<OMPParallelDirective>(*S));
179     break;
180   case Stmt::OMPSimdDirectiveClass:
181     EmitOMPSimdDirective(cast<OMPSimdDirective>(*S));
182     break;
183   case Stmt::OMPForDirectiveClass:
184     EmitOMPForDirective(cast<OMPForDirective>(*S));
185     break;
186   case Stmt::OMPForSimdDirectiveClass:
187     EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S));
188     break;
189   case Stmt::OMPSectionsDirectiveClass:
190     EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S));
191     break;
192   case Stmt::OMPSectionDirectiveClass:
193     EmitOMPSectionDirective(cast<OMPSectionDirective>(*S));
194     break;
195   case Stmt::OMPSingleDirectiveClass:
196     EmitOMPSingleDirective(cast<OMPSingleDirective>(*S));
197     break;
198   case Stmt::OMPMasterDirectiveClass:
199     EmitOMPMasterDirective(cast<OMPMasterDirective>(*S));
200     break;
201   case Stmt::OMPCriticalDirectiveClass:
202     EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S));
203     break;
204   case Stmt::OMPParallelForDirectiveClass:
205     EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S));
206     break;
207   case Stmt::OMPParallelForSimdDirectiveClass:
208     EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S));
209     break;
210   case Stmt::OMPParallelSectionsDirectiveClass:
211     EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S));
212     break;
213   case Stmt::OMPTaskDirectiveClass:
214     EmitOMPTaskDirective(cast<OMPTaskDirective>(*S));
215     break;
216   case Stmt::OMPTaskyieldDirectiveClass:
217     EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S));
218     break;
219   case Stmt::OMPBarrierDirectiveClass:
220     EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S));
221     break;
222   case Stmt::OMPTaskwaitDirectiveClass:
223     EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S));
224     break;
225   case Stmt::OMPTaskgroupDirectiveClass:
226     EmitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*S));
227     break;
228   case Stmt::OMPFlushDirectiveClass:
229     EmitOMPFlushDirective(cast<OMPFlushDirective>(*S));
230     break;
231   case Stmt::OMPOrderedDirectiveClass:
232     EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S));
233     break;
234   case Stmt::OMPAtomicDirectiveClass:
235     EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S));
236     break;
237   case Stmt::OMPTargetDirectiveClass:
238     EmitOMPTargetDirective(cast<OMPTargetDirective>(*S));
239     break;
240   case Stmt::OMPTeamsDirectiveClass:
241     EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S));
242     break;
243   }
244 }
245 
246 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
247   switch (S->getStmtClass()) {
248   default: return false;
249   case Stmt::NullStmtClass: break;
250   case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
251   case Stmt::DeclStmtClass:     EmitDeclStmt(cast<DeclStmt>(*S));         break;
252   case Stmt::LabelStmtClass:    EmitLabelStmt(cast<LabelStmt>(*S));       break;
253   case Stmt::AttributedStmtClass:
254                             EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
255   case Stmt::GotoStmtClass:     EmitGotoStmt(cast<GotoStmt>(*S));         break;
256   case Stmt::BreakStmtClass:    EmitBreakStmt(cast<BreakStmt>(*S));       break;
257   case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
258   case Stmt::DefaultStmtClass:  EmitDefaultStmt(cast<DefaultStmt>(*S));   break;
259   case Stmt::CaseStmtClass:     EmitCaseStmt(cast<CaseStmt>(*S));         break;
260   case Stmt::SEHLeaveStmtClass: EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S)); break;
261   }
262 
263   return true;
264 }
265 
266 /// EmitCompoundStmt - Emit a compound statement {..} node.  If GetLast is true,
267 /// this captures the expression result of the last sub-statement and returns it
268 /// (for use by the statement expression extension).
269 llvm::Value* CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
270                                                AggValueSlot AggSlot) {
271   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
272                              "LLVM IR generation of compound statement ('{}')");
273 
274   // Keep track of the current cleanup stack depth, including debug scopes.
275   LexicalScope Scope(*this, S.getSourceRange());
276 
277   return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
278 }
279 
280 llvm::Value*
281 CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S,
282                                               bool GetLast,
283                                               AggValueSlot AggSlot) {
284 
285   for (CompoundStmt::const_body_iterator I = S.body_begin(),
286        E = S.body_end()-GetLast; I != E; ++I)
287     EmitStmt(*I);
288 
289   llvm::Value *RetAlloca = nullptr;
290   if (GetLast) {
291     // We have to special case labels here.  They are statements, but when put
292     // at the end of a statement expression, they yield the value of their
293     // subexpression.  Handle this by walking through all labels we encounter,
294     // emitting them before we evaluate the subexpr.
295     const Stmt *LastStmt = S.body_back();
296     while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
297       EmitLabel(LS->getDecl());
298       LastStmt = LS->getSubStmt();
299     }
300 
301     EnsureInsertPoint();
302 
303     QualType ExprTy = cast<Expr>(LastStmt)->getType();
304     if (hasAggregateEvaluationKind(ExprTy)) {
305       EmitAggExpr(cast<Expr>(LastStmt), AggSlot);
306     } else {
307       // We can't return an RValue here because there might be cleanups at
308       // the end of the StmtExpr.  Because of that, we have to emit the result
309       // here into a temporary alloca.
310       RetAlloca = CreateMemTemp(ExprTy);
311       EmitAnyExprToMem(cast<Expr>(LastStmt), RetAlloca, Qualifiers(),
312                        /*IsInit*/false);
313     }
314 
315   }
316 
317   return RetAlloca;
318 }
319 
320 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
321   llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
322 
323   // If there is a cleanup stack, then we it isn't worth trying to
324   // simplify this block (we would need to remove it from the scope map
325   // and cleanup entry).
326   if (!EHStack.empty())
327     return;
328 
329   // Can only simplify direct branches.
330   if (!BI || !BI->isUnconditional())
331     return;
332 
333   // Can only simplify empty blocks.
334   if (BI != BB->begin())
335     return;
336 
337   BB->replaceAllUsesWith(BI->getSuccessor(0));
338   BI->eraseFromParent();
339   BB->eraseFromParent();
340 }
341 
342 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
343   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
344 
345   // Fall out of the current block (if necessary).
346   EmitBranch(BB);
347 
348   if (IsFinished && BB->use_empty()) {
349     delete BB;
350     return;
351   }
352 
353   // Place the block after the current block, if possible, or else at
354   // the end of the function.
355   if (CurBB && CurBB->getParent())
356     CurFn->getBasicBlockList().insertAfter(CurBB, BB);
357   else
358     CurFn->getBasicBlockList().push_back(BB);
359   Builder.SetInsertPoint(BB);
360 }
361 
362 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
363   // Emit a branch from the current block to the target one if this
364   // was a real block.  If this was just a fall-through block after a
365   // terminator, don't emit it.
366   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
367 
368   if (!CurBB || CurBB->getTerminator()) {
369     // If there is no insert point or the previous block is already
370     // terminated, don't touch it.
371   } else {
372     // Otherwise, create a fall-through branch.
373     Builder.CreateBr(Target);
374   }
375 
376   Builder.ClearInsertionPoint();
377 }
378 
379 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
380   bool inserted = false;
381   for (llvm::User *u : block->users()) {
382     if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
383       CurFn->getBasicBlockList().insertAfter(insn->getParent(), block);
384       inserted = true;
385       break;
386     }
387   }
388 
389   if (!inserted)
390     CurFn->getBasicBlockList().push_back(block);
391 
392   Builder.SetInsertPoint(block);
393 }
394 
395 CodeGenFunction::JumpDest
396 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
397   JumpDest &Dest = LabelMap[D];
398   if (Dest.isValid()) return Dest;
399 
400   // Create, but don't insert, the new block.
401   Dest = JumpDest(createBasicBlock(D->getName()),
402                   EHScopeStack::stable_iterator::invalid(),
403                   NextCleanupDestIndex++);
404   return Dest;
405 }
406 
407 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
408   // Add this label to the current lexical scope if we're within any
409   // normal cleanups.  Jumps "in" to this label --- when permitted by
410   // the language --- may need to be routed around such cleanups.
411   if (EHStack.hasNormalCleanups() && CurLexicalScope)
412     CurLexicalScope->addLabel(D);
413 
414   JumpDest &Dest = LabelMap[D];
415 
416   // If we didn't need a forward reference to this label, just go
417   // ahead and create a destination at the current scope.
418   if (!Dest.isValid()) {
419     Dest = getJumpDestInCurrentScope(D->getName());
420 
421   // Otherwise, we need to give this label a target depth and remove
422   // it from the branch-fixups list.
423   } else {
424     assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
425     Dest.setScopeDepth(EHStack.stable_begin());
426     ResolveBranchFixups(Dest.getBlock());
427   }
428 
429   EmitBlock(Dest.getBlock());
430   incrementProfileCounter(D->getStmt());
431 }
432 
433 /// Change the cleanup scope of the labels in this lexical scope to
434 /// match the scope of the enclosing context.
435 void CodeGenFunction::LexicalScope::rescopeLabels() {
436   assert(!Labels.empty());
437   EHScopeStack::stable_iterator innermostScope
438     = CGF.EHStack.getInnermostNormalCleanup();
439 
440   // Change the scope depth of all the labels.
441   for (SmallVectorImpl<const LabelDecl*>::const_iterator
442          i = Labels.begin(), e = Labels.end(); i != e; ++i) {
443     assert(CGF.LabelMap.count(*i));
444     JumpDest &dest = CGF.LabelMap.find(*i)->second;
445     assert(dest.getScopeDepth().isValid());
446     assert(innermostScope.encloses(dest.getScopeDepth()));
447     dest.setScopeDepth(innermostScope);
448   }
449 
450   // Reparent the labels if the new scope also has cleanups.
451   if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
452     ParentScope->Labels.append(Labels.begin(), Labels.end());
453   }
454 }
455 
456 
457 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
458   EmitLabel(S.getDecl());
459   EmitStmt(S.getSubStmt());
460 }
461 
462 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
463   const Stmt *SubStmt = S.getSubStmt();
464   switch (SubStmt->getStmtClass()) {
465   case Stmt::DoStmtClass:
466     EmitDoStmt(cast<DoStmt>(*SubStmt), S.getAttrs());
467     break;
468   case Stmt::ForStmtClass:
469     EmitForStmt(cast<ForStmt>(*SubStmt), S.getAttrs());
470     break;
471   case Stmt::WhileStmtClass:
472     EmitWhileStmt(cast<WhileStmt>(*SubStmt), S.getAttrs());
473     break;
474   case Stmt::CXXForRangeStmtClass:
475     EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*SubStmt), S.getAttrs());
476     break;
477   default:
478     EmitStmt(SubStmt);
479   }
480 }
481 
482 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
483   // If this code is reachable then emit a stop point (if generating
484   // debug info). We have to do this ourselves because we are on the
485   // "simple" statement path.
486   if (HaveInsertPoint())
487     EmitStopPoint(&S);
488 
489   EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
490 }
491 
492 
493 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
494   if (const LabelDecl *Target = S.getConstantTarget()) {
495     EmitBranchThroughCleanup(getJumpDestForLabel(Target));
496     return;
497   }
498 
499   // Ensure that we have an i8* for our PHI node.
500   llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
501                                          Int8PtrTy, "addr");
502   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
503 
504   // Get the basic block for the indirect goto.
505   llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
506 
507   // The first instruction in the block has to be the PHI for the switch dest,
508   // add an entry for this branch.
509   cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
510 
511   EmitBranch(IndGotoBB);
512 }
513 
514 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
515   // C99 6.8.4.1: The first substatement is executed if the expression compares
516   // unequal to 0.  The condition must be a scalar type.
517   LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
518 
519   if (S.getConditionVariable())
520     EmitAutoVarDecl(*S.getConditionVariable());
521 
522   // If the condition constant folds and can be elided, try to avoid emitting
523   // the condition and the dead arm of the if/else.
524   bool CondConstant;
525   if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) {
526     // Figure out which block (then or else) is executed.
527     const Stmt *Executed = S.getThen();
528     const Stmt *Skipped  = S.getElse();
529     if (!CondConstant)  // Condition false?
530       std::swap(Executed, Skipped);
531 
532     // If the skipped block has no labels in it, just emit the executed block.
533     // This avoids emitting dead code and simplifies the CFG substantially.
534     if (!ContainsLabel(Skipped)) {
535       if (CondConstant)
536         incrementProfileCounter(&S);
537       if (Executed) {
538         RunCleanupsScope ExecutedScope(*this);
539         EmitStmt(Executed);
540       }
541       return;
542     }
543   }
544 
545   // Otherwise, the condition did not fold, or we couldn't elide it.  Just emit
546   // the conditional branch.
547   llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
548   llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
549   llvm::BasicBlock *ElseBlock = ContBlock;
550   if (S.getElse())
551     ElseBlock = createBasicBlock("if.else");
552 
553   EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock,
554                        getProfileCount(S.getThen()));
555 
556   // Emit the 'then' code.
557   EmitBlock(ThenBlock);
558   incrementProfileCounter(&S);
559   {
560     RunCleanupsScope ThenScope(*this);
561     EmitStmt(S.getThen());
562   }
563   EmitBranch(ContBlock);
564 
565   // Emit the 'else' code if present.
566   if (const Stmt *Else = S.getElse()) {
567     {
568       // There is no need to emit line number for an unconditional branch.
569       auto NL = ApplyDebugLocation::CreateEmpty(*this);
570       EmitBlock(ElseBlock);
571     }
572     {
573       RunCleanupsScope ElseScope(*this);
574       EmitStmt(Else);
575     }
576     {
577       // There is no need to emit line number for an unconditional branch.
578       auto NL = ApplyDebugLocation::CreateEmpty(*this);
579       EmitBranch(ContBlock);
580     }
581   }
582 
583   // Emit the continuation block for code after the if.
584   EmitBlock(ContBlock, true);
585 }
586 
587 void CodeGenFunction::EmitCondBrHints(llvm::LLVMContext &Context,
588                                       llvm::BranchInst *CondBr,
589                                       ArrayRef<const Attr *> Attrs) {
590   // Return if there are no hints.
591   if (Attrs.empty())
592     return;
593 
594   // Add vectorize and unroll hints to the metadata on the conditional branch.
595   //
596   // FIXME: Should this really start with a size of 1?
597   SmallVector<llvm::Metadata *, 2> Metadata(1);
598   for (const auto *Attr : Attrs) {
599     const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(Attr);
600 
601     // Skip non loop hint attributes
602     if (!LH)
603       continue;
604 
605     LoopHintAttr::OptionType Option = LH->getOption();
606     LoopHintAttr::LoopHintState State = LH->getState();
607     const char *MetadataName;
608     switch (Option) {
609     case LoopHintAttr::Vectorize:
610     case LoopHintAttr::VectorizeWidth:
611       MetadataName = "llvm.loop.vectorize.width";
612       break;
613     case LoopHintAttr::Interleave:
614     case LoopHintAttr::InterleaveCount:
615       MetadataName = "llvm.loop.interleave.count";
616       break;
617     case LoopHintAttr::Unroll:
618       // With the unroll loop hint, a non-zero value indicates full unrolling.
619       MetadataName = State == LoopHintAttr::Disable ? "llvm.loop.unroll.disable"
620                                                     : "llvm.loop.unroll.full";
621       break;
622     case LoopHintAttr::UnrollCount:
623       MetadataName = "llvm.loop.unroll.count";
624       break;
625     }
626 
627     Expr *ValueExpr = LH->getValue();
628     int ValueInt = 1;
629     if (ValueExpr) {
630       llvm::APSInt ValueAPS =
631           ValueExpr->EvaluateKnownConstInt(CGM.getContext());
632       ValueInt = static_cast<int>(ValueAPS.getSExtValue());
633     }
634 
635     llvm::Constant *Value;
636     llvm::MDString *Name;
637     switch (Option) {
638     case LoopHintAttr::Vectorize:
639     case LoopHintAttr::Interleave:
640       if (State != LoopHintAttr::Disable) {
641         // FIXME: In the future I will modifiy the behavior of the metadata
642         // so we can enable/disable vectorization and interleaving separately.
643         Name = llvm::MDString::get(Context, "llvm.loop.vectorize.enable");
644         Value = Builder.getTrue();
645         break;
646       }
647       // Vectorization/interleaving is disabled, set width/count to 1.
648       ValueInt = 1;
649       // Fallthrough.
650     case LoopHintAttr::VectorizeWidth:
651     case LoopHintAttr::InterleaveCount:
652     case LoopHintAttr::UnrollCount:
653       Name = llvm::MDString::get(Context, MetadataName);
654       Value = llvm::ConstantInt::get(Int32Ty, ValueInt);
655       break;
656     case LoopHintAttr::Unroll:
657       Name = llvm::MDString::get(Context, MetadataName);
658       Value = nullptr;
659       break;
660     }
661 
662     SmallVector<llvm::Metadata *, 2> OpValues;
663     OpValues.push_back(Name);
664     if (Value)
665       OpValues.push_back(llvm::ConstantAsMetadata::get(Value));
666 
667     // Set or overwrite metadata indicated by Name.
668     Metadata.push_back(llvm::MDNode::get(Context, OpValues));
669   }
670 
671   // FIXME: This condition is never false.  Should it be an assert?
672   if (!Metadata.empty()) {
673     // Add llvm.loop MDNode to CondBr.
674     llvm::MDNode *LoopID = llvm::MDNode::get(Context, Metadata);
675     LoopID->replaceOperandWith(0, LoopID); // First op points to itself.
676 
677     CondBr->setMetadata("llvm.loop", LoopID);
678   }
679 }
680 
681 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
682                                     ArrayRef<const Attr *> WhileAttrs) {
683   // Emit the header for the loop, which will also become
684   // the continue target.
685   JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
686   EmitBlock(LoopHeader.getBlock());
687 
688   LoopStack.push(LoopHeader.getBlock(), WhileAttrs);
689 
690   // Create an exit block for when the condition fails, which will
691   // also become the break target.
692   JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
693 
694   // Store the blocks to use for break and continue.
695   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
696 
697   // C++ [stmt.while]p2:
698   //   When the condition of a while statement is a declaration, the
699   //   scope of the variable that is declared extends from its point
700   //   of declaration (3.3.2) to the end of the while statement.
701   //   [...]
702   //   The object created in a condition is destroyed and created
703   //   with each iteration of the loop.
704   RunCleanupsScope ConditionScope(*this);
705 
706   if (S.getConditionVariable())
707     EmitAutoVarDecl(*S.getConditionVariable());
708 
709   // Evaluate the conditional in the while header.  C99 6.8.5.1: The
710   // evaluation of the controlling expression takes place before each
711   // execution of the loop body.
712   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
713 
714   // while(1) is common, avoid extra exit blocks.  Be sure
715   // to correctly handle break/continue though.
716   bool EmitBoolCondBranch = true;
717   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
718     if (C->isOne())
719       EmitBoolCondBranch = false;
720 
721   // As long as the condition is true, go to the loop body.
722   llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
723   if (EmitBoolCondBranch) {
724     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
725     if (ConditionScope.requiresCleanups())
726       ExitBlock = createBasicBlock("while.exit");
727     llvm::BranchInst *CondBr = Builder.CreateCondBr(
728         BoolCondVal, LoopBody, ExitBlock,
729         createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
730 
731     if (ExitBlock != LoopExit.getBlock()) {
732       EmitBlock(ExitBlock);
733       EmitBranchThroughCleanup(LoopExit);
734     }
735 
736     // Attach metadata to loop body conditional branch.
737     EmitCondBrHints(LoopBody->getContext(), CondBr, WhileAttrs);
738   }
739 
740   // Emit the loop body.  We have to emit this in a cleanup scope
741   // because it might be a singleton DeclStmt.
742   {
743     RunCleanupsScope BodyScope(*this);
744     EmitBlock(LoopBody);
745     incrementProfileCounter(&S);
746     EmitStmt(S.getBody());
747   }
748 
749   BreakContinueStack.pop_back();
750 
751   // Immediately force cleanup.
752   ConditionScope.ForceCleanup();
753 
754   EmitStopPoint(&S);
755   // Branch to the loop header again.
756   EmitBranch(LoopHeader.getBlock());
757 
758   LoopStack.pop();
759 
760   // Emit the exit block.
761   EmitBlock(LoopExit.getBlock(), true);
762 
763   // The LoopHeader typically is just a branch if we skipped emitting
764   // a branch, try to erase it.
765   if (!EmitBoolCondBranch)
766     SimplifyForwardingBlocks(LoopHeader.getBlock());
767 }
768 
769 void CodeGenFunction::EmitDoStmt(const DoStmt &S,
770                                  ArrayRef<const Attr *> DoAttrs) {
771   JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
772   JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
773 
774   uint64_t ParentCount = getCurrentProfileCount();
775 
776   // Store the blocks to use for break and continue.
777   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
778 
779   // Emit the body of the loop.
780   llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
781 
782   LoopStack.push(LoopBody, DoAttrs);
783 
784   EmitBlockWithFallThrough(LoopBody, &S);
785   {
786     RunCleanupsScope BodyScope(*this);
787     EmitStmt(S.getBody());
788   }
789 
790   EmitBlock(LoopCond.getBlock());
791 
792   // C99 6.8.5.2: "The evaluation of the controlling expression takes place
793   // after each execution of the loop body."
794 
795   // Evaluate the conditional in the while header.
796   // C99 6.8.5p2/p4: The first substatement is executed if the expression
797   // compares unequal to 0.  The condition must be a scalar type.
798   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
799 
800   BreakContinueStack.pop_back();
801 
802   // "do {} while (0)" is common in macros, avoid extra blocks.  Be sure
803   // to correctly handle break/continue though.
804   bool EmitBoolCondBranch = true;
805   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
806     if (C->isZero())
807       EmitBoolCondBranch = false;
808 
809   // As long as the condition is true, iterate the loop.
810   if (EmitBoolCondBranch) {
811     uint64_t BackedgeCount = getProfileCount(S.getBody()) - ParentCount;
812     llvm::BranchInst *CondBr = Builder.CreateCondBr(
813         BoolCondVal, LoopBody, LoopExit.getBlock(),
814         createProfileWeightsForLoop(S.getCond(), BackedgeCount));
815 
816     // Attach metadata to loop body conditional branch.
817     EmitCondBrHints(LoopBody->getContext(), CondBr, DoAttrs);
818   }
819 
820   LoopStack.pop();
821 
822   // Emit the exit block.
823   EmitBlock(LoopExit.getBlock());
824 
825   // The DoCond block typically is just a branch if we skipped
826   // emitting a branch, try to erase it.
827   if (!EmitBoolCondBranch)
828     SimplifyForwardingBlocks(LoopCond.getBlock());
829 }
830 
831 void CodeGenFunction::EmitForStmt(const ForStmt &S,
832                                   ArrayRef<const Attr *> ForAttrs) {
833   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
834 
835   LexicalScope ForScope(*this, S.getSourceRange());
836 
837   // Evaluate the first part before the loop.
838   if (S.getInit())
839     EmitStmt(S.getInit());
840 
841   // Start the loop with a block that tests the condition.
842   // If there's an increment, the continue scope will be overwritten
843   // later.
844   JumpDest Continue = getJumpDestInCurrentScope("for.cond");
845   llvm::BasicBlock *CondBlock = Continue.getBlock();
846   EmitBlock(CondBlock);
847 
848   LoopStack.push(CondBlock, ForAttrs);
849 
850   // If the for loop doesn't have an increment we can just use the
851   // condition as the continue block.  Otherwise we'll need to create
852   // a block for it (in the current scope, i.e. in the scope of the
853   // condition), and that we will become our continue block.
854   if (S.getInc())
855     Continue = getJumpDestInCurrentScope("for.inc");
856 
857   // Store the blocks to use for break and continue.
858   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
859 
860   // Create a cleanup scope for the condition variable cleanups.
861   LexicalScope ConditionScope(*this, S.getSourceRange());
862 
863   if (S.getCond()) {
864     // If the for statement has a condition scope, emit the local variable
865     // declaration.
866     if (S.getConditionVariable()) {
867       EmitAutoVarDecl(*S.getConditionVariable());
868     }
869 
870     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
871     // If there are any cleanups between here and the loop-exit scope,
872     // create a block to stage a loop exit along.
873     if (ForScope.requiresCleanups())
874       ExitBlock = createBasicBlock("for.cond.cleanup");
875 
876     // As long as the condition is true, iterate the loop.
877     llvm::BasicBlock *ForBody = createBasicBlock("for.body");
878 
879     // C99 6.8.5p2/p4: The first substatement is executed if the expression
880     // compares unequal to 0.  The condition must be a scalar type.
881     llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
882     llvm::BranchInst *CondBr = Builder.CreateCondBr(
883         BoolCondVal, ForBody, ExitBlock,
884         createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
885 
886     // Attach metadata to loop body conditional branch.
887     EmitCondBrHints(ForBody->getContext(), CondBr, ForAttrs);
888 
889     if (ExitBlock != LoopExit.getBlock()) {
890       EmitBlock(ExitBlock);
891       EmitBranchThroughCleanup(LoopExit);
892     }
893 
894     EmitBlock(ForBody);
895   } else {
896     // Treat it as a non-zero constant.  Don't even create a new block for the
897     // body, just fall into it.
898   }
899   incrementProfileCounter(&S);
900 
901   {
902     // Create a separate cleanup scope for the body, in case it is not
903     // a compound statement.
904     RunCleanupsScope BodyScope(*this);
905     EmitStmt(S.getBody());
906   }
907 
908   // If there is an increment, emit it next.
909   if (S.getInc()) {
910     EmitBlock(Continue.getBlock());
911     EmitStmt(S.getInc());
912   }
913 
914   BreakContinueStack.pop_back();
915 
916   ConditionScope.ForceCleanup();
917 
918   EmitStopPoint(&S);
919   EmitBranch(CondBlock);
920 
921   ForScope.ForceCleanup();
922 
923   LoopStack.pop();
924 
925   // Emit the fall-through block.
926   EmitBlock(LoopExit.getBlock(), true);
927 }
928 
929 void
930 CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
931                                      ArrayRef<const Attr *> ForAttrs) {
932   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
933 
934   LexicalScope ForScope(*this, S.getSourceRange());
935 
936   // Evaluate the first pieces before the loop.
937   EmitStmt(S.getRangeStmt());
938   EmitStmt(S.getBeginEndStmt());
939 
940   // Start the loop with a block that tests the condition.
941   // If there's an increment, the continue scope will be overwritten
942   // later.
943   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
944   EmitBlock(CondBlock);
945 
946   LoopStack.push(CondBlock, ForAttrs);
947 
948   // If there are any cleanups between here and the loop-exit scope,
949   // create a block to stage a loop exit along.
950   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
951   if (ForScope.requiresCleanups())
952     ExitBlock = createBasicBlock("for.cond.cleanup");
953 
954   // The loop body, consisting of the specified body and the loop variable.
955   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
956 
957   // The body is executed if the expression, contextually converted
958   // to bool, is true.
959   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
960   llvm::BranchInst *CondBr = Builder.CreateCondBr(
961       BoolCondVal, ForBody, ExitBlock,
962       createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
963 
964   // Attach metadata to loop body conditional branch.
965   EmitCondBrHints(ForBody->getContext(), CondBr, ForAttrs);
966 
967   if (ExitBlock != LoopExit.getBlock()) {
968     EmitBlock(ExitBlock);
969     EmitBranchThroughCleanup(LoopExit);
970   }
971 
972   EmitBlock(ForBody);
973   incrementProfileCounter(&S);
974 
975   // Create a block for the increment. In case of a 'continue', we jump there.
976   JumpDest Continue = getJumpDestInCurrentScope("for.inc");
977 
978   // Store the blocks to use for break and continue.
979   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
980 
981   {
982     // Create a separate cleanup scope for the loop variable and body.
983     LexicalScope BodyScope(*this, S.getSourceRange());
984     EmitStmt(S.getLoopVarStmt());
985     EmitStmt(S.getBody());
986   }
987 
988   EmitStopPoint(&S);
989   // If there is an increment, emit it next.
990   EmitBlock(Continue.getBlock());
991   EmitStmt(S.getInc());
992 
993   BreakContinueStack.pop_back();
994 
995   EmitBranch(CondBlock);
996 
997   ForScope.ForceCleanup();
998 
999   LoopStack.pop();
1000 
1001   // Emit the fall-through block.
1002   EmitBlock(LoopExit.getBlock(), true);
1003 }
1004 
1005 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
1006   if (RV.isScalar()) {
1007     Builder.CreateStore(RV.getScalarVal(), ReturnValue);
1008   } else if (RV.isAggregate()) {
1009     EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
1010   } else {
1011     EmitStoreOfComplex(RV.getComplexVal(),
1012                        MakeNaturalAlignAddrLValue(ReturnValue, Ty),
1013                        /*init*/ true);
1014   }
1015   EmitBranchThroughCleanup(ReturnBlock);
1016 }
1017 
1018 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
1019 /// if the function returns void, or may be missing one if the function returns
1020 /// non-void.  Fun stuff :).
1021 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
1022   // Returning from an outlined SEH helper is UB, and we already warn on it.
1023   if (IsOutlinedSEHHelper) {
1024     Builder.CreateUnreachable();
1025     Builder.ClearInsertionPoint();
1026   }
1027 
1028   // Emit the result value, even if unused, to evalute the side effects.
1029   const Expr *RV = S.getRetValue();
1030 
1031   // Treat block literals in a return expression as if they appeared
1032   // in their own scope.  This permits a small, easily-implemented
1033   // exception to our over-conservative rules about not jumping to
1034   // statements following block literals with non-trivial cleanups.
1035   RunCleanupsScope cleanupScope(*this);
1036   if (const ExprWithCleanups *cleanups =
1037         dyn_cast_or_null<ExprWithCleanups>(RV)) {
1038     enterFullExpression(cleanups);
1039     RV = cleanups->getSubExpr();
1040   }
1041 
1042   // FIXME: Clean this up by using an LValue for ReturnTemp,
1043   // EmitStoreThroughLValue, and EmitAnyExpr.
1044   if (getLangOpts().ElideConstructors &&
1045       S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
1046     // Apply the named return value optimization for this return statement,
1047     // which means doing nothing: the appropriate result has already been
1048     // constructed into the NRVO variable.
1049 
1050     // If there is an NRVO flag for this variable, set it to 1 into indicate
1051     // that the cleanup code should not destroy the variable.
1052     if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
1053       Builder.CreateStore(Builder.getTrue(), NRVOFlag);
1054   } else if (!ReturnValue || (RV && RV->getType()->isVoidType())) {
1055     // Make sure not to return anything, but evaluate the expression
1056     // for side effects.
1057     if (RV)
1058       EmitAnyExpr(RV);
1059   } else if (!RV) {
1060     // Do nothing (return value is left uninitialized)
1061   } else if (FnRetTy->isReferenceType()) {
1062     // If this function returns a reference, take the address of the expression
1063     // rather than the value.
1064     RValue Result = EmitReferenceBindingToExpr(RV);
1065     Builder.CreateStore(Result.getScalarVal(), ReturnValue);
1066   } else {
1067     switch (getEvaluationKind(RV->getType())) {
1068     case TEK_Scalar:
1069       Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
1070       break;
1071     case TEK_Complex:
1072       EmitComplexExprIntoLValue(RV,
1073                      MakeNaturalAlignAddrLValue(ReturnValue, RV->getType()),
1074                                 /*isInit*/ true);
1075       break;
1076     case TEK_Aggregate: {
1077       CharUnits Alignment = getContext().getTypeAlignInChars(RV->getType());
1078       EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Alignment,
1079                                             Qualifiers(),
1080                                             AggValueSlot::IsDestructed,
1081                                             AggValueSlot::DoesNotNeedGCBarriers,
1082                                             AggValueSlot::IsNotAliased));
1083       break;
1084     }
1085     }
1086   }
1087 
1088   ++NumReturnExprs;
1089   if (!RV || RV->isEvaluatable(getContext()))
1090     ++NumSimpleReturnExprs;
1091 
1092   cleanupScope.ForceCleanup();
1093   EmitBranchThroughCleanup(ReturnBlock);
1094 }
1095 
1096 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
1097   // As long as debug info is modeled with instructions, we have to ensure we
1098   // have a place to insert here and write the stop point here.
1099   if (HaveInsertPoint())
1100     EmitStopPoint(&S);
1101 
1102   for (const auto *I : S.decls())
1103     EmitDecl(*I);
1104 }
1105 
1106 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
1107   assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1108 
1109   // If this code is reachable then emit a stop point (if generating
1110   // debug info). We have to do this ourselves because we are on the
1111   // "simple" statement path.
1112   if (HaveInsertPoint())
1113     EmitStopPoint(&S);
1114 
1115   EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
1116 }
1117 
1118 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
1119   assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1120 
1121   // If this code is reachable then emit a stop point (if generating
1122   // debug info). We have to do this ourselves because we are on the
1123   // "simple" statement path.
1124   if (HaveInsertPoint())
1125     EmitStopPoint(&S);
1126 
1127   EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
1128 }
1129 
1130 /// EmitCaseStmtRange - If case statement range is not too big then
1131 /// add multiple cases to switch instruction, one for each value within
1132 /// the range. If range is too big then emit "if" condition check.
1133 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
1134   assert(S.getRHS() && "Expected RHS value in CaseStmt");
1135 
1136   llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
1137   llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
1138 
1139   // Emit the code for this case. We do this first to make sure it is
1140   // properly chained from our predecessor before generating the
1141   // switch machinery to enter this block.
1142   llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1143   EmitBlockWithFallThrough(CaseDest, &S);
1144   EmitStmt(S.getSubStmt());
1145 
1146   // If range is empty, do nothing.
1147   if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
1148     return;
1149 
1150   llvm::APInt Range = RHS - LHS;
1151   // FIXME: parameters such as this should not be hardcoded.
1152   if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
1153     // Range is small enough to add multiple switch instruction cases.
1154     uint64_t Total = getProfileCount(&S);
1155     unsigned NCases = Range.getZExtValue() + 1;
1156     // We only have one region counter for the entire set of cases here, so we
1157     // need to divide the weights evenly between the generated cases, ensuring
1158     // that the total weight is preserved. E.g., a weight of 5 over three cases
1159     // will be distributed as weights of 2, 2, and 1.
1160     uint64_t Weight = Total / NCases, Rem = Total % NCases;
1161     for (unsigned I = 0; I != NCases; ++I) {
1162       if (SwitchWeights)
1163         SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
1164       if (Rem)
1165         Rem--;
1166       SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
1167       LHS++;
1168     }
1169     return;
1170   }
1171 
1172   // The range is too big. Emit "if" condition into a new block,
1173   // making sure to save and restore the current insertion point.
1174   llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
1175 
1176   // Push this test onto the chain of range checks (which terminates
1177   // in the default basic block). The switch's default will be changed
1178   // to the top of this chain after switch emission is complete.
1179   llvm::BasicBlock *FalseDest = CaseRangeBlock;
1180   CaseRangeBlock = createBasicBlock("sw.caserange");
1181 
1182   CurFn->getBasicBlockList().push_back(CaseRangeBlock);
1183   Builder.SetInsertPoint(CaseRangeBlock);
1184 
1185   // Emit range check.
1186   llvm::Value *Diff =
1187     Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
1188   llvm::Value *Cond =
1189     Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
1190 
1191   llvm::MDNode *Weights = nullptr;
1192   if (SwitchWeights) {
1193     uint64_t ThisCount = getProfileCount(&S);
1194     uint64_t DefaultCount = (*SwitchWeights)[0];
1195     Weights = createProfileWeights(ThisCount, DefaultCount);
1196 
1197     // Since we're chaining the switch default through each large case range, we
1198     // need to update the weight for the default, ie, the first case, to include
1199     // this case.
1200     (*SwitchWeights)[0] += ThisCount;
1201   }
1202   Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
1203 
1204   // Restore the appropriate insertion point.
1205   if (RestoreBB)
1206     Builder.SetInsertPoint(RestoreBB);
1207   else
1208     Builder.ClearInsertionPoint();
1209 }
1210 
1211 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
1212   // If there is no enclosing switch instance that we're aware of, then this
1213   // case statement and its block can be elided.  This situation only happens
1214   // when we've constant-folded the switch, are emitting the constant case,
1215   // and part of the constant case includes another case statement.  For
1216   // instance: switch (4) { case 4: do { case 5: } while (1); }
1217   if (!SwitchInsn) {
1218     EmitStmt(S.getSubStmt());
1219     return;
1220   }
1221 
1222   // Handle case ranges.
1223   if (S.getRHS()) {
1224     EmitCaseStmtRange(S);
1225     return;
1226   }
1227 
1228   llvm::ConstantInt *CaseVal =
1229     Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
1230 
1231   // If the body of the case is just a 'break', try to not emit an empty block.
1232   // If we're profiling or we're not optimizing, leave the block in for better
1233   // debug and coverage analysis.
1234   if (!CGM.getCodeGenOpts().ProfileInstrGenerate &&
1235       CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1236       isa<BreakStmt>(S.getSubStmt())) {
1237     JumpDest Block = BreakContinueStack.back().BreakBlock;
1238 
1239     // Only do this optimization if there are no cleanups that need emitting.
1240     if (isObviouslyBranchWithoutCleanups(Block)) {
1241       if (SwitchWeights)
1242         SwitchWeights->push_back(getProfileCount(&S));
1243       SwitchInsn->addCase(CaseVal, Block.getBlock());
1244 
1245       // If there was a fallthrough into this case, make sure to redirect it to
1246       // the end of the switch as well.
1247       if (Builder.GetInsertBlock()) {
1248         Builder.CreateBr(Block.getBlock());
1249         Builder.ClearInsertionPoint();
1250       }
1251       return;
1252     }
1253   }
1254 
1255   llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1256   EmitBlockWithFallThrough(CaseDest, &S);
1257   if (SwitchWeights)
1258     SwitchWeights->push_back(getProfileCount(&S));
1259   SwitchInsn->addCase(CaseVal, CaseDest);
1260 
1261   // Recursively emitting the statement is acceptable, but is not wonderful for
1262   // code where we have many case statements nested together, i.e.:
1263   //  case 1:
1264   //    case 2:
1265   //      case 3: etc.
1266   // Handling this recursively will create a new block for each case statement
1267   // that falls through to the next case which is IR intensive.  It also causes
1268   // deep recursion which can run into stack depth limitations.  Handle
1269   // sequential non-range case statements specially.
1270   const CaseStmt *CurCase = &S;
1271   const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1272 
1273   // Otherwise, iteratively add consecutive cases to this switch stmt.
1274   while (NextCase && NextCase->getRHS() == nullptr) {
1275     CurCase = NextCase;
1276     llvm::ConstantInt *CaseVal =
1277       Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1278 
1279     if (SwitchWeights)
1280       SwitchWeights->push_back(getProfileCount(NextCase));
1281     if (CGM.getCodeGenOpts().ProfileInstrGenerate) {
1282       CaseDest = createBasicBlock("sw.bb");
1283       EmitBlockWithFallThrough(CaseDest, &S);
1284     }
1285 
1286     SwitchInsn->addCase(CaseVal, CaseDest);
1287     NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1288   }
1289 
1290   // Normal default recursion for non-cases.
1291   EmitStmt(CurCase->getSubStmt());
1292 }
1293 
1294 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
1295   llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1296   assert(DefaultBlock->empty() &&
1297          "EmitDefaultStmt: Default block already defined?");
1298 
1299   EmitBlockWithFallThrough(DefaultBlock, &S);
1300 
1301   EmitStmt(S.getSubStmt());
1302 }
1303 
1304 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
1305 /// constant value that is being switched on, see if we can dead code eliminate
1306 /// the body of the switch to a simple series of statements to emit.  Basically,
1307 /// on a switch (5) we want to find these statements:
1308 ///    case 5:
1309 ///      printf(...);    <--
1310 ///      ++i;            <--
1311 ///      break;
1312 ///
1313 /// and add them to the ResultStmts vector.  If it is unsafe to do this
1314 /// transformation (for example, one of the elided statements contains a label
1315 /// that might be jumped to), return CSFC_Failure.  If we handled it and 'S'
1316 /// should include statements after it (e.g. the printf() line is a substmt of
1317 /// the case) then return CSFC_FallThrough.  If we handled it and found a break
1318 /// statement, then return CSFC_Success.
1319 ///
1320 /// If Case is non-null, then we are looking for the specified case, checking
1321 /// that nothing we jump over contains labels.  If Case is null, then we found
1322 /// the case and are looking for the break.
1323 ///
1324 /// If the recursive walk actually finds our Case, then we set FoundCase to
1325 /// true.
1326 ///
1327 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
1328 static CSFC_Result CollectStatementsForCase(const Stmt *S,
1329                                             const SwitchCase *Case,
1330                                             bool &FoundCase,
1331                               SmallVectorImpl<const Stmt*> &ResultStmts) {
1332   // If this is a null statement, just succeed.
1333   if (!S)
1334     return Case ? CSFC_Success : CSFC_FallThrough;
1335 
1336   // If this is the switchcase (case 4: or default) that we're looking for, then
1337   // we're in business.  Just add the substatement.
1338   if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1339     if (S == Case) {
1340       FoundCase = true;
1341       return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
1342                                       ResultStmts);
1343     }
1344 
1345     // Otherwise, this is some other case or default statement, just ignore it.
1346     return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1347                                     ResultStmts);
1348   }
1349 
1350   // If we are in the live part of the code and we found our break statement,
1351   // return a success!
1352   if (!Case && isa<BreakStmt>(S))
1353     return CSFC_Success;
1354 
1355   // If this is a switch statement, then it might contain the SwitchCase, the
1356   // break, or neither.
1357   if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1358     // Handle this as two cases: we might be looking for the SwitchCase (if so
1359     // the skipped statements must be skippable) or we might already have it.
1360     CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1361     if (Case) {
1362       // Keep track of whether we see a skipped declaration.  The code could be
1363       // using the declaration even if it is skipped, so we can't optimize out
1364       // the decl if the kept statements might refer to it.
1365       bool HadSkippedDecl = false;
1366 
1367       // If we're looking for the case, just see if we can skip each of the
1368       // substatements.
1369       for (; Case && I != E; ++I) {
1370         HadSkippedDecl |= isa<DeclStmt>(*I);
1371 
1372         switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1373         case CSFC_Failure: return CSFC_Failure;
1374         case CSFC_Success:
1375           // A successful result means that either 1) that the statement doesn't
1376           // have the case and is skippable, or 2) does contain the case value
1377           // and also contains the break to exit the switch.  In the later case,
1378           // we just verify the rest of the statements are elidable.
1379           if (FoundCase) {
1380             // If we found the case and skipped declarations, we can't do the
1381             // optimization.
1382             if (HadSkippedDecl)
1383               return CSFC_Failure;
1384 
1385             for (++I; I != E; ++I)
1386               if (CodeGenFunction::ContainsLabel(*I, true))
1387                 return CSFC_Failure;
1388             return CSFC_Success;
1389           }
1390           break;
1391         case CSFC_FallThrough:
1392           // If we have a fallthrough condition, then we must have found the
1393           // case started to include statements.  Consider the rest of the
1394           // statements in the compound statement as candidates for inclusion.
1395           assert(FoundCase && "Didn't find case but returned fallthrough?");
1396           // We recursively found Case, so we're not looking for it anymore.
1397           Case = nullptr;
1398 
1399           // If we found the case and skipped declarations, we can't do the
1400           // optimization.
1401           if (HadSkippedDecl)
1402             return CSFC_Failure;
1403           break;
1404         }
1405       }
1406     }
1407 
1408     // If we have statements in our range, then we know that the statements are
1409     // live and need to be added to the set of statements we're tracking.
1410     for (; I != E; ++I) {
1411       switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
1412       case CSFC_Failure: return CSFC_Failure;
1413       case CSFC_FallThrough:
1414         // A fallthrough result means that the statement was simple and just
1415         // included in ResultStmt, keep adding them afterwards.
1416         break;
1417       case CSFC_Success:
1418         // A successful result means that we found the break statement and
1419         // stopped statement inclusion.  We just ensure that any leftover stmts
1420         // are skippable and return success ourselves.
1421         for (++I; I != E; ++I)
1422           if (CodeGenFunction::ContainsLabel(*I, true))
1423             return CSFC_Failure;
1424         return CSFC_Success;
1425       }
1426     }
1427 
1428     return Case ? CSFC_Success : CSFC_FallThrough;
1429   }
1430 
1431   // Okay, this is some other statement that we don't handle explicitly, like a
1432   // for statement or increment etc.  If we are skipping over this statement,
1433   // just verify it doesn't have labels, which would make it invalid to elide.
1434   if (Case) {
1435     if (CodeGenFunction::ContainsLabel(S, true))
1436       return CSFC_Failure;
1437     return CSFC_Success;
1438   }
1439 
1440   // Otherwise, we want to include this statement.  Everything is cool with that
1441   // so long as it doesn't contain a break out of the switch we're in.
1442   if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1443 
1444   // Otherwise, everything is great.  Include the statement and tell the caller
1445   // that we fall through and include the next statement as well.
1446   ResultStmts.push_back(S);
1447   return CSFC_FallThrough;
1448 }
1449 
1450 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1451 /// then invoke CollectStatementsForCase to find the list of statements to emit
1452 /// for a switch on constant.  See the comment above CollectStatementsForCase
1453 /// for more details.
1454 static bool FindCaseStatementsForValue(const SwitchStmt &S,
1455                                        const llvm::APSInt &ConstantCondValue,
1456                                 SmallVectorImpl<const Stmt*> &ResultStmts,
1457                                        ASTContext &C,
1458                                        const SwitchCase *&ResultCase) {
1459   // First step, find the switch case that is being branched to.  We can do this
1460   // efficiently by scanning the SwitchCase list.
1461   const SwitchCase *Case = S.getSwitchCaseList();
1462   const DefaultStmt *DefaultCase = nullptr;
1463 
1464   for (; Case; Case = Case->getNextSwitchCase()) {
1465     // It's either a default or case.  Just remember the default statement in
1466     // case we're not jumping to any numbered cases.
1467     if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1468       DefaultCase = DS;
1469       continue;
1470     }
1471 
1472     // Check to see if this case is the one we're looking for.
1473     const CaseStmt *CS = cast<CaseStmt>(Case);
1474     // Don't handle case ranges yet.
1475     if (CS->getRHS()) return false;
1476 
1477     // If we found our case, remember it as 'case'.
1478     if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
1479       break;
1480   }
1481 
1482   // If we didn't find a matching case, we use a default if it exists, or we
1483   // elide the whole switch body!
1484   if (!Case) {
1485     // It is safe to elide the body of the switch if it doesn't contain labels
1486     // etc.  If it is safe, return successfully with an empty ResultStmts list.
1487     if (!DefaultCase)
1488       return !CodeGenFunction::ContainsLabel(&S);
1489     Case = DefaultCase;
1490   }
1491 
1492   // Ok, we know which case is being jumped to, try to collect all the
1493   // statements that follow it.  This can fail for a variety of reasons.  Also,
1494   // check to see that the recursive walk actually found our case statement.
1495   // Insane cases like this can fail to find it in the recursive walk since we
1496   // don't handle every stmt kind:
1497   // switch (4) {
1498   //   while (1) {
1499   //     case 4: ...
1500   bool FoundCase = false;
1501   ResultCase = Case;
1502   return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1503                                   ResultStmts) != CSFC_Failure &&
1504          FoundCase;
1505 }
1506 
1507 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1508   // Handle nested switch statements.
1509   llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1510   SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
1511   llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1512 
1513   // See if we can constant fold the condition of the switch and therefore only
1514   // emit the live case statement (if any) of the switch.
1515   llvm::APSInt ConstantCondValue;
1516   if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1517     SmallVector<const Stmt*, 4> CaseStmts;
1518     const SwitchCase *Case = nullptr;
1519     if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1520                                    getContext(), Case)) {
1521       if (Case)
1522         incrementProfileCounter(Case);
1523       RunCleanupsScope ExecutedScope(*this);
1524 
1525       // Emit the condition variable if needed inside the entire cleanup scope
1526       // used by this special case for constant folded switches.
1527       if (S.getConditionVariable())
1528         EmitAutoVarDecl(*S.getConditionVariable());
1529 
1530       // At this point, we are no longer "within" a switch instance, so
1531       // we can temporarily enforce this to ensure that any embedded case
1532       // statements are not emitted.
1533       SwitchInsn = nullptr;
1534 
1535       // Okay, we can dead code eliminate everything except this case.  Emit the
1536       // specified series of statements and we're good.
1537       for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1538         EmitStmt(CaseStmts[i]);
1539       incrementProfileCounter(&S);
1540 
1541       // Now we want to restore the saved switch instance so that nested
1542       // switches continue to function properly
1543       SwitchInsn = SavedSwitchInsn;
1544 
1545       return;
1546     }
1547   }
1548 
1549   JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1550 
1551   RunCleanupsScope ConditionScope(*this);
1552   if (S.getConditionVariable())
1553     EmitAutoVarDecl(*S.getConditionVariable());
1554   llvm::Value *CondV = EmitScalarExpr(S.getCond());
1555 
1556   // Create basic block to hold stuff that comes after switch
1557   // statement. We also need to create a default block now so that
1558   // explicit case ranges tests can have a place to jump to on
1559   // failure.
1560   llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1561   SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1562   if (PGO.haveRegionCounts()) {
1563     // Walk the SwitchCase list to find how many there are.
1564     uint64_t DefaultCount = 0;
1565     unsigned NumCases = 0;
1566     for (const SwitchCase *Case = S.getSwitchCaseList();
1567          Case;
1568          Case = Case->getNextSwitchCase()) {
1569       if (isa<DefaultStmt>(Case))
1570         DefaultCount = getProfileCount(Case);
1571       NumCases += 1;
1572     }
1573     SwitchWeights = new SmallVector<uint64_t, 16>();
1574     SwitchWeights->reserve(NumCases);
1575     // The default needs to be first. We store the edge count, so we already
1576     // know the right weight.
1577     SwitchWeights->push_back(DefaultCount);
1578   }
1579   CaseRangeBlock = DefaultBlock;
1580 
1581   // Clear the insertion point to indicate we are in unreachable code.
1582   Builder.ClearInsertionPoint();
1583 
1584   // All break statements jump to NextBlock. If BreakContinueStack is non-empty
1585   // then reuse last ContinueBlock.
1586   JumpDest OuterContinue;
1587   if (!BreakContinueStack.empty())
1588     OuterContinue = BreakContinueStack.back().ContinueBlock;
1589 
1590   BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1591 
1592   // Emit switch body.
1593   EmitStmt(S.getBody());
1594 
1595   BreakContinueStack.pop_back();
1596 
1597   // Update the default block in case explicit case range tests have
1598   // been chained on top.
1599   SwitchInsn->setDefaultDest(CaseRangeBlock);
1600 
1601   // If a default was never emitted:
1602   if (!DefaultBlock->getParent()) {
1603     // If we have cleanups, emit the default block so that there's a
1604     // place to jump through the cleanups from.
1605     if (ConditionScope.requiresCleanups()) {
1606       EmitBlock(DefaultBlock);
1607 
1608     // Otherwise, just forward the default block to the switch end.
1609     } else {
1610       DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1611       delete DefaultBlock;
1612     }
1613   }
1614 
1615   ConditionScope.ForceCleanup();
1616 
1617   // Emit continuation.
1618   EmitBlock(SwitchExit.getBlock(), true);
1619   incrementProfileCounter(&S);
1620 
1621   if (SwitchWeights) {
1622     assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
1623            "switch weights do not match switch cases");
1624     // If there's only one jump destination there's no sense weighting it.
1625     if (SwitchWeights->size() > 1)
1626       SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
1627                               createProfileWeights(*SwitchWeights));
1628     delete SwitchWeights;
1629   }
1630   SwitchInsn = SavedSwitchInsn;
1631   SwitchWeights = SavedSwitchWeights;
1632   CaseRangeBlock = SavedCRBlock;
1633 }
1634 
1635 static std::string
1636 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1637                  SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) {
1638   std::string Result;
1639 
1640   while (*Constraint) {
1641     switch (*Constraint) {
1642     default:
1643       Result += Target.convertConstraint(Constraint);
1644       break;
1645     // Ignore these
1646     case '*':
1647     case '?':
1648     case '!':
1649     case '=': // Will see this and the following in mult-alt constraints.
1650     case '+':
1651       break;
1652     case '#': // Ignore the rest of the constraint alternative.
1653       while (Constraint[1] && Constraint[1] != ',')
1654         Constraint++;
1655       break;
1656     case '&':
1657     case '%':
1658       Result += *Constraint;
1659       while (Constraint[1] && Constraint[1] == *Constraint)
1660         Constraint++;
1661       break;
1662     case ',':
1663       Result += "|";
1664       break;
1665     case 'g':
1666       Result += "imr";
1667       break;
1668     case '[': {
1669       assert(OutCons &&
1670              "Must pass output names to constraints with a symbolic name");
1671       unsigned Index;
1672       bool result = Target.resolveSymbolicName(Constraint,
1673                                                &(*OutCons)[0],
1674                                                OutCons->size(), Index);
1675       assert(result && "Could not resolve symbolic name"); (void)result;
1676       Result += llvm::utostr(Index);
1677       break;
1678     }
1679     }
1680 
1681     Constraint++;
1682   }
1683 
1684   return Result;
1685 }
1686 
1687 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1688 /// as using a particular register add that as a constraint that will be used
1689 /// in this asm stmt.
1690 static std::string
1691 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1692                        const TargetInfo &Target, CodeGenModule &CGM,
1693                        const AsmStmt &Stmt, const bool EarlyClobber) {
1694   const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1695   if (!AsmDeclRef)
1696     return Constraint;
1697   const ValueDecl &Value = *AsmDeclRef->getDecl();
1698   const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1699   if (!Variable)
1700     return Constraint;
1701   if (Variable->getStorageClass() != SC_Register)
1702     return Constraint;
1703   AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1704   if (!Attr)
1705     return Constraint;
1706   StringRef Register = Attr->getLabel();
1707   assert(Target.isValidGCCRegisterName(Register));
1708   // We're using validateOutputConstraint here because we only care if
1709   // this is a register constraint.
1710   TargetInfo::ConstraintInfo Info(Constraint, "");
1711   if (Target.validateOutputConstraint(Info) &&
1712       !Info.allowsRegister()) {
1713     CGM.ErrorUnsupported(&Stmt, "__asm__");
1714     return Constraint;
1715   }
1716   // Canonicalize the register here before returning it.
1717   Register = Target.getNormalizedGCCRegisterName(Register);
1718   return (EarlyClobber ? "&{" : "{") + Register.str() + "}";
1719 }
1720 
1721 llvm::Value*
1722 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
1723                                     LValue InputValue, QualType InputType,
1724                                     std::string &ConstraintStr,
1725                                     SourceLocation Loc) {
1726   llvm::Value *Arg;
1727   if (Info.allowsRegister() || !Info.allowsMemory()) {
1728     if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
1729       Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
1730     } else {
1731       llvm::Type *Ty = ConvertType(InputType);
1732       uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
1733       if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1734         Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1735         Ty = llvm::PointerType::getUnqual(Ty);
1736 
1737         Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1738                                                        Ty));
1739       } else {
1740         Arg = InputValue.getAddress();
1741         ConstraintStr += '*';
1742       }
1743     }
1744   } else {
1745     Arg = InputValue.getAddress();
1746     ConstraintStr += '*';
1747   }
1748 
1749   return Arg;
1750 }
1751 
1752 llvm::Value* CodeGenFunction::EmitAsmInput(
1753                                          const TargetInfo::ConstraintInfo &Info,
1754                                            const Expr *InputExpr,
1755                                            std::string &ConstraintStr) {
1756   // If this can't be a register or memory, i.e., has to be a constant
1757   // (immediate or symbolic), try to emit it as such.
1758   if (!Info.allowsRegister() && !Info.allowsMemory()) {
1759     llvm::APSInt Result;
1760     if (InputExpr->EvaluateAsInt(Result, getContext()))
1761       return llvm::ConstantInt::get(getLLVMContext(), Result);
1762     assert(!Info.requiresImmediateConstant() &&
1763            "Required-immediate inlineasm arg isn't constant?");
1764   }
1765 
1766   if (Info.allowsRegister() || !Info.allowsMemory())
1767     if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
1768       return EmitScalarExpr(InputExpr);
1769 
1770   InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1771   LValue Dest = EmitLValue(InputExpr);
1772   return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
1773                             InputExpr->getExprLoc());
1774 }
1775 
1776 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1777 /// asm call instruction.  The !srcloc MDNode contains a list of constant
1778 /// integers which are the source locations of the start of each line in the
1779 /// asm.
1780 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1781                                       CodeGenFunction &CGF) {
1782   SmallVector<llvm::Metadata *, 8> Locs;
1783   // Add the location of the first line to the MDNode.
1784   Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1785       CGF.Int32Ty, Str->getLocStart().getRawEncoding())));
1786   StringRef StrVal = Str->getString();
1787   if (!StrVal.empty()) {
1788     const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1789     const LangOptions &LangOpts = CGF.CGM.getLangOpts();
1790 
1791     // Add the location of the start of each subsequent line of the asm to the
1792     // MDNode.
1793     for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
1794       if (StrVal[i] != '\n') continue;
1795       SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
1796                                                       CGF.getTarget());
1797       Locs.push_back(llvm::ConstantAsMetadata::get(
1798           llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding())));
1799     }
1800   }
1801 
1802   return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1803 }
1804 
1805 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1806   // Assemble the final asm string.
1807   std::string AsmString = S.generateAsmString(getContext());
1808 
1809   // Get all the output and input constraints together.
1810   SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1811   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1812 
1813   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1814     StringRef Name;
1815     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1816       Name = GAS->getOutputName(i);
1817     TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
1818     bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
1819     assert(IsValid && "Failed to parse output constraint");
1820     OutputConstraintInfos.push_back(Info);
1821   }
1822 
1823   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1824     StringRef Name;
1825     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1826       Name = GAS->getInputName(i);
1827     TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
1828     bool IsValid =
1829       getTarget().validateInputConstraint(OutputConstraintInfos.data(),
1830                                           S.getNumOutputs(), Info);
1831     assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1832     InputConstraintInfos.push_back(Info);
1833   }
1834 
1835   std::string Constraints;
1836 
1837   std::vector<LValue> ResultRegDests;
1838   std::vector<QualType> ResultRegQualTys;
1839   std::vector<llvm::Type *> ResultRegTypes;
1840   std::vector<llvm::Type *> ResultTruncRegTypes;
1841   std::vector<llvm::Type *> ArgTypes;
1842   std::vector<llvm::Value*> Args;
1843 
1844   // Keep track of inout constraints.
1845   std::string InOutConstraints;
1846   std::vector<llvm::Value*> InOutArgs;
1847   std::vector<llvm::Type*> InOutArgTypes;
1848 
1849   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1850     TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1851 
1852     // Simplify the output constraint.
1853     std::string OutputConstraint(S.getOutputConstraint(i));
1854     OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
1855                                           getTarget());
1856 
1857     const Expr *OutExpr = S.getOutputExpr(i);
1858     OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1859 
1860     OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1861                                               getTarget(), CGM, S,
1862                                               Info.earlyClobber());
1863 
1864     LValue Dest = EmitLValue(OutExpr);
1865     if (!Constraints.empty())
1866       Constraints += ',';
1867 
1868     // If this is a register output, then make the inline asm return it
1869     // by-value.  If this is a memory result, return the value by-reference.
1870     if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
1871       Constraints += "=" + OutputConstraint;
1872       ResultRegQualTys.push_back(OutExpr->getType());
1873       ResultRegDests.push_back(Dest);
1874       ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1875       ResultTruncRegTypes.push_back(ResultRegTypes.back());
1876 
1877       // If this output is tied to an input, and if the input is larger, then
1878       // we need to set the actual result type of the inline asm node to be the
1879       // same as the input type.
1880       if (Info.hasMatchingInput()) {
1881         unsigned InputNo;
1882         for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1883           TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1884           if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1885             break;
1886         }
1887         assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1888 
1889         QualType InputTy = S.getInputExpr(InputNo)->getType();
1890         QualType OutputType = OutExpr->getType();
1891 
1892         uint64_t InputSize = getContext().getTypeSize(InputTy);
1893         if (getContext().getTypeSize(OutputType) < InputSize) {
1894           // Form the asm to return the value as a larger integer or fp type.
1895           ResultRegTypes.back() = ConvertType(InputTy);
1896         }
1897       }
1898       if (llvm::Type* AdjTy =
1899             getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1900                                                  ResultRegTypes.back()))
1901         ResultRegTypes.back() = AdjTy;
1902       else {
1903         CGM.getDiags().Report(S.getAsmLoc(),
1904                               diag::err_asm_invalid_type_in_input)
1905             << OutExpr->getType() << OutputConstraint;
1906       }
1907     } else {
1908       ArgTypes.push_back(Dest.getAddress()->getType());
1909       Args.push_back(Dest.getAddress());
1910       Constraints += "=*";
1911       Constraints += OutputConstraint;
1912     }
1913 
1914     if (Info.isReadWrite()) {
1915       InOutConstraints += ',';
1916 
1917       const Expr *InputExpr = S.getOutputExpr(i);
1918       llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
1919                                             InOutConstraints,
1920                                             InputExpr->getExprLoc());
1921 
1922       if (llvm::Type* AdjTy =
1923           getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1924                                                Arg->getType()))
1925         Arg = Builder.CreateBitCast(Arg, AdjTy);
1926 
1927       if (Info.allowsRegister())
1928         InOutConstraints += llvm::utostr(i);
1929       else
1930         InOutConstraints += OutputConstraint;
1931 
1932       InOutArgTypes.push_back(Arg->getType());
1933       InOutArgs.push_back(Arg);
1934     }
1935   }
1936 
1937   // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
1938   // to the return value slot. Only do this when returning in registers.
1939   if (isa<MSAsmStmt>(&S)) {
1940     const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
1941     if (RetAI.isDirect() || RetAI.isExtend()) {
1942       // Make a fake lvalue for the return value slot.
1943       LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy);
1944       CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
1945           *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
1946           ResultRegDests, AsmString, S.getNumOutputs());
1947       SawAsmBlock = true;
1948     }
1949   }
1950 
1951   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1952     const Expr *InputExpr = S.getInputExpr(i);
1953 
1954     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1955 
1956     if (!Constraints.empty())
1957       Constraints += ',';
1958 
1959     // Simplify the input constraint.
1960     std::string InputConstraint(S.getInputConstraint(i));
1961     InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
1962                                          &OutputConstraintInfos);
1963 
1964     InputConstraint = AddVariableConstraints(
1965         InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
1966         getTarget(), CGM, S, false /* No EarlyClobber */);
1967 
1968     llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
1969 
1970     // If this input argument is tied to a larger output result, extend the
1971     // input to be the same size as the output.  The LLVM backend wants to see
1972     // the input and output of a matching constraint be the same size.  Note
1973     // that GCC does not define what the top bits are here.  We use zext because
1974     // that is usually cheaper, but LLVM IR should really get an anyext someday.
1975     if (Info.hasTiedOperand()) {
1976       unsigned Output = Info.getTiedOperand();
1977       QualType OutputType = S.getOutputExpr(Output)->getType();
1978       QualType InputTy = InputExpr->getType();
1979 
1980       if (getContext().getTypeSize(OutputType) >
1981           getContext().getTypeSize(InputTy)) {
1982         // Use ptrtoint as appropriate so that we can do our extension.
1983         if (isa<llvm::PointerType>(Arg->getType()))
1984           Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
1985         llvm::Type *OutputTy = ConvertType(OutputType);
1986         if (isa<llvm::IntegerType>(OutputTy))
1987           Arg = Builder.CreateZExt(Arg, OutputTy);
1988         else if (isa<llvm::PointerType>(OutputTy))
1989           Arg = Builder.CreateZExt(Arg, IntPtrTy);
1990         else {
1991           assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
1992           Arg = Builder.CreateFPExt(Arg, OutputTy);
1993         }
1994       }
1995     }
1996     if (llvm::Type* AdjTy =
1997               getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
1998                                                    Arg->getType()))
1999       Arg = Builder.CreateBitCast(Arg, AdjTy);
2000     else
2001       CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
2002           << InputExpr->getType() << InputConstraint;
2003 
2004     ArgTypes.push_back(Arg->getType());
2005     Args.push_back(Arg);
2006     Constraints += InputConstraint;
2007   }
2008 
2009   // Append the "input" part of inout constraints last.
2010   for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
2011     ArgTypes.push_back(InOutArgTypes[i]);
2012     Args.push_back(InOutArgs[i]);
2013   }
2014   Constraints += InOutConstraints;
2015 
2016   // Clobbers
2017   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
2018     StringRef Clobber = S.getClobber(i);
2019 
2020     if (Clobber != "memory" && Clobber != "cc")
2021       Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
2022 
2023     if (!Constraints.empty())
2024       Constraints += ',';
2025 
2026     Constraints += "~{";
2027     Constraints += Clobber;
2028     Constraints += '}';
2029   }
2030 
2031   // Add machine specific clobbers
2032   std::string MachineClobbers = getTarget().getClobbers();
2033   if (!MachineClobbers.empty()) {
2034     if (!Constraints.empty())
2035       Constraints += ',';
2036     Constraints += MachineClobbers;
2037   }
2038 
2039   llvm::Type *ResultType;
2040   if (ResultRegTypes.empty())
2041     ResultType = VoidTy;
2042   else if (ResultRegTypes.size() == 1)
2043     ResultType = ResultRegTypes[0];
2044   else
2045     ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
2046 
2047   llvm::FunctionType *FTy =
2048     llvm::FunctionType::get(ResultType, ArgTypes, false);
2049 
2050   bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
2051   llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
2052     llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
2053   llvm::InlineAsm *IA =
2054     llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
2055                          /* IsAlignStack */ false, AsmDialect);
2056   llvm::CallInst *Result = Builder.CreateCall(IA, Args);
2057   Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2058                        llvm::Attribute::NoUnwind);
2059 
2060   // Slap the source location of the inline asm into a !srcloc metadata on the
2061   // call.
2062   if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S)) {
2063     Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
2064                                                    *this));
2065   } else {
2066     // At least put the line number on MS inline asm blobs.
2067     auto Loc = llvm::ConstantInt::get(Int32Ty, S.getAsmLoc().getRawEncoding());
2068     Result->setMetadata("srcloc",
2069                         llvm::MDNode::get(getLLVMContext(),
2070                                           llvm::ConstantAsMetadata::get(Loc)));
2071   }
2072 
2073   // Extract all of the register value results from the asm.
2074   std::vector<llvm::Value*> RegResults;
2075   if (ResultRegTypes.size() == 1) {
2076     RegResults.push_back(Result);
2077   } else {
2078     for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
2079       llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
2080       RegResults.push_back(Tmp);
2081     }
2082   }
2083 
2084   assert(RegResults.size() == ResultRegTypes.size());
2085   assert(RegResults.size() == ResultTruncRegTypes.size());
2086   assert(RegResults.size() == ResultRegDests.size());
2087   for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
2088     llvm::Value *Tmp = RegResults[i];
2089 
2090     // If the result type of the LLVM IR asm doesn't match the result type of
2091     // the expression, do the conversion.
2092     if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
2093       llvm::Type *TruncTy = ResultTruncRegTypes[i];
2094 
2095       // Truncate the integer result to the right size, note that TruncTy can be
2096       // a pointer.
2097       if (TruncTy->isFloatingPointTy())
2098         Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
2099       else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
2100         uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
2101         Tmp = Builder.CreateTrunc(Tmp,
2102                    llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
2103         Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
2104       } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
2105         uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
2106         Tmp = Builder.CreatePtrToInt(Tmp,
2107                    llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
2108         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2109       } else if (TruncTy->isIntegerTy()) {
2110         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2111       } else if (TruncTy->isVectorTy()) {
2112         Tmp = Builder.CreateBitCast(Tmp, TruncTy);
2113       }
2114     }
2115 
2116     EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
2117   }
2118 }
2119 
2120 LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) {
2121   const RecordDecl *RD = S.getCapturedRecordDecl();
2122   QualType RecordTy = getContext().getRecordType(RD);
2123 
2124   // Initialize the captured struct.
2125   LValue SlotLV = MakeNaturalAlignAddrLValue(
2126       CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
2127 
2128   RecordDecl::field_iterator CurField = RD->field_begin();
2129   for (CapturedStmt::capture_init_iterator I = S.capture_init_begin(),
2130                                            E = S.capture_init_end();
2131        I != E; ++I, ++CurField) {
2132     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
2133     if (CurField->hasCapturedVLAType()) {
2134       auto VAT = CurField->getCapturedVLAType();
2135       EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2136     } else {
2137       EmitInitializerForField(*CurField, LV, *I, None);
2138     }
2139   }
2140 
2141   return SlotLV;
2142 }
2143 
2144 /// Generate an outlined function for the body of a CapturedStmt, store any
2145 /// captured variables into the captured struct, and call the outlined function.
2146 llvm::Function *
2147 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
2148   LValue CapStruct = InitCapturedStruct(S);
2149 
2150   // Emit the CapturedDecl
2151   CodeGenFunction CGF(CGM, true);
2152   CGF.CapturedStmtInfo = new CGCapturedStmtInfo(S, K);
2153   llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
2154   delete CGF.CapturedStmtInfo;
2155 
2156   // Emit call to the helper function.
2157   EmitCallOrInvoke(F, CapStruct.getAddress());
2158 
2159   return F;
2160 }
2161 
2162 llvm::Value *
2163 CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
2164   LValue CapStruct = InitCapturedStruct(S);
2165   return CapStruct.getAddress();
2166 }
2167 
2168 /// Creates the outlined function for a CapturedStmt.
2169 llvm::Function *
2170 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
2171   assert(CapturedStmtInfo &&
2172     "CapturedStmtInfo should be set when generating the captured function");
2173   const CapturedDecl *CD = S.getCapturedDecl();
2174   const RecordDecl *RD = S.getCapturedRecordDecl();
2175   SourceLocation Loc = S.getLocStart();
2176   assert(CD->hasBody() && "missing CapturedDecl body");
2177 
2178   // Build the argument list.
2179   ASTContext &Ctx = CGM.getContext();
2180   FunctionArgList Args;
2181   Args.append(CD->param_begin(), CD->param_end());
2182 
2183   // Create the function declaration.
2184   FunctionType::ExtInfo ExtInfo;
2185   const CGFunctionInfo &FuncInfo =
2186       CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
2187                                                     /*IsVariadic=*/false);
2188   llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
2189 
2190   llvm::Function *F =
2191     llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
2192                            CapturedStmtInfo->getHelperName(), &CGM.getModule());
2193   CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
2194   if (CD->isNothrow())
2195     F->addFnAttr(llvm::Attribute::NoUnwind);
2196 
2197   // Generate the function.
2198   StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args,
2199                 CD->getLocation(),
2200                 CD->getBody()->getLocStart());
2201   // Set the context parameter in CapturedStmtInfo.
2202   llvm::Value *DeclPtr = LocalDeclMap[CD->getContextParam()];
2203   assert(DeclPtr && "missing context parameter for CapturedStmt");
2204   CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
2205 
2206   // Initialize variable-length arrays.
2207   LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
2208                                            Ctx.getTagDeclType(RD));
2209   for (auto *FD : RD->fields()) {
2210     if (FD->hasCapturedVLAType()) {
2211       auto *ExprArg = EmitLoadOfLValue(EmitLValueForField(Base, FD),
2212                                        S.getLocStart()).getScalarVal();
2213       auto VAT = FD->getCapturedVLAType();
2214       VLASizeMap[VAT->getSizeExpr()] = ExprArg;
2215     }
2216   }
2217 
2218   // If 'this' is captured, load it into CXXThisValue.
2219   if (CapturedStmtInfo->isCXXThisExprCaptured()) {
2220     FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
2221     LValue ThisLValue = EmitLValueForField(Base, FD);
2222     CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
2223   }
2224 
2225   PGO.assignRegionCounters(CD, F);
2226   CapturedStmtInfo->EmitBody(*this, CD->getBody());
2227   FinishFunction(CD->getBodyRBrace());
2228 
2229   return F;
2230 }
2231