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