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/Sema/SemaDiagnostic.h"
20 #include "clang/Basic/PrettyStackTrace.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/Support/CallSite.h"
27 using namespace clang;
28 using namespace CodeGen;
29 
30 //===----------------------------------------------------------------------===//
31 //                              Statement Emission
32 //===----------------------------------------------------------------------===//
33 
34 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
35   if (CGDebugInfo *DI = getDebugInfo()) {
36     SourceLocation Loc;
37     if (isa<DeclStmt>(S))
38       Loc = S->getLocEnd();
39     else
40       Loc = S->getLocStart();
41     DI->EmitLocation(Builder, Loc);
42 
43     LastStopPoint = Loc;
44   }
45 }
46 
47 void CodeGenFunction::EmitStmt(const Stmt *S) {
48   assert(S && "Null statement?");
49 
50   // These statements have their own debug info handling.
51   if (EmitSimpleStmt(S))
52     return;
53 
54   // Check if we are generating unreachable code.
55   if (!HaveInsertPoint()) {
56     // If so, and the statement doesn't contain a label, then we do not need to
57     // generate actual code. This is safe because (1) the current point is
58     // unreachable, so we don't need to execute the code, and (2) we've already
59     // handled the statements which update internal data structures (like the
60     // local variable map) which could be used by subsequent statements.
61     if (!ContainsLabel(S)) {
62       // Verify that any decl statements were handled as simple, they may be in
63       // scope of subsequent reachable statements.
64       assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
65       return;
66     }
67 
68     // Otherwise, make a new block to hold the code.
69     EnsureInsertPoint();
70   }
71 
72   // Generate a stoppoint if we are emitting debug info.
73   EmitStopPoint(S);
74 
75   switch (S->getStmtClass()) {
76   case Stmt::NoStmtClass:
77   case Stmt::CXXCatchStmtClass:
78   case Stmt::SEHExceptStmtClass:
79   case Stmt::SEHFinallyStmtClass:
80   case Stmt::MSDependentExistsStmtClass:
81     llvm_unreachable("invalid statement class to emit generically");
82   case Stmt::NullStmtClass:
83   case Stmt::CompoundStmtClass:
84   case Stmt::DeclStmtClass:
85   case Stmt::LabelStmtClass:
86   case Stmt::AttributedStmtClass:
87   case Stmt::GotoStmtClass:
88   case Stmt::BreakStmtClass:
89   case Stmt::ContinueStmtClass:
90   case Stmt::DefaultStmtClass:
91   case Stmt::CaseStmtClass:
92     llvm_unreachable("should have emitted these statements as simple");
93 
94 #define STMT(Type, Base)
95 #define ABSTRACT_STMT(Op)
96 #define EXPR(Type, Base) \
97   case Stmt::Type##Class:
98 #include "clang/AST/StmtNodes.inc"
99   {
100     // Remember the block we came in on.
101     llvm::BasicBlock *incoming = Builder.GetInsertBlock();
102     assert(incoming && "expression emission must have an insertion point");
103 
104     EmitIgnoredExpr(cast<Expr>(S));
105 
106     llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
107     assert(outgoing && "expression emission cleared block!");
108 
109     // The expression emitters assume (reasonably!) that the insertion
110     // point is always set.  To maintain that, the call-emission code
111     // for noreturn functions has to enter a new block with no
112     // predecessors.  We want to kill that block and mark the current
113     // insertion point unreachable in the common case of a call like
114     // "exit();".  Since expression emission doesn't otherwise create
115     // blocks with no predecessors, we can just test for that.
116     // However, we must be careful not to do this to our incoming
117     // block, because *statement* emission does sometimes create
118     // reachable blocks which will have no predecessors until later in
119     // the function.  This occurs with, e.g., labels that are not
120     // reachable by fallthrough.
121     if (incoming != outgoing && outgoing->use_empty()) {
122       outgoing->eraseFromParent();
123       Builder.ClearInsertionPoint();
124     }
125     break;
126   }
127 
128   case Stmt::IndirectGotoStmtClass:
129     EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
130 
131   case Stmt::IfStmtClass:       EmitIfStmt(cast<IfStmt>(*S));             break;
132   case Stmt::WhileStmtClass:    EmitWhileStmt(cast<WhileStmt>(*S));       break;
133   case Stmt::DoStmtClass:       EmitDoStmt(cast<DoStmt>(*S));             break;
134   case Stmt::ForStmtClass:      EmitForStmt(cast<ForStmt>(*S));           break;
135 
136   case Stmt::ReturnStmtClass:   EmitReturnStmt(cast<ReturnStmt>(*S));     break;
137 
138   case Stmt::SwitchStmtClass:   EmitSwitchStmt(cast<SwitchStmt>(*S));     break;
139   case Stmt::GCCAsmStmtClass:   // Intentional fall-through.
140   case Stmt::MSAsmStmtClass:    EmitAsmStmt(cast<AsmStmt>(*S));           break;
141   case Stmt::CapturedStmtClass:
142     EmitCapturedStmt(cast<CapturedStmt>(*S), CR_Default);
143     break;
144   case Stmt::ObjCAtTryStmtClass:
145     EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
146     break;
147   case Stmt::ObjCAtCatchStmtClass:
148     llvm_unreachable(
149                     "@catch statements should be handled by EmitObjCAtTryStmt");
150   case Stmt::ObjCAtFinallyStmtClass:
151     llvm_unreachable(
152                   "@finally statements should be handled by EmitObjCAtTryStmt");
153   case Stmt::ObjCAtThrowStmtClass:
154     EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
155     break;
156   case Stmt::ObjCAtSynchronizedStmtClass:
157     EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
158     break;
159   case Stmt::ObjCForCollectionStmtClass:
160     EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
161     break;
162   case Stmt::ObjCAutoreleasePoolStmtClass:
163     EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
164     break;
165 
166   case Stmt::CXXTryStmtClass:
167     EmitCXXTryStmt(cast<CXXTryStmt>(*S));
168     break;
169   case Stmt::CXXForRangeStmtClass:
170     EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
171   case Stmt::SEHTryStmtClass:
172     // FIXME Not yet implemented
173     break;
174   }
175 }
176 
177 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
178   switch (S->getStmtClass()) {
179   default: return false;
180   case Stmt::NullStmtClass: break;
181   case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
182   case Stmt::DeclStmtClass:     EmitDeclStmt(cast<DeclStmt>(*S));         break;
183   case Stmt::LabelStmtClass:    EmitLabelStmt(cast<LabelStmt>(*S));       break;
184   case Stmt::AttributedStmtClass:
185                             EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
186   case Stmt::GotoStmtClass:     EmitGotoStmt(cast<GotoStmt>(*S));         break;
187   case Stmt::BreakStmtClass:    EmitBreakStmt(cast<BreakStmt>(*S));       break;
188   case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
189   case Stmt::DefaultStmtClass:  EmitDefaultStmt(cast<DefaultStmt>(*S));   break;
190   case Stmt::CaseStmtClass:     EmitCaseStmt(cast<CaseStmt>(*S));         break;
191   }
192 
193   return true;
194 }
195 
196 /// EmitCompoundStmt - Emit a compound statement {..} node.  If GetLast is true,
197 /// this captures the expression result of the last sub-statement and returns it
198 /// (for use by the statement expression extension).
199 llvm::Value* CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
200                                                AggValueSlot AggSlot) {
201   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
202                              "LLVM IR generation of compound statement ('{}')");
203 
204   // Keep track of the current cleanup stack depth, including debug scopes.
205   LexicalScope Scope(*this, S.getSourceRange());
206 
207   return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
208 }
209 
210 llvm::Value*
211 CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S,
212                                               bool GetLast,
213                                               AggValueSlot AggSlot) {
214 
215   for (CompoundStmt::const_body_iterator I = S.body_begin(),
216        E = S.body_end()-GetLast; I != E; ++I)
217     EmitStmt(*I);
218 
219   llvm::Value *RetAlloca = 0;
220   if (GetLast) {
221     // We have to special case labels here.  They are statements, but when put
222     // at the end of a statement expression, they yield the value of their
223     // subexpression.  Handle this by walking through all labels we encounter,
224     // emitting them before we evaluate the subexpr.
225     const Stmt *LastStmt = S.body_back();
226     while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
227       EmitLabel(LS->getDecl());
228       LastStmt = LS->getSubStmt();
229     }
230 
231     EnsureInsertPoint();
232 
233     QualType ExprTy = cast<Expr>(LastStmt)->getType();
234     if (hasAggregateEvaluationKind(ExprTy)) {
235       EmitAggExpr(cast<Expr>(LastStmt), AggSlot);
236     } else {
237       // We can't return an RValue here because there might be cleanups at
238       // the end of the StmtExpr.  Because of that, we have to emit the result
239       // here into a temporary alloca.
240       RetAlloca = CreateMemTemp(ExprTy);
241       EmitAnyExprToMem(cast<Expr>(LastStmt), RetAlloca, Qualifiers(),
242                        /*IsInit*/false);
243     }
244 
245   }
246 
247   return RetAlloca;
248 }
249 
250 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
251   llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
252 
253   // If there is a cleanup stack, then we it isn't worth trying to
254   // simplify this block (we would need to remove it from the scope map
255   // and cleanup entry).
256   if (!EHStack.empty())
257     return;
258 
259   // Can only simplify direct branches.
260   if (!BI || !BI->isUnconditional())
261     return;
262 
263   // Can only simplify empty blocks.
264   if (BI != BB->begin())
265     return;
266 
267   BB->replaceAllUsesWith(BI->getSuccessor(0));
268   BI->eraseFromParent();
269   BB->eraseFromParent();
270 }
271 
272 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
273   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
274 
275   // Fall out of the current block (if necessary).
276   EmitBranch(BB);
277 
278   if (IsFinished && BB->use_empty()) {
279     delete BB;
280     return;
281   }
282 
283   // Place the block after the current block, if possible, or else at
284   // the end of the function.
285   if (CurBB && CurBB->getParent())
286     CurFn->getBasicBlockList().insertAfter(CurBB, BB);
287   else
288     CurFn->getBasicBlockList().push_back(BB);
289   Builder.SetInsertPoint(BB);
290 }
291 
292 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
293   // Emit a branch from the current block to the target one if this
294   // was a real block.  If this was just a fall-through block after a
295   // terminator, don't emit it.
296   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
297 
298   if (!CurBB || CurBB->getTerminator()) {
299     // If there is no insert point or the previous block is already
300     // terminated, don't touch it.
301   } else {
302     // Otherwise, create a fall-through branch.
303     Builder.CreateBr(Target);
304   }
305 
306   Builder.ClearInsertionPoint();
307 }
308 
309 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
310   bool inserted = false;
311   for (llvm::BasicBlock::use_iterator
312          i = block->use_begin(), e = block->use_end(); i != e; ++i) {
313     if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(*i)) {
314       CurFn->getBasicBlockList().insertAfter(insn->getParent(), block);
315       inserted = true;
316       break;
317     }
318   }
319 
320   if (!inserted)
321     CurFn->getBasicBlockList().push_back(block);
322 
323   Builder.SetInsertPoint(block);
324 }
325 
326 CodeGenFunction::JumpDest
327 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
328   JumpDest &Dest = LabelMap[D];
329   if (Dest.isValid()) return Dest;
330 
331   // Create, but don't insert, the new block.
332   Dest = JumpDest(createBasicBlock(D->getName()),
333                   EHScopeStack::stable_iterator::invalid(),
334                   NextCleanupDestIndex++);
335   return Dest;
336 }
337 
338 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
339   // Add this label to the current lexical scope if we're within any
340   // normal cleanups.  Jumps "in" to this label --- when permitted by
341   // the language --- may need to be routed around such cleanups.
342   if (EHStack.hasNormalCleanups() && CurLexicalScope)
343     CurLexicalScope->addLabel(D);
344 
345   JumpDest &Dest = LabelMap[D];
346 
347   // If we didn't need a forward reference to this label, just go
348   // ahead and create a destination at the current scope.
349   if (!Dest.isValid()) {
350     Dest = getJumpDestInCurrentScope(D->getName());
351 
352   // Otherwise, we need to give this label a target depth and remove
353   // it from the branch-fixups list.
354   } else {
355     assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
356     Dest.setScopeDepth(EHStack.stable_begin());
357     ResolveBranchFixups(Dest.getBlock());
358   }
359 
360   EmitBlock(Dest.getBlock());
361 }
362 
363 /// Change the cleanup scope of the labels in this lexical scope to
364 /// match the scope of the enclosing context.
365 void CodeGenFunction::LexicalScope::rescopeLabels() {
366   assert(!Labels.empty());
367   EHScopeStack::stable_iterator innermostScope
368     = CGF.EHStack.getInnermostNormalCleanup();
369 
370   // Change the scope depth of all the labels.
371   for (SmallVectorImpl<const LabelDecl*>::const_iterator
372          i = Labels.begin(), e = Labels.end(); i != e; ++i) {
373     assert(CGF.LabelMap.count(*i));
374     JumpDest &dest = CGF.LabelMap.find(*i)->second;
375     assert(dest.getScopeDepth().isValid());
376     assert(innermostScope.encloses(dest.getScopeDepth()));
377     dest.setScopeDepth(innermostScope);
378   }
379 
380   // Reparent the labels if the new scope also has cleanups.
381   if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
382     ParentScope->Labels.append(Labels.begin(), Labels.end());
383   }
384 }
385 
386 
387 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
388   EmitLabel(S.getDecl());
389   EmitStmt(S.getSubStmt());
390 }
391 
392 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
393   EmitStmt(S.getSubStmt());
394 }
395 
396 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
397   // If this code is reachable then emit a stop point (if generating
398   // debug info). We have to do this ourselves because we are on the
399   // "simple" statement path.
400   if (HaveInsertPoint())
401     EmitStopPoint(&S);
402 
403   EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
404 }
405 
406 
407 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
408   if (const LabelDecl *Target = S.getConstantTarget()) {
409     EmitBranchThroughCleanup(getJumpDestForLabel(Target));
410     return;
411   }
412 
413   // Ensure that we have an i8* for our PHI node.
414   llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
415                                          Int8PtrTy, "addr");
416   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
417 
418   // Get the basic block for the indirect goto.
419   llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
420 
421   // The first instruction in the block has to be the PHI for the switch dest,
422   // add an entry for this branch.
423   cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
424 
425   EmitBranch(IndGotoBB);
426 }
427 
428 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
429   // C99 6.8.4.1: The first substatement is executed if the expression compares
430   // unequal to 0.  The condition must be a scalar type.
431   RunCleanupsScope ConditionScope(*this);
432 
433   // Also open a debugger-visible lexical scope for the condition.
434   CGDebugInfo *DI = getDebugInfo();
435   if (DI)
436     DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
437 
438   if (S.getConditionVariable())
439     EmitAutoVarDecl(*S.getConditionVariable());
440 
441   // If the condition constant folds and can be elided, try to avoid emitting
442   // the condition and the dead arm of the if/else.
443   bool CondConstant;
444   if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) {
445     // Figure out which block (then or else) is executed.
446     const Stmt *Executed = S.getThen();
447     const Stmt *Skipped  = S.getElse();
448     if (!CondConstant)  // Condition false?
449       std::swap(Executed, Skipped);
450 
451     // If the skipped block has no labels in it, just emit the executed block.
452     // This avoids emitting dead code and simplifies the CFG substantially.
453     if (!ContainsLabel(Skipped)) {
454       if (Executed) {
455         RunCleanupsScope ExecutedScope(*this);
456         EmitStmt(Executed);
457       }
458       if (DI)
459         DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
460       return;
461     }
462   }
463 
464   // Otherwise, the condition did not fold, or we couldn't elide it.  Just emit
465   // the conditional branch.
466   llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
467   llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
468   llvm::BasicBlock *ElseBlock = ContBlock;
469   if (S.getElse())
470     ElseBlock = createBasicBlock("if.else");
471   EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
472 
473   // Emit the 'then' code.
474   EmitBlock(ThenBlock);
475   {
476     RunCleanupsScope ThenScope(*this);
477     EmitStmt(S.getThen());
478   }
479   EmitBranch(ContBlock);
480 
481   // Emit the 'else' code if present.
482   if (const Stmt *Else = S.getElse()) {
483     // There is no need to emit line number for unconditional branch.
484     if (getDebugInfo())
485       Builder.SetCurrentDebugLocation(llvm::DebugLoc());
486     EmitBlock(ElseBlock);
487     {
488       RunCleanupsScope ElseScope(*this);
489       EmitStmt(Else);
490     }
491     // There is no need to emit line number for unconditional branch.
492     if (getDebugInfo())
493       Builder.SetCurrentDebugLocation(llvm::DebugLoc());
494     EmitBranch(ContBlock);
495   }
496 
497   if (DI)
498     DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
499 
500   // Emit the continuation block for code after the if.
501   EmitBlock(ContBlock, true);
502 }
503 
504 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
505   // Emit the header for the loop, which will also become
506   // the continue target.
507   JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
508   EmitBlock(LoopHeader.getBlock());
509 
510   // Create an exit block for when the condition fails, which will
511   // also become the break target.
512   JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
513 
514   // Store the blocks to use for break and continue.
515   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
516 
517   // C++ [stmt.while]p2:
518   //   When the condition of a while statement is a declaration, the
519   //   scope of the variable that is declared extends from its point
520   //   of declaration (3.3.2) to the end of the while statement.
521   //   [...]
522   //   The object created in a condition is destroyed and created
523   //   with each iteration of the loop.
524   RunCleanupsScope ConditionScope(*this);
525 
526   if (S.getConditionVariable())
527     EmitAutoVarDecl(*S.getConditionVariable());
528 
529   // Evaluate the conditional in the while header.  C99 6.8.5.1: The
530   // evaluation of the controlling expression takes place before each
531   // execution of the loop body.
532   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
533 
534   // while(1) is common, avoid extra exit blocks.  Be sure
535   // to correctly handle break/continue though.
536   bool EmitBoolCondBranch = true;
537   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
538     if (C->isOne())
539       EmitBoolCondBranch = false;
540 
541   // As long as the condition is true, go to the loop body.
542   llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
543   if (EmitBoolCondBranch) {
544     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
545     if (ConditionScope.requiresCleanups())
546       ExitBlock = createBasicBlock("while.exit");
547 
548     Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
549 
550     if (ExitBlock != LoopExit.getBlock()) {
551       EmitBlock(ExitBlock);
552       EmitBranchThroughCleanup(LoopExit);
553     }
554   }
555 
556   // Emit the loop body.  We have to emit this in a cleanup scope
557   // because it might be a singleton DeclStmt.
558   {
559     RunCleanupsScope BodyScope(*this);
560     EmitBlock(LoopBody);
561     EmitStmt(S.getBody());
562   }
563 
564   BreakContinueStack.pop_back();
565 
566   // Immediately force cleanup.
567   ConditionScope.ForceCleanup();
568 
569   // Branch to the loop header again.
570   EmitBranch(LoopHeader.getBlock());
571 
572   // Emit the exit block.
573   EmitBlock(LoopExit.getBlock(), true);
574 
575   // The LoopHeader typically is just a branch if we skipped emitting
576   // a branch, try to erase it.
577   if (!EmitBoolCondBranch)
578     SimplifyForwardingBlocks(LoopHeader.getBlock());
579 }
580 
581 void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
582   JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
583   JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
584 
585   // Store the blocks to use for break and continue.
586   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
587 
588   // Emit the body of the loop.
589   llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
590   EmitBlock(LoopBody);
591   {
592     RunCleanupsScope BodyScope(*this);
593     EmitStmt(S.getBody());
594   }
595 
596   BreakContinueStack.pop_back();
597 
598   EmitBlock(LoopCond.getBlock());
599 
600   // C99 6.8.5.2: "The evaluation of the controlling expression takes place
601   // after each execution of the loop body."
602 
603   // Evaluate the conditional in the while header.
604   // C99 6.8.5p2/p4: The first substatement is executed if the expression
605   // compares unequal to 0.  The condition must be a scalar type.
606   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
607 
608   // "do {} while (0)" is common in macros, avoid extra blocks.  Be sure
609   // to correctly handle break/continue though.
610   bool EmitBoolCondBranch = true;
611   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
612     if (C->isZero())
613       EmitBoolCondBranch = false;
614 
615   // As long as the condition is true, iterate the loop.
616   if (EmitBoolCondBranch)
617     Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock());
618 
619   // Emit the exit block.
620   EmitBlock(LoopExit.getBlock());
621 
622   // The DoCond block typically is just a branch if we skipped
623   // emitting a branch, try to erase it.
624   if (!EmitBoolCondBranch)
625     SimplifyForwardingBlocks(LoopCond.getBlock());
626 }
627 
628 void CodeGenFunction::EmitForStmt(const ForStmt &S) {
629   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
630 
631   RunCleanupsScope ForScope(*this);
632 
633   CGDebugInfo *DI = getDebugInfo();
634   if (DI)
635     DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
636 
637   // Evaluate the first part before the loop.
638   if (S.getInit())
639     EmitStmt(S.getInit());
640 
641   // Start the loop with a block that tests the condition.
642   // If there's an increment, the continue scope will be overwritten
643   // later.
644   JumpDest Continue = getJumpDestInCurrentScope("for.cond");
645   llvm::BasicBlock *CondBlock = Continue.getBlock();
646   EmitBlock(CondBlock);
647 
648   // Create a cleanup scope for the condition variable cleanups.
649   RunCleanupsScope ConditionScope(*this);
650 
651   llvm::Value *BoolCondVal = 0;
652   if (S.getCond()) {
653     // If the for statement has a condition scope, emit the local variable
654     // declaration.
655     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
656     if (S.getConditionVariable()) {
657       EmitAutoVarDecl(*S.getConditionVariable());
658     }
659 
660     // If there are any cleanups between here and the loop-exit scope,
661     // create a block to stage a loop exit along.
662     if (ForScope.requiresCleanups())
663       ExitBlock = createBasicBlock("for.cond.cleanup");
664 
665     // As long as the condition is true, iterate the loop.
666     llvm::BasicBlock *ForBody = createBasicBlock("for.body");
667 
668     // C99 6.8.5p2/p4: The first substatement is executed if the expression
669     // compares unequal to 0.  The condition must be a scalar type.
670     BoolCondVal = EvaluateExprAsBool(S.getCond());
671     Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
672 
673     if (ExitBlock != LoopExit.getBlock()) {
674       EmitBlock(ExitBlock);
675       EmitBranchThroughCleanup(LoopExit);
676     }
677 
678     EmitBlock(ForBody);
679   } else {
680     // Treat it as a non-zero constant.  Don't even create a new block for the
681     // body, just fall into it.
682   }
683 
684   // If the for loop doesn't have an increment we can just use the
685   // condition as the continue block.  Otherwise we'll need to create
686   // a block for it (in the current scope, i.e. in the scope of the
687   // condition), and that we will become our continue block.
688   if (S.getInc())
689     Continue = getJumpDestInCurrentScope("for.inc");
690 
691   // Store the blocks to use for break and continue.
692   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
693 
694   {
695     // Create a separate cleanup scope for the body, in case it is not
696     // a compound statement.
697     RunCleanupsScope BodyScope(*this);
698     EmitStmt(S.getBody());
699   }
700 
701   // If there is an increment, emit it next.
702   if (S.getInc()) {
703     EmitBlock(Continue.getBlock());
704     EmitStmt(S.getInc());
705   }
706 
707   BreakContinueStack.pop_back();
708 
709   ConditionScope.ForceCleanup();
710   EmitBranch(CondBlock);
711 
712   ForScope.ForceCleanup();
713 
714   if (DI)
715     DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
716 
717   // Emit the fall-through block.
718   EmitBlock(LoopExit.getBlock(), true);
719 }
720 
721 void CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S) {
722   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
723 
724   RunCleanupsScope ForScope(*this);
725 
726   CGDebugInfo *DI = getDebugInfo();
727   if (DI)
728     DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
729 
730   // Evaluate the first pieces before the loop.
731   EmitStmt(S.getRangeStmt());
732   EmitStmt(S.getBeginEndStmt());
733 
734   // Start the loop with a block that tests the condition.
735   // If there's an increment, the continue scope will be overwritten
736   // later.
737   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
738   EmitBlock(CondBlock);
739 
740   // If there are any cleanups between here and the loop-exit scope,
741   // create a block to stage a loop exit along.
742   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
743   if (ForScope.requiresCleanups())
744     ExitBlock = createBasicBlock("for.cond.cleanup");
745 
746   // The loop body, consisting of the specified body and the loop variable.
747   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
748 
749   // The body is executed if the expression, contextually converted
750   // to bool, is true.
751   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
752   Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
753 
754   if (ExitBlock != LoopExit.getBlock()) {
755     EmitBlock(ExitBlock);
756     EmitBranchThroughCleanup(LoopExit);
757   }
758 
759   EmitBlock(ForBody);
760 
761   // Create a block for the increment. In case of a 'continue', we jump there.
762   JumpDest Continue = getJumpDestInCurrentScope("for.inc");
763 
764   // Store the blocks to use for break and continue.
765   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
766 
767   {
768     // Create a separate cleanup scope for the loop variable and body.
769     RunCleanupsScope BodyScope(*this);
770     EmitStmt(S.getLoopVarStmt());
771     EmitStmt(S.getBody());
772   }
773 
774   // If there is an increment, emit it next.
775   EmitBlock(Continue.getBlock());
776   EmitStmt(S.getInc());
777 
778   BreakContinueStack.pop_back();
779 
780   EmitBranch(CondBlock);
781 
782   ForScope.ForceCleanup();
783 
784   if (DI)
785     DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
786 
787   // Emit the fall-through block.
788   EmitBlock(LoopExit.getBlock(), true);
789 }
790 
791 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
792   if (RV.isScalar()) {
793     Builder.CreateStore(RV.getScalarVal(), ReturnValue);
794   } else if (RV.isAggregate()) {
795     EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
796   } else {
797     EmitStoreOfComplex(RV.getComplexVal(),
798                        MakeNaturalAlignAddrLValue(ReturnValue, Ty),
799                        /*init*/ true);
800   }
801   EmitBranchThroughCleanup(ReturnBlock);
802 }
803 
804 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
805 /// if the function returns void, or may be missing one if the function returns
806 /// non-void.  Fun stuff :).
807 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
808   // Emit the result value, even if unused, to evalute the side effects.
809   const Expr *RV = S.getRetValue();
810 
811   // Treat block literals in a return expression as if they appeared
812   // in their own scope.  This permits a small, easily-implemented
813   // exception to our over-conservative rules about not jumping to
814   // statements following block literals with non-trivial cleanups.
815   RunCleanupsScope cleanupScope(*this);
816   if (const ExprWithCleanups *cleanups =
817         dyn_cast_or_null<ExprWithCleanups>(RV)) {
818     enterFullExpression(cleanups);
819     RV = cleanups->getSubExpr();
820   }
821 
822   // FIXME: Clean this up by using an LValue for ReturnTemp,
823   // EmitStoreThroughLValue, and EmitAnyExpr.
824   if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
825     // Apply the named return value optimization for this return statement,
826     // which means doing nothing: the appropriate result has already been
827     // constructed into the NRVO variable.
828 
829     // If there is an NRVO flag for this variable, set it to 1 into indicate
830     // that the cleanup code should not destroy the variable.
831     if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
832       Builder.CreateStore(Builder.getTrue(), NRVOFlag);
833   } else if (!ReturnValue) {
834     // Make sure not to return anything, but evaluate the expression
835     // for side effects.
836     if (RV)
837       EmitAnyExpr(RV);
838   } else if (RV == 0) {
839     // Do nothing (return value is left uninitialized)
840   } else if (FnRetTy->isReferenceType()) {
841     // If this function returns a reference, take the address of the expression
842     // rather than the value.
843     RValue Result = EmitReferenceBindingToExpr(RV);
844     Builder.CreateStore(Result.getScalarVal(), ReturnValue);
845   } else {
846     switch (getEvaluationKind(RV->getType())) {
847     case TEK_Scalar:
848       Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
849       break;
850     case TEK_Complex:
851       EmitComplexExprIntoLValue(RV,
852                      MakeNaturalAlignAddrLValue(ReturnValue, RV->getType()),
853                                 /*isInit*/ true);
854       break;
855     case TEK_Aggregate: {
856       CharUnits Alignment = getContext().getTypeAlignInChars(RV->getType());
857       EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Alignment,
858                                             Qualifiers(),
859                                             AggValueSlot::IsDestructed,
860                                             AggValueSlot::DoesNotNeedGCBarriers,
861                                             AggValueSlot::IsNotAliased));
862       break;
863     }
864     }
865   }
866 
867   ++NumReturnExprs;
868   if (RV == 0 || RV->isEvaluatable(getContext()))
869     ++NumSimpleReturnExprs;
870 
871   cleanupScope.ForceCleanup();
872   EmitBranchThroughCleanup(ReturnBlock);
873 }
874 
875 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
876   // As long as debug info is modeled with instructions, we have to ensure we
877   // have a place to insert here and write the stop point here.
878   if (HaveInsertPoint())
879     EmitStopPoint(&S);
880 
881   for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
882        I != E; ++I)
883     EmitDecl(**I);
884 }
885 
886 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
887   assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
888 
889   // If this code is reachable then emit a stop point (if generating
890   // debug info). We have to do this ourselves because we are on the
891   // "simple" statement path.
892   if (HaveInsertPoint())
893     EmitStopPoint(&S);
894 
895   JumpDest Block = BreakContinueStack.back().BreakBlock;
896   EmitBranchThroughCleanup(Block);
897 }
898 
899 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
900   assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
901 
902   // If this code is reachable then emit a stop point (if generating
903   // debug info). We have to do this ourselves because we are on the
904   // "simple" statement path.
905   if (HaveInsertPoint())
906     EmitStopPoint(&S);
907 
908   JumpDest Block = BreakContinueStack.back().ContinueBlock;
909   EmitBranchThroughCleanup(Block);
910 }
911 
912 /// EmitCaseStmtRange - If case statement range is not too big then
913 /// add multiple cases to switch instruction, one for each value within
914 /// the range. If range is too big then emit "if" condition check.
915 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
916   assert(S.getRHS() && "Expected RHS value in CaseStmt");
917 
918   llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
919   llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
920 
921   // Emit the code for this case. We do this first to make sure it is
922   // properly chained from our predecessor before generating the
923   // switch machinery to enter this block.
924   EmitBlock(createBasicBlock("sw.bb"));
925   llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
926   EmitStmt(S.getSubStmt());
927 
928   // If range is empty, do nothing.
929   if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
930     return;
931 
932   llvm::APInt Range = RHS - LHS;
933   // FIXME: parameters such as this should not be hardcoded.
934   if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
935     // Range is small enough to add multiple switch instruction cases.
936     for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
937       SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
938       LHS++;
939     }
940     return;
941   }
942 
943   // The range is too big. Emit "if" condition into a new block,
944   // making sure to save and restore the current insertion point.
945   llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
946 
947   // Push this test onto the chain of range checks (which terminates
948   // in the default basic block). The switch's default will be changed
949   // to the top of this chain after switch emission is complete.
950   llvm::BasicBlock *FalseDest = CaseRangeBlock;
951   CaseRangeBlock = createBasicBlock("sw.caserange");
952 
953   CurFn->getBasicBlockList().push_back(CaseRangeBlock);
954   Builder.SetInsertPoint(CaseRangeBlock);
955 
956   // Emit range check.
957   llvm::Value *Diff =
958     Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
959   llvm::Value *Cond =
960     Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
961   Builder.CreateCondBr(Cond, CaseDest, FalseDest);
962 
963   // Restore the appropriate insertion point.
964   if (RestoreBB)
965     Builder.SetInsertPoint(RestoreBB);
966   else
967     Builder.ClearInsertionPoint();
968 }
969 
970 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
971   // If there is no enclosing switch instance that we're aware of, then this
972   // case statement and its block can be elided.  This situation only happens
973   // when we've constant-folded the switch, are emitting the constant case,
974   // and part of the constant case includes another case statement.  For
975   // instance: switch (4) { case 4: do { case 5: } while (1); }
976   if (!SwitchInsn) {
977     EmitStmt(S.getSubStmt());
978     return;
979   }
980 
981   // Handle case ranges.
982   if (S.getRHS()) {
983     EmitCaseStmtRange(S);
984     return;
985   }
986 
987   llvm::ConstantInt *CaseVal =
988     Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
989 
990   // If the body of the case is just a 'break', and if there was no fallthrough,
991   // try to not emit an empty block.
992   if ((CGM.getCodeGenOpts().OptimizationLevel > 0) &&
993       isa<BreakStmt>(S.getSubStmt())) {
994     JumpDest Block = BreakContinueStack.back().BreakBlock;
995 
996     // Only do this optimization if there are no cleanups that need emitting.
997     if (isObviouslyBranchWithoutCleanups(Block)) {
998       SwitchInsn->addCase(CaseVal, Block.getBlock());
999 
1000       // If there was a fallthrough into this case, make sure to redirect it to
1001       // the end of the switch as well.
1002       if (Builder.GetInsertBlock()) {
1003         Builder.CreateBr(Block.getBlock());
1004         Builder.ClearInsertionPoint();
1005       }
1006       return;
1007     }
1008   }
1009 
1010   EmitBlock(createBasicBlock("sw.bb"));
1011   llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
1012   SwitchInsn->addCase(CaseVal, CaseDest);
1013 
1014   // Recursively emitting the statement is acceptable, but is not wonderful for
1015   // code where we have many case statements nested together, i.e.:
1016   //  case 1:
1017   //    case 2:
1018   //      case 3: etc.
1019   // Handling this recursively will create a new block for each case statement
1020   // that falls through to the next case which is IR intensive.  It also causes
1021   // deep recursion which can run into stack depth limitations.  Handle
1022   // sequential non-range case statements specially.
1023   const CaseStmt *CurCase = &S;
1024   const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1025 
1026   // Otherwise, iteratively add consecutive cases to this switch stmt.
1027   while (NextCase && NextCase->getRHS() == 0) {
1028     CurCase = NextCase;
1029     llvm::ConstantInt *CaseVal =
1030       Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1031     SwitchInsn->addCase(CaseVal, CaseDest);
1032     NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1033   }
1034 
1035   // Normal default recursion for non-cases.
1036   EmitStmt(CurCase->getSubStmt());
1037 }
1038 
1039 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
1040   llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1041   assert(DefaultBlock->empty() &&
1042          "EmitDefaultStmt: Default block already defined?");
1043   EmitBlock(DefaultBlock);
1044   EmitStmt(S.getSubStmt());
1045 }
1046 
1047 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
1048 /// constant value that is being switched on, see if we can dead code eliminate
1049 /// the body of the switch to a simple series of statements to emit.  Basically,
1050 /// on a switch (5) we want to find these statements:
1051 ///    case 5:
1052 ///      printf(...);    <--
1053 ///      ++i;            <--
1054 ///      break;
1055 ///
1056 /// and add them to the ResultStmts vector.  If it is unsafe to do this
1057 /// transformation (for example, one of the elided statements contains a label
1058 /// that might be jumped to), return CSFC_Failure.  If we handled it and 'S'
1059 /// should include statements after it (e.g. the printf() line is a substmt of
1060 /// the case) then return CSFC_FallThrough.  If we handled it and found a break
1061 /// statement, then return CSFC_Success.
1062 ///
1063 /// If Case is non-null, then we are looking for the specified case, checking
1064 /// that nothing we jump over contains labels.  If Case is null, then we found
1065 /// the case and are looking for the break.
1066 ///
1067 /// If the recursive walk actually finds our Case, then we set FoundCase to
1068 /// true.
1069 ///
1070 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
1071 static CSFC_Result CollectStatementsForCase(const Stmt *S,
1072                                             const SwitchCase *Case,
1073                                             bool &FoundCase,
1074                               SmallVectorImpl<const Stmt*> &ResultStmts) {
1075   // If this is a null statement, just succeed.
1076   if (S == 0)
1077     return Case ? CSFC_Success : CSFC_FallThrough;
1078 
1079   // If this is the switchcase (case 4: or default) that we're looking for, then
1080   // we're in business.  Just add the substatement.
1081   if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1082     if (S == Case) {
1083       FoundCase = true;
1084       return CollectStatementsForCase(SC->getSubStmt(), 0, FoundCase,
1085                                       ResultStmts);
1086     }
1087 
1088     // Otherwise, this is some other case or default statement, just ignore it.
1089     return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1090                                     ResultStmts);
1091   }
1092 
1093   // If we are in the live part of the code and we found our break statement,
1094   // return a success!
1095   if (Case == 0 && isa<BreakStmt>(S))
1096     return CSFC_Success;
1097 
1098   // If this is a switch statement, then it might contain the SwitchCase, the
1099   // break, or neither.
1100   if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1101     // Handle this as two cases: we might be looking for the SwitchCase (if so
1102     // the skipped statements must be skippable) or we might already have it.
1103     CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1104     if (Case) {
1105       // Keep track of whether we see a skipped declaration.  The code could be
1106       // using the declaration even if it is skipped, so we can't optimize out
1107       // the decl if the kept statements might refer to it.
1108       bool HadSkippedDecl = false;
1109 
1110       // If we're looking for the case, just see if we can skip each of the
1111       // substatements.
1112       for (; Case && I != E; ++I) {
1113         HadSkippedDecl |= isa<DeclStmt>(*I);
1114 
1115         switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1116         case CSFC_Failure: return CSFC_Failure;
1117         case CSFC_Success:
1118           // A successful result means that either 1) that the statement doesn't
1119           // have the case and is skippable, or 2) does contain the case value
1120           // and also contains the break to exit the switch.  In the later case,
1121           // we just verify the rest of the statements are elidable.
1122           if (FoundCase) {
1123             // If we found the case and skipped declarations, we can't do the
1124             // optimization.
1125             if (HadSkippedDecl)
1126               return CSFC_Failure;
1127 
1128             for (++I; I != E; ++I)
1129               if (CodeGenFunction::ContainsLabel(*I, true))
1130                 return CSFC_Failure;
1131             return CSFC_Success;
1132           }
1133           break;
1134         case CSFC_FallThrough:
1135           // If we have a fallthrough condition, then we must have found the
1136           // case started to include statements.  Consider the rest of the
1137           // statements in the compound statement as candidates for inclusion.
1138           assert(FoundCase && "Didn't find case but returned fallthrough?");
1139           // We recursively found Case, so we're not looking for it anymore.
1140           Case = 0;
1141 
1142           // If we found the case and skipped declarations, we can't do the
1143           // optimization.
1144           if (HadSkippedDecl)
1145             return CSFC_Failure;
1146           break;
1147         }
1148       }
1149     }
1150 
1151     // If we have statements in our range, then we know that the statements are
1152     // live and need to be added to the set of statements we're tracking.
1153     for (; I != E; ++I) {
1154       switch (CollectStatementsForCase(*I, 0, FoundCase, ResultStmts)) {
1155       case CSFC_Failure: return CSFC_Failure;
1156       case CSFC_FallThrough:
1157         // A fallthrough result means that the statement was simple and just
1158         // included in ResultStmt, keep adding them afterwards.
1159         break;
1160       case CSFC_Success:
1161         // A successful result means that we found the break statement and
1162         // stopped statement inclusion.  We just ensure that any leftover stmts
1163         // are skippable and return success ourselves.
1164         for (++I; I != E; ++I)
1165           if (CodeGenFunction::ContainsLabel(*I, true))
1166             return CSFC_Failure;
1167         return CSFC_Success;
1168       }
1169     }
1170 
1171     return Case ? CSFC_Success : CSFC_FallThrough;
1172   }
1173 
1174   // Okay, this is some other statement that we don't handle explicitly, like a
1175   // for statement or increment etc.  If we are skipping over this statement,
1176   // just verify it doesn't have labels, which would make it invalid to elide.
1177   if (Case) {
1178     if (CodeGenFunction::ContainsLabel(S, true))
1179       return CSFC_Failure;
1180     return CSFC_Success;
1181   }
1182 
1183   // Otherwise, we want to include this statement.  Everything is cool with that
1184   // so long as it doesn't contain a break out of the switch we're in.
1185   if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1186 
1187   // Otherwise, everything is great.  Include the statement and tell the caller
1188   // that we fall through and include the next statement as well.
1189   ResultStmts.push_back(S);
1190   return CSFC_FallThrough;
1191 }
1192 
1193 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1194 /// then invoke CollectStatementsForCase to find the list of statements to emit
1195 /// for a switch on constant.  See the comment above CollectStatementsForCase
1196 /// for more details.
1197 static bool FindCaseStatementsForValue(const SwitchStmt &S,
1198                                        const llvm::APSInt &ConstantCondValue,
1199                                 SmallVectorImpl<const Stmt*> &ResultStmts,
1200                                        ASTContext &C) {
1201   // First step, find the switch case that is being branched to.  We can do this
1202   // efficiently by scanning the SwitchCase list.
1203   const SwitchCase *Case = S.getSwitchCaseList();
1204   const DefaultStmt *DefaultCase = 0;
1205 
1206   for (; Case; Case = Case->getNextSwitchCase()) {
1207     // It's either a default or case.  Just remember the default statement in
1208     // case we're not jumping to any numbered cases.
1209     if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1210       DefaultCase = DS;
1211       continue;
1212     }
1213 
1214     // Check to see if this case is the one we're looking for.
1215     const CaseStmt *CS = cast<CaseStmt>(Case);
1216     // Don't handle case ranges yet.
1217     if (CS->getRHS()) return false;
1218 
1219     // If we found our case, remember it as 'case'.
1220     if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
1221       break;
1222   }
1223 
1224   // If we didn't find a matching case, we use a default if it exists, or we
1225   // elide the whole switch body!
1226   if (Case == 0) {
1227     // It is safe to elide the body of the switch if it doesn't contain labels
1228     // etc.  If it is safe, return successfully with an empty ResultStmts list.
1229     if (DefaultCase == 0)
1230       return !CodeGenFunction::ContainsLabel(&S);
1231     Case = DefaultCase;
1232   }
1233 
1234   // Ok, we know which case is being jumped to, try to collect all the
1235   // statements that follow it.  This can fail for a variety of reasons.  Also,
1236   // check to see that the recursive walk actually found our case statement.
1237   // Insane cases like this can fail to find it in the recursive walk since we
1238   // don't handle every stmt kind:
1239   // switch (4) {
1240   //   while (1) {
1241   //     case 4: ...
1242   bool FoundCase = false;
1243   return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1244                                   ResultStmts) != CSFC_Failure &&
1245          FoundCase;
1246 }
1247 
1248 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1249   JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1250 
1251   RunCleanupsScope ConditionScope(*this);
1252 
1253   if (S.getConditionVariable())
1254     EmitAutoVarDecl(*S.getConditionVariable());
1255 
1256   // Handle nested switch statements.
1257   llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1258   llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1259 
1260   // See if we can constant fold the condition of the switch and therefore only
1261   // emit the live case statement (if any) of the switch.
1262   llvm::APSInt ConstantCondValue;
1263   if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1264     SmallVector<const Stmt*, 4> CaseStmts;
1265     if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1266                                    getContext())) {
1267       RunCleanupsScope ExecutedScope(*this);
1268 
1269       // At this point, we are no longer "within" a switch instance, so
1270       // we can temporarily enforce this to ensure that any embedded case
1271       // statements are not emitted.
1272       SwitchInsn = 0;
1273 
1274       // Okay, we can dead code eliminate everything except this case.  Emit the
1275       // specified series of statements and we're good.
1276       for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1277         EmitStmt(CaseStmts[i]);
1278 
1279       // Now we want to restore the saved switch instance so that nested
1280       // switches continue to function properly
1281       SwitchInsn = SavedSwitchInsn;
1282 
1283       return;
1284     }
1285   }
1286 
1287   llvm::Value *CondV = EmitScalarExpr(S.getCond());
1288 
1289   // Create basic block to hold stuff that comes after switch
1290   // statement. We also need to create a default block now so that
1291   // explicit case ranges tests can have a place to jump to on
1292   // failure.
1293   llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1294   SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1295   CaseRangeBlock = DefaultBlock;
1296 
1297   // Clear the insertion point to indicate we are in unreachable code.
1298   Builder.ClearInsertionPoint();
1299 
1300   // All break statements jump to NextBlock. If BreakContinueStack is non empty
1301   // then reuse last ContinueBlock.
1302   JumpDest OuterContinue;
1303   if (!BreakContinueStack.empty())
1304     OuterContinue = BreakContinueStack.back().ContinueBlock;
1305 
1306   BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1307 
1308   // Emit switch body.
1309   EmitStmt(S.getBody());
1310 
1311   BreakContinueStack.pop_back();
1312 
1313   // Update the default block in case explicit case range tests have
1314   // been chained on top.
1315   SwitchInsn->setDefaultDest(CaseRangeBlock);
1316 
1317   // If a default was never emitted:
1318   if (!DefaultBlock->getParent()) {
1319     // If we have cleanups, emit the default block so that there's a
1320     // place to jump through the cleanups from.
1321     if (ConditionScope.requiresCleanups()) {
1322       EmitBlock(DefaultBlock);
1323 
1324     // Otherwise, just forward the default block to the switch end.
1325     } else {
1326       DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1327       delete DefaultBlock;
1328     }
1329   }
1330 
1331   ConditionScope.ForceCleanup();
1332 
1333   // Emit continuation.
1334   EmitBlock(SwitchExit.getBlock(), true);
1335 
1336   SwitchInsn = SavedSwitchInsn;
1337   CaseRangeBlock = SavedCRBlock;
1338 }
1339 
1340 static std::string
1341 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1342                  SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
1343   std::string Result;
1344 
1345   while (*Constraint) {
1346     switch (*Constraint) {
1347     default:
1348       Result += Target.convertConstraint(Constraint);
1349       break;
1350     // Ignore these
1351     case '*':
1352     case '?':
1353     case '!':
1354     case '=': // Will see this and the following in mult-alt constraints.
1355     case '+':
1356       break;
1357     case '#': // Ignore the rest of the constraint alternative.
1358       while (Constraint[1] && Constraint[1] != ',')
1359 	Constraint++;
1360       break;
1361     case ',':
1362       Result += "|";
1363       break;
1364     case 'g':
1365       Result += "imr";
1366       break;
1367     case '[': {
1368       assert(OutCons &&
1369              "Must pass output names to constraints with a symbolic name");
1370       unsigned Index;
1371       bool result = Target.resolveSymbolicName(Constraint,
1372                                                &(*OutCons)[0],
1373                                                OutCons->size(), Index);
1374       assert(result && "Could not resolve symbolic name"); (void)result;
1375       Result += llvm::utostr(Index);
1376       break;
1377     }
1378     }
1379 
1380     Constraint++;
1381   }
1382 
1383   return Result;
1384 }
1385 
1386 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1387 /// as using a particular register add that as a constraint that will be used
1388 /// in this asm stmt.
1389 static std::string
1390 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1391                        const TargetInfo &Target, CodeGenModule &CGM,
1392                        const AsmStmt &Stmt) {
1393   const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1394   if (!AsmDeclRef)
1395     return Constraint;
1396   const ValueDecl &Value = *AsmDeclRef->getDecl();
1397   const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1398   if (!Variable)
1399     return Constraint;
1400   if (Variable->getStorageClass() != SC_Register)
1401     return Constraint;
1402   AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1403   if (!Attr)
1404     return Constraint;
1405   StringRef Register = Attr->getLabel();
1406   assert(Target.isValidGCCRegisterName(Register));
1407   // We're using validateOutputConstraint here because we only care if
1408   // this is a register constraint.
1409   TargetInfo::ConstraintInfo Info(Constraint, "");
1410   if (Target.validateOutputConstraint(Info) &&
1411       !Info.allowsRegister()) {
1412     CGM.ErrorUnsupported(&Stmt, "__asm__");
1413     return Constraint;
1414   }
1415   // Canonicalize the register here before returning it.
1416   Register = Target.getNormalizedGCCRegisterName(Register);
1417   return "{" + Register.str() + "}";
1418 }
1419 
1420 llvm::Value*
1421 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
1422                                     LValue InputValue, QualType InputType,
1423                                     std::string &ConstraintStr) {
1424   llvm::Value *Arg;
1425   if (Info.allowsRegister() || !Info.allowsMemory()) {
1426     if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
1427       Arg = EmitLoadOfLValue(InputValue).getScalarVal();
1428     } else {
1429       llvm::Type *Ty = ConvertType(InputType);
1430       uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
1431       if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1432         Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1433         Ty = llvm::PointerType::getUnqual(Ty);
1434 
1435         Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1436                                                        Ty));
1437       } else {
1438         Arg = InputValue.getAddress();
1439         ConstraintStr += '*';
1440       }
1441     }
1442   } else {
1443     Arg = InputValue.getAddress();
1444     ConstraintStr += '*';
1445   }
1446 
1447   return Arg;
1448 }
1449 
1450 llvm::Value* CodeGenFunction::EmitAsmInput(
1451                                          const TargetInfo::ConstraintInfo &Info,
1452                                            const Expr *InputExpr,
1453                                            std::string &ConstraintStr) {
1454   if (Info.allowsRegister() || !Info.allowsMemory())
1455     if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
1456       return EmitScalarExpr(InputExpr);
1457 
1458   InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1459   LValue Dest = EmitLValue(InputExpr);
1460   return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr);
1461 }
1462 
1463 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1464 /// asm call instruction.  The !srcloc MDNode contains a list of constant
1465 /// integers which are the source locations of the start of each line in the
1466 /// asm.
1467 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1468                                       CodeGenFunction &CGF) {
1469   SmallVector<llvm::Value *, 8> Locs;
1470   // Add the location of the first line to the MDNode.
1471   Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1472                                         Str->getLocStart().getRawEncoding()));
1473   StringRef StrVal = Str->getString();
1474   if (!StrVal.empty()) {
1475     const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1476     const LangOptions &LangOpts = CGF.CGM.getLangOpts();
1477 
1478     // Add the location of the start of each subsequent line of the asm to the
1479     // MDNode.
1480     for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
1481       if (StrVal[i] != '\n') continue;
1482       SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
1483                                                       CGF.getTarget());
1484       Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1485                                             LineLoc.getRawEncoding()));
1486     }
1487   }
1488 
1489   return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1490 }
1491 
1492 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1493   // Assemble the final asm string.
1494   std::string AsmString = S.generateAsmString(getContext());
1495 
1496   // Get all the output and input constraints together.
1497   SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1498   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1499 
1500   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1501     StringRef Name;
1502     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1503       Name = GAS->getOutputName(i);
1504     TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
1505     bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
1506     assert(IsValid && "Failed to parse output constraint");
1507     OutputConstraintInfos.push_back(Info);
1508   }
1509 
1510   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1511     StringRef Name;
1512     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1513       Name = GAS->getInputName(i);
1514     TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
1515     bool IsValid =
1516       getTarget().validateInputConstraint(OutputConstraintInfos.data(),
1517                                           S.getNumOutputs(), Info);
1518     assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1519     InputConstraintInfos.push_back(Info);
1520   }
1521 
1522   std::string Constraints;
1523 
1524   std::vector<LValue> ResultRegDests;
1525   std::vector<QualType> ResultRegQualTys;
1526   std::vector<llvm::Type *> ResultRegTypes;
1527   std::vector<llvm::Type *> ResultTruncRegTypes;
1528   std::vector<llvm::Type *> ArgTypes;
1529   std::vector<llvm::Value*> Args;
1530 
1531   // Keep track of inout constraints.
1532   std::string InOutConstraints;
1533   std::vector<llvm::Value*> InOutArgs;
1534   std::vector<llvm::Type*> InOutArgTypes;
1535 
1536   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1537     TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1538 
1539     // Simplify the output constraint.
1540     std::string OutputConstraint(S.getOutputConstraint(i));
1541     OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
1542                                           getTarget());
1543 
1544     const Expr *OutExpr = S.getOutputExpr(i);
1545     OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1546 
1547     OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1548                                               getTarget(), CGM, S);
1549 
1550     LValue Dest = EmitLValue(OutExpr);
1551     if (!Constraints.empty())
1552       Constraints += ',';
1553 
1554     // If this is a register output, then make the inline asm return it
1555     // by-value.  If this is a memory result, return the value by-reference.
1556     if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
1557       Constraints += "=" + OutputConstraint;
1558       ResultRegQualTys.push_back(OutExpr->getType());
1559       ResultRegDests.push_back(Dest);
1560       ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1561       ResultTruncRegTypes.push_back(ResultRegTypes.back());
1562 
1563       // If this output is tied to an input, and if the input is larger, then
1564       // we need to set the actual result type of the inline asm node to be the
1565       // same as the input type.
1566       if (Info.hasMatchingInput()) {
1567         unsigned InputNo;
1568         for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1569           TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1570           if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1571             break;
1572         }
1573         assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1574 
1575         QualType InputTy = S.getInputExpr(InputNo)->getType();
1576         QualType OutputType = OutExpr->getType();
1577 
1578         uint64_t InputSize = getContext().getTypeSize(InputTy);
1579         if (getContext().getTypeSize(OutputType) < InputSize) {
1580           // Form the asm to return the value as a larger integer or fp type.
1581           ResultRegTypes.back() = ConvertType(InputTy);
1582         }
1583       }
1584       if (llvm::Type* AdjTy =
1585             getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1586                                                  ResultRegTypes.back()))
1587         ResultRegTypes.back() = AdjTy;
1588       else {
1589         CGM.getDiags().Report(S.getAsmLoc(),
1590                               diag::err_asm_invalid_type_in_input)
1591             << OutExpr->getType() << OutputConstraint;
1592       }
1593     } else {
1594       ArgTypes.push_back(Dest.getAddress()->getType());
1595       Args.push_back(Dest.getAddress());
1596       Constraints += "=*";
1597       Constraints += OutputConstraint;
1598     }
1599 
1600     if (Info.isReadWrite()) {
1601       InOutConstraints += ',';
1602 
1603       const Expr *InputExpr = S.getOutputExpr(i);
1604       llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
1605                                             InOutConstraints);
1606 
1607       if (llvm::Type* AdjTy =
1608           getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1609                                                Arg->getType()))
1610         Arg = Builder.CreateBitCast(Arg, AdjTy);
1611 
1612       if (Info.allowsRegister())
1613         InOutConstraints += llvm::utostr(i);
1614       else
1615         InOutConstraints += OutputConstraint;
1616 
1617       InOutArgTypes.push_back(Arg->getType());
1618       InOutArgs.push_back(Arg);
1619     }
1620   }
1621 
1622   unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1623 
1624   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1625     const Expr *InputExpr = S.getInputExpr(i);
1626 
1627     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1628 
1629     if (!Constraints.empty())
1630       Constraints += ',';
1631 
1632     // Simplify the input constraint.
1633     std::string InputConstraint(S.getInputConstraint(i));
1634     InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
1635                                          &OutputConstraintInfos);
1636 
1637     InputConstraint =
1638       AddVariableConstraints(InputConstraint,
1639                             *InputExpr->IgnoreParenNoopCasts(getContext()),
1640                             getTarget(), CGM, S);
1641 
1642     llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
1643 
1644     // If this input argument is tied to a larger output result, extend the
1645     // input to be the same size as the output.  The LLVM backend wants to see
1646     // the input and output of a matching constraint be the same size.  Note
1647     // that GCC does not define what the top bits are here.  We use zext because
1648     // that is usually cheaper, but LLVM IR should really get an anyext someday.
1649     if (Info.hasTiedOperand()) {
1650       unsigned Output = Info.getTiedOperand();
1651       QualType OutputType = S.getOutputExpr(Output)->getType();
1652       QualType InputTy = InputExpr->getType();
1653 
1654       if (getContext().getTypeSize(OutputType) >
1655           getContext().getTypeSize(InputTy)) {
1656         // Use ptrtoint as appropriate so that we can do our extension.
1657         if (isa<llvm::PointerType>(Arg->getType()))
1658           Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
1659         llvm::Type *OutputTy = ConvertType(OutputType);
1660         if (isa<llvm::IntegerType>(OutputTy))
1661           Arg = Builder.CreateZExt(Arg, OutputTy);
1662         else if (isa<llvm::PointerType>(OutputTy))
1663           Arg = Builder.CreateZExt(Arg, IntPtrTy);
1664         else {
1665           assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
1666           Arg = Builder.CreateFPExt(Arg, OutputTy);
1667         }
1668       }
1669     }
1670     if (llvm::Type* AdjTy =
1671               getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
1672                                                    Arg->getType()))
1673       Arg = Builder.CreateBitCast(Arg, AdjTy);
1674     else
1675       CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
1676           << InputExpr->getType() << InputConstraint;
1677 
1678     ArgTypes.push_back(Arg->getType());
1679     Args.push_back(Arg);
1680     Constraints += InputConstraint;
1681   }
1682 
1683   // Append the "input" part of inout constraints last.
1684   for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1685     ArgTypes.push_back(InOutArgTypes[i]);
1686     Args.push_back(InOutArgs[i]);
1687   }
1688   Constraints += InOutConstraints;
1689 
1690   // Clobbers
1691   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1692     StringRef Clobber = S.getClobber(i);
1693 
1694     if (Clobber != "memory" && Clobber != "cc")
1695     Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
1696 
1697     if (i != 0 || NumConstraints != 0)
1698       Constraints += ',';
1699 
1700     Constraints += "~{";
1701     Constraints += Clobber;
1702     Constraints += '}';
1703   }
1704 
1705   // Add machine specific clobbers
1706   std::string MachineClobbers = getTarget().getClobbers();
1707   if (!MachineClobbers.empty()) {
1708     if (!Constraints.empty())
1709       Constraints += ',';
1710     Constraints += MachineClobbers;
1711   }
1712 
1713   llvm::Type *ResultType;
1714   if (ResultRegTypes.empty())
1715     ResultType = VoidTy;
1716   else if (ResultRegTypes.size() == 1)
1717     ResultType = ResultRegTypes[0];
1718   else
1719     ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
1720 
1721   llvm::FunctionType *FTy =
1722     llvm::FunctionType::get(ResultType, ArgTypes, false);
1723 
1724   bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
1725   llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
1726     llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
1727   llvm::InlineAsm *IA =
1728     llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
1729                          /* IsAlignStack */ false, AsmDialect);
1730   llvm::CallInst *Result = Builder.CreateCall(IA, Args);
1731   Result->addAttribute(llvm::AttributeSet::FunctionIndex,
1732                        llvm::Attribute::NoUnwind);
1733 
1734   // Slap the source location of the inline asm into a !srcloc metadata on the
1735   // call.  FIXME: Handle metadata for MS-style inline asms.
1736   if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S))
1737     Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
1738                                                    *this));
1739 
1740   // Extract all of the register value results from the asm.
1741   std::vector<llvm::Value*> RegResults;
1742   if (ResultRegTypes.size() == 1) {
1743     RegResults.push_back(Result);
1744   } else {
1745     for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
1746       llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
1747       RegResults.push_back(Tmp);
1748     }
1749   }
1750 
1751   for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1752     llvm::Value *Tmp = RegResults[i];
1753 
1754     // If the result type of the LLVM IR asm doesn't match the result type of
1755     // the expression, do the conversion.
1756     if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1757       llvm::Type *TruncTy = ResultTruncRegTypes[i];
1758 
1759       // Truncate the integer result to the right size, note that TruncTy can be
1760       // a pointer.
1761       if (TruncTy->isFloatingPointTy())
1762         Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
1763       else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
1764         uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
1765         Tmp = Builder.CreateTrunc(Tmp,
1766                    llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
1767         Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
1768       } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1769         uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
1770         Tmp = Builder.CreatePtrToInt(Tmp,
1771                    llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
1772         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1773       } else if (TruncTy->isIntegerTy()) {
1774         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1775       } else if (TruncTy->isVectorTy()) {
1776         Tmp = Builder.CreateBitCast(Tmp, TruncTy);
1777       }
1778     }
1779 
1780     EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
1781   }
1782 }
1783 
1784 static LValue InitCapturedStruct(CodeGenFunction &CGF, const CapturedStmt &S) {
1785   const RecordDecl *RD = S.getCapturedRecordDecl();
1786   QualType RecordTy = CGF.getContext().getRecordType(RD);
1787 
1788   // Initialize the captured struct.
1789   LValue SlotLV = CGF.MakeNaturalAlignAddrLValue(
1790                     CGF.CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
1791 
1792   RecordDecl::field_iterator CurField = RD->field_begin();
1793   for (CapturedStmt::capture_init_iterator I = S.capture_init_begin(),
1794                                            E = S.capture_init_end();
1795        I != E; ++I, ++CurField) {
1796     LValue LV = CGF.EmitLValueForFieldInitialization(SlotLV, *CurField);
1797     CGF.EmitInitializerForField(*CurField, LV, *I, ArrayRef<VarDecl *>());
1798   }
1799 
1800   return SlotLV;
1801 }
1802 
1803 /// Generate an outlined function for the body of a CapturedStmt, store any
1804 /// captured variables into the captured struct, and call the outlined function.
1805 llvm::Function *
1806 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
1807   const CapturedDecl *CD = S.getCapturedDecl();
1808   const RecordDecl *RD = S.getCapturedRecordDecl();
1809   assert(CD->hasBody() && "missing CapturedDecl body");
1810 
1811   LValue CapStruct = InitCapturedStruct(*this, S);
1812 
1813   // Emit the CapturedDecl
1814   CodeGenFunction CGF(CGM, true);
1815   CGF.CapturedStmtInfo = new CGCapturedStmtInfo(S, K);
1816   llvm::Function *F = CGF.GenerateCapturedStmtFunction(CD, RD);
1817   delete CGF.CapturedStmtInfo;
1818 
1819   // Emit call to the helper function.
1820   EmitCallOrInvoke(F, CapStruct.getAddress());
1821 
1822   return F;
1823 }
1824 
1825 /// Creates the outlined function for a CapturedStmt.
1826 llvm::Function *
1827 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedDecl *CD,
1828                                               const RecordDecl *RD) {
1829   assert(CapturedStmtInfo &&
1830     "CapturedStmtInfo should be set when generating the captured function");
1831 
1832   // Check if we should generate debug info for this function.
1833   maybeInitializeDebugInfo();
1834 
1835   // Build the argument list.
1836   ASTContext &Ctx = CGM.getContext();
1837   FunctionArgList Args;
1838   Args.append(CD->param_begin(), CD->param_end());
1839 
1840   // Create the function declaration.
1841   FunctionType::ExtInfo ExtInfo;
1842   const CGFunctionInfo &FuncInfo =
1843     CGM.getTypes().arrangeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
1844                                               /*IsVariadic=*/false);
1845   llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
1846 
1847   llvm::Function *F =
1848     llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
1849                            CapturedStmtInfo->getHelperName(), &CGM.getModule());
1850   CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
1851 
1852   // Generate the function.
1853   StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getBody()->getLocStart());
1854 
1855   // Set the context parameter in CapturedStmtInfo.
1856   llvm::Value *DeclPtr = LocalDeclMap[CD->getContextParam()];
1857   assert(DeclPtr && "missing context parameter for CapturedStmt");
1858   CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
1859 
1860   // If 'this' is captured, load it into CXXThisValue.
1861   if (CapturedStmtInfo->isCXXThisExprCaptured()) {
1862     FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
1863     LValue LV = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
1864                                            Ctx.getTagDeclType(RD));
1865     LValue ThisLValue = EmitLValueForField(LV, FD);
1866 
1867     CXXThisValue = EmitLoadOfLValue(ThisLValue).getScalarVal();
1868   }
1869 
1870   CapturedStmtInfo->EmitBody(*this, CD->getBody());
1871   FinishFunction(CD->getBodyRBrace());
1872 
1873   return F;
1874 }
1875