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