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