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