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