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