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