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