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