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