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