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