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