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