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