CGStmt.cpp revision b992259f7790d3fb9fc5c2eb7182d7af9d64f9ac
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 "clang/AST/StmtVisitor.h"
18#include "clang/Basic/PrettyStackTrace.h"
19#include "clang/Basic/TargetInfo.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/InlineAsm.h"
22#include "llvm/Intrinsics.h"
23#include "llvm/Target/TargetData.h"
24using namespace clang;
25using namespace CodeGen;
26
27//===----------------------------------------------------------------------===//
28//                              Statement Emission
29//===----------------------------------------------------------------------===//
30
31void CodeGenFunction::EmitStopPoint(const Stmt *S) {
32  if (CGDebugInfo *DI = getDebugInfo()) {
33    DI->setLocation(S->getLocStart());
34    DI->EmitStopPoint(CurFn, Builder);
35  }
36}
37
38void CodeGenFunction::EmitStmt(const Stmt *S) {
39  assert(S && "Null statement?");
40
41  // Check if we can handle this without bothering to generate an
42  // insert point or debug info.
43  if (EmitSimpleStmt(S))
44    return;
45
46  // Check if we are generating unreachable code.
47  if (!HaveInsertPoint()) {
48    // If so, and the statement doesn't contain a label, then we do not need to
49    // generate actual code. This is safe because (1) the current point is
50    // unreachable, so we don't need to execute the code, and (2) we've already
51    // handled the statements which update internal data structures (like the
52    // local variable map) which could be used by subsequent statements.
53    if (!ContainsLabel(S)) {
54      // Verify that any decl statements were handled as simple, they may be in
55      // scope of subsequent reachable statements.
56      assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
57      return;
58    }
59
60    // Otherwise, make a new block to hold the code.
61    EnsureInsertPoint();
62  }
63
64  // Generate a stoppoint if we are emitting debug info.
65  EmitStopPoint(S);
66
67  switch (S->getStmtClass()) {
68  default:
69    // Must be an expression in a stmt context.  Emit the value (to get
70    // side-effects) and ignore the result.
71    if (!isa<Expr>(S))
72      ErrorUnsupported(S, "statement");
73
74    EmitAnyExpr(cast<Expr>(S), 0, false, true);
75
76    // Expression emitters don't handle unreachable blocks yet, so look for one
77    // explicitly here. This handles the common case of a call to a noreturn
78    // function.
79    if (llvm::BasicBlock *CurBB = Builder.GetInsertBlock()) {
80      if (CurBB->empty() && CurBB->use_empty()) {
81        CurBB->eraseFromParent();
82        Builder.ClearInsertionPoint();
83      }
84    }
85    break;
86  case Stmt::IndirectGotoStmtClass:
87    EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
88
89  case Stmt::IfStmtClass:       EmitIfStmt(cast<IfStmt>(*S));             break;
90  case Stmt::WhileStmtClass:    EmitWhileStmt(cast<WhileStmt>(*S));       break;
91  case Stmt::DoStmtClass:       EmitDoStmt(cast<DoStmt>(*S));             break;
92  case Stmt::ForStmtClass:      EmitForStmt(cast<ForStmt>(*S));           break;
93
94  case Stmt::ReturnStmtClass:   EmitReturnStmt(cast<ReturnStmt>(*S));     break;
95
96  case Stmt::SwitchStmtClass:   EmitSwitchStmt(cast<SwitchStmt>(*S));     break;
97  case Stmt::AsmStmtClass:      EmitAsmStmt(cast<AsmStmt>(*S));           break;
98
99  case Stmt::ObjCAtTryStmtClass:
100    EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
101    break;
102  case Stmt::ObjCAtCatchStmtClass:
103    assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
104    break;
105  case Stmt::ObjCAtFinallyStmtClass:
106    assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
107    break;
108  case Stmt::ObjCAtThrowStmtClass:
109    EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
110    break;
111  case Stmt::ObjCAtSynchronizedStmtClass:
112    EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
113    break;
114  case Stmt::ObjCForCollectionStmtClass:
115    EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
116    break;
117
118  case Stmt::CXXTryStmtClass:
119    EmitCXXTryStmt(cast<CXXTryStmt>(*S));
120    break;
121  }
122}
123
124bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
125  switch (S->getStmtClass()) {
126  default: return false;
127  case Stmt::NullStmtClass: break;
128  case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
129  case Stmt::DeclStmtClass:     EmitDeclStmt(cast<DeclStmt>(*S));         break;
130  case Stmt::LabelStmtClass:    EmitLabelStmt(cast<LabelStmt>(*S));       break;
131  case Stmt::GotoStmtClass:     EmitGotoStmt(cast<GotoStmt>(*S));         break;
132  case Stmt::BreakStmtClass:    EmitBreakStmt(cast<BreakStmt>(*S));       break;
133  case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
134  case Stmt::DefaultStmtClass:  EmitDefaultStmt(cast<DefaultStmt>(*S));   break;
135  case Stmt::CaseStmtClass:     EmitCaseStmt(cast<CaseStmt>(*S));         break;
136  }
137
138  return true;
139}
140
141/// EmitCompoundStmt - Emit a compound statement {..} node.  If GetLast is true,
142/// this captures the expression result of the last sub-statement and returns it
143/// (for use by the statement expression extension).
144RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
145                                         llvm::Value *AggLoc, bool isAggVol) {
146  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
147                             "LLVM IR generation of compound statement ('{}')");
148
149  CGDebugInfo *DI = getDebugInfo();
150  if (DI) {
151    DI->setLocation(S.getLBracLoc());
152    DI->EmitRegionStart(CurFn, Builder);
153  }
154
155  // Keep track of the current cleanup stack depth.
156  CleanupScope Scope(*this);
157
158  for (CompoundStmt::const_body_iterator I = S.body_begin(),
159       E = S.body_end()-GetLast; I != E; ++I)
160    EmitStmt(*I);
161
162  if (DI) {
163    DI->setLocation(S.getLBracLoc());
164    DI->EmitRegionEnd(CurFn, Builder);
165  }
166
167  RValue RV;
168  if (!GetLast)
169    RV = RValue::get(0);
170  else {
171    // We have to special case labels here.  They are statements, but when put
172    // at the end of a statement expression, they yield the value of their
173    // subexpression.  Handle this by walking through all labels we encounter,
174    // emitting them before we evaluate the subexpr.
175    const Stmt *LastStmt = S.body_back();
176    while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
177      EmitLabel(*LS);
178      LastStmt = LS->getSubStmt();
179    }
180
181    EnsureInsertPoint();
182
183    RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
184  }
185
186  return RV;
187}
188
189void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
190  llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
191
192  // If there is a cleanup stack, then we it isn't worth trying to
193  // simplify this block (we would need to remove it from the scope map
194  // and cleanup entry).
195  if (!CleanupEntries.empty())
196    return;
197
198  // Can only simplify direct branches.
199  if (!BI || !BI->isUnconditional())
200    return;
201
202  BB->replaceAllUsesWith(BI->getSuccessor(0));
203  BI->eraseFromParent();
204  BB->eraseFromParent();
205}
206
207void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
208  // Fall out of the current block (if necessary).
209  EmitBranch(BB);
210
211  if (IsFinished && BB->use_empty()) {
212    delete BB;
213    return;
214  }
215
216  // If necessary, associate the block with the cleanup stack size.
217  if (!CleanupEntries.empty()) {
218    // Check if the basic block has already been inserted.
219    BlockScopeMap::iterator I = BlockScopes.find(BB);
220    if (I != BlockScopes.end()) {
221      assert(I->second == CleanupEntries.size() - 1);
222    } else {
223      BlockScopes[BB] = CleanupEntries.size() - 1;
224      CleanupEntries.back().Blocks.push_back(BB);
225    }
226  }
227
228  CurFn->getBasicBlockList().push_back(BB);
229  Builder.SetInsertPoint(BB);
230}
231
232void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
233  // Emit a branch from the current block to the target one if this
234  // was a real block.  If this was just a fall-through block after a
235  // terminator, don't emit it.
236  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
237
238  if (!CurBB || CurBB->getTerminator()) {
239    // If there is no insert point or the previous block is already
240    // terminated, don't touch it.
241  } else {
242    // Otherwise, create a fall-through branch.
243    Builder.CreateBr(Target);
244  }
245
246  Builder.ClearInsertionPoint();
247}
248
249void CodeGenFunction::EmitLabel(const LabelStmt &S) {
250  EmitBlock(getBasicBlockForLabel(&S));
251}
252
253
254void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
255  EmitLabel(S);
256  EmitStmt(S.getSubStmt());
257}
258
259void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
260  // If this code is reachable then emit a stop point (if generating
261  // debug info). We have to do this ourselves because we are on the
262  // "simple" statement path.
263  if (HaveInsertPoint())
264    EmitStopPoint(&S);
265
266  EmitBranchThroughCleanup(getBasicBlockForLabel(S.getLabel()));
267}
268
269
270void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
271  // Ensure that we have an i8* for our PHI node.
272  llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
273                                         llvm::Type::getInt8PtrTy(VMContext),
274                                          "addr");
275  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
276
277
278  // Get the basic block for the indirect goto.
279  llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
280
281  // The first instruction in the block has to be the PHI for the switch dest,
282  // add an entry for this branch.
283  cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
284
285  EmitBranch(IndGotoBB);
286}
287
288void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
289  // C99 6.8.4.1: The first substatement is executed if the expression compares
290  // unequal to 0.  The condition must be a scalar type.
291  CleanupScope ConditionScope(*this);
292
293  if (S.getConditionVariable())
294    EmitLocalBlockVarDecl(*S.getConditionVariable());
295
296  // If the condition constant folds and can be elided, try to avoid emitting
297  // the condition and the dead arm of the if/else.
298  if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
299    // Figure out which block (then or else) is executed.
300    const Stmt *Executed = S.getThen(), *Skipped  = S.getElse();
301    if (Cond == -1)  // Condition false?
302      std::swap(Executed, Skipped);
303
304    // If the skipped block has no labels in it, just emit the executed block.
305    // This avoids emitting dead code and simplifies the CFG substantially.
306    if (!ContainsLabel(Skipped)) {
307      if (Executed) {
308        CleanupScope ExecutedScope(*this);
309        EmitStmt(Executed);
310      }
311      return;
312    }
313  }
314
315  // Otherwise, the condition did not fold, or we couldn't elide it.  Just emit
316  // the conditional branch.
317  llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
318  llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
319  llvm::BasicBlock *ElseBlock = ContBlock;
320  if (S.getElse())
321    ElseBlock = createBasicBlock("if.else");
322  EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
323
324  // Emit the 'then' code.
325  EmitBlock(ThenBlock);
326  {
327    CleanupScope ThenScope(*this);
328    EmitStmt(S.getThen());
329  }
330  EmitBranch(ContBlock);
331
332  // Emit the 'else' code if present.
333  if (const Stmt *Else = S.getElse()) {
334    EmitBlock(ElseBlock);
335    {
336      CleanupScope ElseScope(*this);
337      EmitStmt(Else);
338    }
339    EmitBranch(ContBlock);
340  }
341
342  // Emit the continuation block for code after the if.
343  EmitBlock(ContBlock, true);
344}
345
346void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
347  // Emit the header for the loop, insert it, which will create an uncond br to
348  // it.
349  llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
350  EmitBlock(LoopHeader);
351
352  // Create an exit block for when the condition fails, create a block for the
353  // body of the loop.
354  llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
355  llvm::BasicBlock *LoopBody  = createBasicBlock("while.body");
356  llvm::BasicBlock *CleanupBlock = 0;
357  llvm::BasicBlock *EffectiveExitBlock = ExitBlock;
358
359  // Store the blocks to use for break and continue.
360  BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
361
362  // C++ [stmt.while]p2:
363  //   When the condition of a while statement is a declaration, the
364  //   scope of the variable that is declared extends from its point
365  //   of declaration (3.3.2) to the end of the while statement.
366  //   [...]
367  //   The object created in a condition is destroyed and created
368  //   with each iteration of the loop.
369  CleanupScope ConditionScope(*this);
370
371  if (S.getConditionVariable()) {
372    EmitLocalBlockVarDecl(*S.getConditionVariable());
373
374    // If this condition variable requires cleanups, create a basic
375    // block to handle those cleanups.
376    if (ConditionScope.requiresCleanups()) {
377      CleanupBlock = createBasicBlock("while.cleanup");
378      EffectiveExitBlock = CleanupBlock;
379    }
380  }
381
382  // Evaluate the conditional in the while header.  C99 6.8.5.1: The
383  // evaluation of the controlling expression takes place before each
384  // execution of the loop body.
385  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
386
387  // while(1) is common, avoid extra exit blocks.  Be sure
388  // to correctly handle break/continue though.
389  bool EmitBoolCondBranch = true;
390  if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
391    if (C->isOne())
392      EmitBoolCondBranch = false;
393
394  // As long as the condition is true, go to the loop body.
395  if (EmitBoolCondBranch)
396    Builder.CreateCondBr(BoolCondVal, LoopBody, EffectiveExitBlock);
397
398  // Emit the loop body.
399  {
400    CleanupScope BodyScope(*this);
401    EmitBlock(LoopBody);
402    EmitStmt(S.getBody());
403  }
404
405  BreakContinueStack.pop_back();
406
407  if (CleanupBlock) {
408    // If we have a cleanup block, jump there to perform cleanups
409    // before looping.
410    EmitBranch(CleanupBlock);
411
412    // Emit the cleanup block, performing cleanups for the condition
413    // and then jumping to either the loop header or the exit block.
414    EmitBlock(CleanupBlock);
415    ConditionScope.ForceCleanup();
416    Builder.CreateCondBr(BoolCondVal, LoopHeader, ExitBlock);
417  } else {
418    // Cycle to the condition.
419    EmitBranch(LoopHeader);
420  }
421
422  // Emit the exit block.
423  EmitBlock(ExitBlock, true);
424
425
426  // The LoopHeader typically is just a branch if we skipped emitting
427  // a branch, try to erase it.
428  if (!EmitBoolCondBranch && !CleanupBlock)
429    SimplifyForwardingBlocks(LoopHeader);
430}
431
432void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
433  // Emit the body for the loop, insert it, which will create an uncond br to
434  // it.
435  llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
436  llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
437  EmitBlock(LoopBody);
438
439  llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
440
441  // Store the blocks to use for break and continue.
442  BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
443
444  // Emit the body of the loop into the block.
445  EmitStmt(S.getBody());
446
447  BreakContinueStack.pop_back();
448
449  EmitBlock(DoCond);
450
451  // C99 6.8.5.2: "The evaluation of the controlling expression takes place
452  // after each execution of the loop body."
453
454  // Evaluate the conditional in the while header.
455  // C99 6.8.5p2/p4: The first substatement is executed if the expression
456  // compares unequal to 0.  The condition must be a scalar type.
457  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
458
459  // "do {} while (0)" is common in macros, avoid extra blocks.  Be sure
460  // to correctly handle break/continue though.
461  bool EmitBoolCondBranch = true;
462  if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
463    if (C->isZero())
464      EmitBoolCondBranch = false;
465
466  // As long as the condition is true, iterate the loop.
467  if (EmitBoolCondBranch)
468    Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
469
470  // Emit the exit block.
471  EmitBlock(AfterDo);
472
473  // The DoCond block typically is just a branch if we skipped
474  // emitting a branch, try to erase it.
475  if (!EmitBoolCondBranch)
476    SimplifyForwardingBlocks(DoCond);
477}
478
479void CodeGenFunction::EmitForStmt(const ForStmt &S) {
480  // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
481  // which contains a continue/break?
482  CleanupScope ForScope(*this);
483
484  // Evaluate the first part before the loop.
485  if (S.getInit())
486    EmitStmt(S.getInit());
487
488  // Start the loop with a block that tests the condition.
489  llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
490  llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
491  llvm::BasicBlock *IncBlock = 0;
492  llvm::BasicBlock *CondCleanup = 0;
493  llvm::BasicBlock *EffectiveExitBlock = AfterFor;
494  EmitBlock(CondBlock);
495
496  // Create a cleanup scope for the condition variable cleanups.
497  CleanupScope ConditionScope(*this);
498
499  llvm::Value *BoolCondVal = 0;
500  if (S.getCond()) {
501    // If the for statement has a condition scope, emit the local variable
502    // declaration.
503    if (S.getConditionVariable()) {
504      EmitLocalBlockVarDecl(*S.getConditionVariable());
505
506      if (ConditionScope.requiresCleanups()) {
507        CondCleanup = createBasicBlock("for.cond.cleanup");
508        EffectiveExitBlock = CondCleanup;
509      }
510    }
511
512    // As long as the condition is true, iterate the loop.
513    llvm::BasicBlock *ForBody = createBasicBlock("for.body");
514
515    // C99 6.8.5p2/p4: The first substatement is executed if the expression
516    // compares unequal to 0.  The condition must be a scalar type.
517    BoolCondVal = EvaluateExprAsBool(S.getCond());
518    Builder.CreateCondBr(BoolCondVal, ForBody, EffectiveExitBlock);
519
520    EmitBlock(ForBody);
521  } else {
522    // Treat it as a non-zero constant.  Don't even create a new block for the
523    // body, just fall into it.
524  }
525
526  // If the for loop doesn't have an increment we can just use the
527  // condition as the continue block.
528  llvm::BasicBlock *ContinueBlock;
529  if (S.getInc())
530    ContinueBlock = IncBlock = createBasicBlock("for.inc");
531  else
532    ContinueBlock = CondBlock;
533
534  // Store the blocks to use for break and continue.
535  BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
536
537  // If the condition is true, execute the body of the for stmt.
538  CGDebugInfo *DI = getDebugInfo();
539  if (DI) {
540    DI->setLocation(S.getSourceRange().getBegin());
541    DI->EmitRegionStart(CurFn, Builder);
542  }
543
544  {
545    // Create a separate cleanup scope for the body, in case it is not
546    // a compound statement.
547    CleanupScope BodyScope(*this);
548    EmitStmt(S.getBody());
549  }
550
551  BreakContinueStack.pop_back();
552
553  // If there is an increment, emit it next.
554  if (S.getInc()) {
555    EmitBlock(IncBlock);
556    EmitStmt(S.getInc());
557  }
558
559  // Finally, branch back up to the condition for the next iteration.
560  if (CondCleanup) {
561    // Branch to the cleanup block.
562    EmitBranch(CondCleanup);
563
564    // Emit the cleanup block, which branches back to the loop body or
565    // outside of the for statement once it is done.
566    EmitBlock(CondCleanup);
567    ConditionScope.ForceCleanup();
568    Builder.CreateCondBr(BoolCondVal, CondBlock, AfterFor);
569  } else
570    EmitBranch(CondBlock);
571  if (DI) {
572    DI->setLocation(S.getSourceRange().getEnd());
573    DI->EmitRegionEnd(CurFn, Builder);
574  }
575
576  // Emit the fall-through block.
577  EmitBlock(AfterFor, true);
578}
579
580void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
581  if (RV.isScalar()) {
582    Builder.CreateStore(RV.getScalarVal(), ReturnValue);
583  } else if (RV.isAggregate()) {
584    EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
585  } else {
586    StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
587  }
588  EmitBranchThroughCleanup(ReturnBlock);
589}
590
591/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
592/// if the function returns void, or may be missing one if the function returns
593/// non-void.  Fun stuff :).
594void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
595  // Emit the result value, even if unused, to evalute the side effects.
596  const Expr *RV = S.getRetValue();
597
598  // FIXME: Clean this up by using an LValue for ReturnTemp,
599  // EmitStoreThroughLValue, and EmitAnyExpr.
600  if (!ReturnValue) {
601    // Make sure not to return anything, but evaluate the expression
602    // for side effects.
603    if (RV)
604      EmitAnyExpr(RV);
605  } else if (RV == 0) {
606    // Do nothing (return value is left uninitialized)
607  } else if (FnRetTy->isReferenceType()) {
608    // If this function returns a reference, take the address of the expression
609    // rather than the value.
610    Builder.CreateStore(EmitLValue(RV).getAddress(), ReturnValue);
611  } else if (!hasAggregateLLVMType(RV->getType())) {
612    Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
613  } else if (RV->getType()->isAnyComplexType()) {
614    EmitComplexExprIntoAddr(RV, ReturnValue, false);
615  } else {
616    EmitAggExpr(RV, ReturnValue, false);
617  }
618
619  EmitBranchThroughCleanup(ReturnBlock);
620}
621
622void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
623  // As long as debug info is modeled with instructions, we have to ensure we
624  // have a place to insert here and write the stop point here.
625  if (getDebugInfo()) {
626    EnsureInsertPoint();
627    EmitStopPoint(&S);
628  }
629
630  for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
631       I != E; ++I)
632    EmitDecl(**I);
633}
634
635void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
636  assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
637
638  // If this code is reachable then emit a stop point (if generating
639  // debug info). We have to do this ourselves because we are on the
640  // "simple" statement path.
641  if (HaveInsertPoint())
642    EmitStopPoint(&S);
643
644  llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
645  EmitBranchThroughCleanup(Block);
646}
647
648void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
649  assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
650
651  // If this code is reachable then emit a stop point (if generating
652  // debug info). We have to do this ourselves because we are on the
653  // "simple" statement path.
654  if (HaveInsertPoint())
655    EmitStopPoint(&S);
656
657  llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
658  EmitBranchThroughCleanup(Block);
659}
660
661/// EmitCaseStmtRange - If case statement range is not too big then
662/// add multiple cases to switch instruction, one for each value within
663/// the range. If range is too big then emit "if" condition check.
664void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
665  assert(S.getRHS() && "Expected RHS value in CaseStmt");
666
667  llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
668  llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
669
670  // Emit the code for this case. We do this first to make sure it is
671  // properly chained from our predecessor before generating the
672  // switch machinery to enter this block.
673  EmitBlock(createBasicBlock("sw.bb"));
674  llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
675  EmitStmt(S.getSubStmt());
676
677  // If range is empty, do nothing.
678  if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
679    return;
680
681  llvm::APInt Range = RHS - LHS;
682  // FIXME: parameters such as this should not be hardcoded.
683  if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
684    // Range is small enough to add multiple switch instruction cases.
685    for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
686      SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, LHS), CaseDest);
687      LHS++;
688    }
689    return;
690  }
691
692  // The range is too big. Emit "if" condition into a new block,
693  // making sure to save and restore the current insertion point.
694  llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
695
696  // Push this test onto the chain of range checks (which terminates
697  // in the default basic block). The switch's default will be changed
698  // to the top of this chain after switch emission is complete.
699  llvm::BasicBlock *FalseDest = CaseRangeBlock;
700  CaseRangeBlock = createBasicBlock("sw.caserange");
701
702  CurFn->getBasicBlockList().push_back(CaseRangeBlock);
703  Builder.SetInsertPoint(CaseRangeBlock);
704
705  // Emit range check.
706  llvm::Value *Diff =
707    Builder.CreateSub(SwitchInsn->getCondition(),
708                      llvm::ConstantInt::get(VMContext, LHS),  "tmp");
709  llvm::Value *Cond =
710    Builder.CreateICmpULE(Diff,
711                          llvm::ConstantInt::get(VMContext, Range), "tmp");
712  Builder.CreateCondBr(Cond, CaseDest, FalseDest);
713
714  // Restore the appropriate insertion point.
715  if (RestoreBB)
716    Builder.SetInsertPoint(RestoreBB);
717  else
718    Builder.ClearInsertionPoint();
719}
720
721void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
722  if (S.getRHS()) {
723    EmitCaseStmtRange(S);
724    return;
725  }
726
727  EmitBlock(createBasicBlock("sw.bb"));
728  llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
729  llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
730  SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
731
732  // Recursively emitting the statement is acceptable, but is not wonderful for
733  // code where we have many case statements nested together, i.e.:
734  //  case 1:
735  //    case 2:
736  //      case 3: etc.
737  // Handling this recursively will create a new block for each case statement
738  // that falls through to the next case which is IR intensive.  It also causes
739  // deep recursion which can run into stack depth limitations.  Handle
740  // sequential non-range case statements specially.
741  const CaseStmt *CurCase = &S;
742  const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
743
744  // Otherwise, iteratively add consequtive cases to this switch stmt.
745  while (NextCase && NextCase->getRHS() == 0) {
746    CurCase = NextCase;
747    CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
748    SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
749
750    NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
751  }
752
753  // Normal default recursion for non-cases.
754  EmitStmt(CurCase->getSubStmt());
755}
756
757void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
758  llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
759  assert(DefaultBlock->empty() &&
760         "EmitDefaultStmt: Default block already defined?");
761  EmitBlock(DefaultBlock);
762  EmitStmt(S.getSubStmt());
763}
764
765void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
766  CleanupScope ConditionScope(*this);
767
768  if (S.getConditionVariable())
769    EmitLocalBlockVarDecl(*S.getConditionVariable());
770
771  llvm::Value *CondV = EmitScalarExpr(S.getCond());
772
773  // Handle nested switch statements.
774  llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
775  llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
776
777  // Create basic block to hold stuff that comes after switch
778  // statement. We also need to create a default block now so that
779  // explicit case ranges tests can have a place to jump to on
780  // failure.
781  llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
782  llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
783  SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
784  CaseRangeBlock = DefaultBlock;
785
786  // Clear the insertion point to indicate we are in unreachable code.
787  Builder.ClearInsertionPoint();
788
789  // All break statements jump to NextBlock. If BreakContinueStack is non empty
790  // then reuse last ContinueBlock.
791  llvm::BasicBlock *ContinueBlock = 0;
792  if (!BreakContinueStack.empty())
793    ContinueBlock = BreakContinueStack.back().ContinueBlock;
794
795  // Ensure any vlas created between there and here, are undone
796  BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
797
798  // Emit switch body.
799  EmitStmt(S.getBody());
800
801  BreakContinueStack.pop_back();
802
803  // Update the default block in case explicit case range tests have
804  // been chained on top.
805  SwitchInsn->setSuccessor(0, CaseRangeBlock);
806
807  // If a default was never emitted then reroute any jumps to it and
808  // discard.
809  if (!DefaultBlock->getParent()) {
810    DefaultBlock->replaceAllUsesWith(NextBlock);
811    delete DefaultBlock;
812  }
813
814  // Emit continuation.
815  EmitBlock(NextBlock, true);
816
817  SwitchInsn = SavedSwitchInsn;
818  CaseRangeBlock = SavedCRBlock;
819}
820
821static std::string
822SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
823                 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
824  std::string Result;
825
826  while (*Constraint) {
827    switch (*Constraint) {
828    default:
829      Result += Target.convertConstraint(*Constraint);
830      break;
831    // Ignore these
832    case '*':
833    case '?':
834    case '!':
835      break;
836    case 'g':
837      Result += "imr";
838      break;
839    case '[': {
840      assert(OutCons &&
841             "Must pass output names to constraints with a symbolic name");
842      unsigned Index;
843      bool result = Target.resolveSymbolicName(Constraint,
844                                               &(*OutCons)[0],
845                                               OutCons->size(), Index);
846      assert(result && "Could not resolve symbolic name"); result=result;
847      Result += llvm::utostr(Index);
848      break;
849    }
850    }
851
852    Constraint++;
853  }
854
855  return Result;
856}
857
858llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
859                                         const TargetInfo::ConstraintInfo &Info,
860                                           const Expr *InputExpr,
861                                           std::string &ConstraintStr) {
862  llvm::Value *Arg;
863  if (Info.allowsRegister() || !Info.allowsMemory()) {
864    if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType())) {
865      Arg = EmitScalarExpr(InputExpr);
866    } else {
867      InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
868      LValue Dest = EmitLValue(InputExpr);
869
870      const llvm::Type *Ty = ConvertType(InputExpr->getType());
871      uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
872      if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
873        Ty = llvm::IntegerType::get(VMContext, Size);
874        Ty = llvm::PointerType::getUnqual(Ty);
875
876        Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
877      } else {
878        Arg = Dest.getAddress();
879        ConstraintStr += '*';
880      }
881    }
882  } else {
883    InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
884    LValue Dest = EmitLValue(InputExpr);
885    Arg = Dest.getAddress();
886    ConstraintStr += '*';
887  }
888
889  return Arg;
890}
891
892void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
893  // Analyze the asm string to decompose it into its pieces.  We know that Sema
894  // has already done this, so it is guaranteed to be successful.
895  llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
896  unsigned DiagOffs;
897  S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
898
899  // Assemble the pieces into the final asm string.
900  std::string AsmString;
901  for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
902    if (Pieces[i].isString())
903      AsmString += Pieces[i].getString();
904    else if (Pieces[i].getModifier() == '\0')
905      AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
906    else
907      AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
908                   Pieces[i].getModifier() + '}';
909  }
910
911  // Get all the output and input constraints together.
912  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
913  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
914
915  for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
916    TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
917                                    S.getOutputName(i));
918    bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
919    assert(IsValid && "Failed to parse output constraint");
920    OutputConstraintInfos.push_back(Info);
921  }
922
923  for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
924    TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
925                                    S.getInputName(i));
926    bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
927                                                  S.getNumOutputs(), Info);
928    assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
929    InputConstraintInfos.push_back(Info);
930  }
931
932  std::string Constraints;
933
934  std::vector<LValue> ResultRegDests;
935  std::vector<QualType> ResultRegQualTys;
936  std::vector<const llvm::Type *> ResultRegTypes;
937  std::vector<const llvm::Type *> ResultTruncRegTypes;
938  std::vector<const llvm::Type*> ArgTypes;
939  std::vector<llvm::Value*> Args;
940
941  // Keep track of inout constraints.
942  std::string InOutConstraints;
943  std::vector<llvm::Value*> InOutArgs;
944  std::vector<const llvm::Type*> InOutArgTypes;
945
946  for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
947    TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
948
949    // Simplify the output constraint.
950    std::string OutputConstraint(S.getOutputConstraint(i));
951    OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
952
953    const Expr *OutExpr = S.getOutputExpr(i);
954    OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
955
956    LValue Dest = EmitLValue(OutExpr);
957    if (!Constraints.empty())
958      Constraints += ',';
959
960    // If this is a register output, then make the inline asm return it
961    // by-value.  If this is a memory result, return the value by-reference.
962    if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
963      Constraints += "=" + OutputConstraint;
964      ResultRegQualTys.push_back(OutExpr->getType());
965      ResultRegDests.push_back(Dest);
966      ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
967      ResultTruncRegTypes.push_back(ResultRegTypes.back());
968
969      // If this output is tied to an input, and if the input is larger, then
970      // we need to set the actual result type of the inline asm node to be the
971      // same as the input type.
972      if (Info.hasMatchingInput()) {
973        unsigned InputNo;
974        for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
975          TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
976          if (Input.hasTiedOperand() &&
977              Input.getTiedOperand() == i)
978            break;
979        }
980        assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
981
982        QualType InputTy = S.getInputExpr(InputNo)->getType();
983        QualType OutputTy = OutExpr->getType();
984
985        uint64_t InputSize = getContext().getTypeSize(InputTy);
986        if (getContext().getTypeSize(OutputTy) < InputSize) {
987          // Form the asm to return the value as a larger integer type.
988          ResultRegTypes.back() = llvm::IntegerType::get(VMContext, (unsigned)InputSize);
989        }
990      }
991    } else {
992      ArgTypes.push_back(Dest.getAddress()->getType());
993      Args.push_back(Dest.getAddress());
994      Constraints += "=*";
995      Constraints += OutputConstraint;
996    }
997
998    if (Info.isReadWrite()) {
999      InOutConstraints += ',';
1000
1001      const Expr *InputExpr = S.getOutputExpr(i);
1002      llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
1003
1004      if (Info.allowsRegister())
1005        InOutConstraints += llvm::utostr(i);
1006      else
1007        InOutConstraints += OutputConstraint;
1008
1009      InOutArgTypes.push_back(Arg->getType());
1010      InOutArgs.push_back(Arg);
1011    }
1012  }
1013
1014  unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1015
1016  for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1017    const Expr *InputExpr = S.getInputExpr(i);
1018
1019    TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1020
1021    if (!Constraints.empty())
1022      Constraints += ',';
1023
1024    // Simplify the input constraint.
1025    std::string InputConstraint(S.getInputConstraint(i));
1026    InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
1027                                         &OutputConstraintInfos);
1028
1029    llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
1030
1031    // If this input argument is tied to a larger output result, extend the
1032    // input to be the same size as the output.  The LLVM backend wants to see
1033    // the input and output of a matching constraint be the same size.  Note
1034    // that GCC does not define what the top bits are here.  We use zext because
1035    // that is usually cheaper, but LLVM IR should really get an anyext someday.
1036    if (Info.hasTiedOperand()) {
1037      unsigned Output = Info.getTiedOperand();
1038      QualType OutputTy = S.getOutputExpr(Output)->getType();
1039      QualType InputTy = InputExpr->getType();
1040
1041      if (getContext().getTypeSize(OutputTy) >
1042          getContext().getTypeSize(InputTy)) {
1043        // Use ptrtoint as appropriate so that we can do our extension.
1044        if (isa<llvm::PointerType>(Arg->getType()))
1045          Arg = Builder.CreatePtrToInt(Arg,
1046                                      llvm::IntegerType::get(VMContext, LLVMPointerWidth));
1047        unsigned OutputSize = (unsigned)getContext().getTypeSize(OutputTy);
1048        Arg = Builder.CreateZExt(Arg, llvm::IntegerType::get(VMContext, OutputSize));
1049      }
1050    }
1051
1052
1053    ArgTypes.push_back(Arg->getType());
1054    Args.push_back(Arg);
1055    Constraints += InputConstraint;
1056  }
1057
1058  // Append the "input" part of inout constraints last.
1059  for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1060    ArgTypes.push_back(InOutArgTypes[i]);
1061    Args.push_back(InOutArgs[i]);
1062  }
1063  Constraints += InOutConstraints;
1064
1065  // Clobbers
1066  for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1067    llvm::StringRef Clobber = S.getClobber(i)->getString();
1068
1069    Clobber = Target.getNormalizedGCCRegisterName(Clobber);
1070
1071    if (i != 0 || NumConstraints != 0)
1072      Constraints += ',';
1073
1074    Constraints += "~{";
1075    Constraints += Clobber;
1076    Constraints += '}';
1077  }
1078
1079  // Add machine specific clobbers
1080  std::string MachineClobbers = Target.getClobbers();
1081  if (!MachineClobbers.empty()) {
1082    if (!Constraints.empty())
1083      Constraints += ',';
1084    Constraints += MachineClobbers;
1085  }
1086
1087  const llvm::Type *ResultType;
1088  if (ResultRegTypes.empty())
1089    ResultType = llvm::Type::getVoidTy(VMContext);
1090  else if (ResultRegTypes.size() == 1)
1091    ResultType = ResultRegTypes[0];
1092  else
1093    ResultType = llvm::StructType::get(VMContext, ResultRegTypes);
1094
1095  const llvm::FunctionType *FTy =
1096    llvm::FunctionType::get(ResultType, ArgTypes, false);
1097
1098  llvm::InlineAsm *IA =
1099    llvm::InlineAsm::get(FTy, AsmString, Constraints,
1100                         S.isVolatile() || S.getNumOutputs() == 0);
1101  llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end());
1102  Result->addAttribute(~0, llvm::Attribute::NoUnwind);
1103
1104
1105  // Extract all of the register value results from the asm.
1106  std::vector<llvm::Value*> RegResults;
1107  if (ResultRegTypes.size() == 1) {
1108    RegResults.push_back(Result);
1109  } else {
1110    for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
1111      llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
1112      RegResults.push_back(Tmp);
1113    }
1114  }
1115
1116  for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1117    llvm::Value *Tmp = RegResults[i];
1118
1119    // If the result type of the LLVM IR asm doesn't match the result type of
1120    // the expression, do the conversion.
1121    if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1122      const llvm::Type *TruncTy = ResultTruncRegTypes[i];
1123      // Truncate the integer result to the right size, note that
1124      // ResultTruncRegTypes can be a pointer.
1125      uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
1126      Tmp = Builder.CreateTrunc(Tmp, llvm::IntegerType::get(VMContext, (unsigned)ResSize));
1127
1128      if (Tmp->getType() != TruncTy) {
1129        assert(isa<llvm::PointerType>(TruncTy));
1130        Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
1131      }
1132    }
1133
1134    EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i],
1135                           ResultRegQualTys[i]);
1136  }
1137}
1138