CGStmt.cpp revision bb57265fdba1e8af05dd917b8bf243d49cfb3465
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  // If we happen to be at an unreachable point just create a dummy
47  // basic block to hold the code. We could change parts of irgen to
48  // simply not generate this code, but this situation is rare and
49  // probably not worth the effort.
50  // FIXME: Verify previous performance/effort claim.
51  EnsureInsertPoint();
52
53  // Generate a stoppoint if we are emitting debug info.
54  EmitStopPoint(S);
55
56  switch (S->getStmtClass()) {
57  default:
58    // Must be an expression in a stmt context.  Emit the value (to get
59    // side-effects) and ignore the result.
60    if (const Expr *E = dyn_cast<Expr>(S)) {
61      if (!hasAggregateLLVMType(E->getType()))
62        EmitScalarExpr(E);
63      else if (E->getType()->isAnyComplexType())
64        EmitComplexExpr(E);
65      else
66        EmitAggExpr(E, 0, false);
67    } else {
68      ErrorUnsupported(S, "statement");
69    }
70    break;
71  case Stmt::IndirectGotoStmtClass:
72    EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
73
74  case Stmt::IfStmtClass:       EmitIfStmt(cast<IfStmt>(*S));             break;
75  case Stmt::WhileStmtClass:    EmitWhileStmt(cast<WhileStmt>(*S));       break;
76  case Stmt::DoStmtClass:       EmitDoStmt(cast<DoStmt>(*S));             break;
77  case Stmt::ForStmtClass:      EmitForStmt(cast<ForStmt>(*S));           break;
78
79  case Stmt::ReturnStmtClass:   EmitReturnStmt(cast<ReturnStmt>(*S));     break;
80  case Stmt::DeclStmtClass:     EmitDeclStmt(cast<DeclStmt>(*S));         break;
81
82  case Stmt::SwitchStmtClass:   EmitSwitchStmt(cast<SwitchStmt>(*S));     break;
83  case Stmt::AsmStmtClass:      EmitAsmStmt(cast<AsmStmt>(*S));           break;
84
85  case Stmt::ObjCAtTryStmtClass:
86    EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
87    break;
88  case Stmt::ObjCAtCatchStmtClass:
89    assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
90    break;
91  case Stmt::ObjCAtFinallyStmtClass:
92    assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
93    break;
94  case Stmt::ObjCAtThrowStmtClass:
95    EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
96    break;
97  case Stmt::ObjCAtSynchronizedStmtClass:
98    EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
99    break;
100  case Stmt::ObjCForCollectionStmtClass:
101    EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
102    break;
103  }
104}
105
106bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
107  switch (S->getStmtClass()) {
108  default: return false;
109  case Stmt::NullStmtClass: break;
110  case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
111  case Stmt::LabelStmtClass:    EmitLabelStmt(cast<LabelStmt>(*S));       break;
112  case Stmt::GotoStmtClass:     EmitGotoStmt(cast<GotoStmt>(*S));         break;
113  case Stmt::BreakStmtClass:    EmitBreakStmt(cast<BreakStmt>(*S));       break;
114  case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
115  case Stmt::DefaultStmtClass:  EmitDefaultStmt(cast<DefaultStmt>(*S));   break;
116  case Stmt::CaseStmtClass:     EmitCaseStmt(cast<CaseStmt>(*S));         break;
117  }
118
119  return true;
120}
121
122/// EmitCompoundStmt - Emit a compound statement {..} node.  If GetLast is true,
123/// this captures the expression result of the last sub-statement and returns it
124/// (for use by the statement expression extension).
125RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
126                                         llvm::Value *AggLoc, bool isAggVol) {
127  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
128                             "LLVM IR generation of compound statement ('{}')");
129
130  CGDebugInfo *DI = getDebugInfo();
131  if (DI) {
132    EnsureInsertPoint();
133    DI->setLocation(S.getLBracLoc());
134    DI->EmitRegionStart(CurFn, Builder);
135  }
136
137  // Keep track of the current cleanup stack depth.
138  size_t CleanupStackDepth = CleanupEntries.size();
139  bool OldDidCallStackSave = DidCallStackSave;
140  DidCallStackSave = false;
141
142  for (CompoundStmt::const_body_iterator I = S.body_begin(),
143       E = S.body_end()-GetLast; I != E; ++I)
144    EmitStmt(*I);
145
146  if (DI) {
147    EnsureInsertPoint();
148    DI->setLocation(S.getRBracLoc());
149    DI->EmitRegionEnd(CurFn, Builder);
150  }
151
152  RValue RV;
153  if (!GetLast)
154    RV = RValue::get(0);
155  else {
156    // We have to special case labels here.  They are statements, but when put
157    // at the end of a statement expression, they yield the value of their
158    // subexpression.  Handle this by walking through all labels we encounter,
159    // emitting them before we evaluate the subexpr.
160    const Stmt *LastStmt = S.body_back();
161    while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
162      EmitLabel(*LS);
163      LastStmt = LS->getSubStmt();
164    }
165
166    EnsureInsertPoint();
167
168    RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
169  }
170
171  DidCallStackSave = OldDidCallStackSave;
172
173  EmitCleanupBlocks(CleanupStackDepth);
174
175  return RV;
176}
177
178void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
179  // Fall out of the current block (if necessary).
180  EmitBranch(BB);
181
182  if (IsFinished && BB->use_empty()) {
183    delete BB;
184    return;
185  }
186
187  // If necessary, associate the block with the cleanup stack size.
188  if (!CleanupEntries.empty()) {
189    // Check if the basic block has already been inserted.
190    BlockScopeMap::iterator I = BlockScopes.find(BB);
191    if (I != BlockScopes.end()) {
192      assert(I->second == CleanupEntries.size() - 1);
193    } else {
194      BlockScopes[BB] = CleanupEntries.size() - 1;
195      CleanupEntries.back().Blocks.push_back(BB);
196    }
197  }
198
199  CurFn->getBasicBlockList().push_back(BB);
200  Builder.SetInsertPoint(BB);
201}
202
203void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
204  // Emit a branch from the current block to the target one if this
205  // was a real block.  If this was just a fall-through block after a
206  // terminator, don't emit it.
207  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
208
209  if (!CurBB || CurBB->getTerminator()) {
210    // If there is no insert point or the previous block is already
211    // terminated, don't touch it.
212  } else {
213    // Otherwise, create a fall-through branch.
214    Builder.CreateBr(Target);
215  }
216
217  Builder.ClearInsertionPoint();
218}
219
220void CodeGenFunction::EmitLabel(const LabelStmt &S) {
221  EmitBlock(getBasicBlockForLabel(&S));
222}
223
224
225void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
226  EmitLabel(S);
227  EmitStmt(S.getSubStmt());
228}
229
230void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
231  // If this code is reachable then emit a stop point (if generating
232  // debug info). We have to do this ourselves because we are on the
233  // "simple" statement path.
234  if (HaveInsertPoint())
235    EmitStopPoint(&S);
236
237  EmitBranchThroughCleanup(getBasicBlockForLabel(S.getLabel()));
238}
239
240void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
241  // Emit initial switch which will be patched up later by
242  // EmitIndirectSwitches(). We need a default dest, so we use the
243  // current BB, but this is overwritten.
244  llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
245                                          llvm::Type::Int32Ty,
246                                          "addr");
247  llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
248  IndirectSwitches.push_back(I);
249
250  // Clear the insertion point to indicate we are in unreachable code.
251  Builder.ClearInsertionPoint();
252}
253
254void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
255  // C99 6.8.4.1: The first substatement is executed if the expression compares
256  // unequal to 0.  The condition must be a scalar type.
257
258  // If the condition constant folds and can be elided, try to avoid emitting
259  // the condition and the dead arm of the if/else.
260  if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
261    // Figure out which block (then or else) is executed.
262    const Stmt *Executed = S.getThen(), *Skipped  = S.getElse();
263    if (Cond == -1)  // Condition false?
264      std::swap(Executed, Skipped);
265
266    // If the skipped block has no labels in it, just emit the executed block.
267    // This avoids emitting dead code and simplifies the CFG substantially.
268    if (!ContainsLabel(Skipped)) {
269      if (Executed)
270        EmitStmt(Executed);
271      return;
272    }
273  }
274
275  // Otherwise, the condition did not fold, or we couldn't elide it.  Just emit
276  // the conditional branch.
277  llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
278  llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
279  llvm::BasicBlock *ElseBlock = ContBlock;
280  if (S.getElse())
281    ElseBlock = createBasicBlock("if.else");
282  EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
283
284  // Emit the 'then' code.
285  EmitBlock(ThenBlock);
286  EmitStmt(S.getThen());
287  EmitBranch(ContBlock);
288
289  // Emit the 'else' code if present.
290  if (const Stmt *Else = S.getElse()) {
291    EmitBlock(ElseBlock);
292    EmitStmt(Else);
293    EmitBranch(ContBlock);
294  }
295
296  // Emit the continuation block for code after the if.
297  EmitBlock(ContBlock, true);
298}
299
300void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
301  // Emit the header for the loop, insert it, which will create an uncond br to
302  // it.
303  llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
304  EmitBlock(LoopHeader);
305
306  // Create an exit block for when the condition fails, create a block for the
307  // body of the loop.
308  llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
309  llvm::BasicBlock *LoopBody  = createBasicBlock("while.body");
310
311  // Store the blocks to use for break and continue.
312  BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
313
314  // Evaluate the conditional in the while header.  C99 6.8.5.1: The
315  // evaluation of the controlling expression takes place before each
316  // execution of the loop body.
317  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
318
319  // while(1) is common, avoid extra exit blocks.  Be sure
320  // to correctly handle break/continue though.
321  bool EmitBoolCondBranch = true;
322  if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
323    if (C->isOne())
324      EmitBoolCondBranch = false;
325
326  // As long as the condition is true, go to the loop body.
327  if (EmitBoolCondBranch)
328    Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
329
330  // Emit the loop body.
331  EmitBlock(LoopBody);
332  EmitStmt(S.getBody());
333
334  BreakContinueStack.pop_back();
335
336  // Cycle to the condition.
337  EmitBranch(LoopHeader);
338
339  // Emit the exit block.
340  EmitBlock(ExitBlock, true);
341
342  // If LoopHeader is a simple forwarding block then eliminate it.
343  if (!EmitBoolCondBranch
344      && &LoopHeader->front() == LoopHeader->getTerminator()) {
345    LoopHeader->replaceAllUsesWith(LoopBody);
346    LoopHeader->getTerminator()->eraseFromParent();
347    LoopHeader->eraseFromParent();
348  }
349}
350
351void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
352  // Emit the body for the loop, insert it, which will create an uncond br to
353  // it.
354  llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
355  llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
356  EmitBlock(LoopBody);
357
358  llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
359
360  // Store the blocks to use for break and continue.
361  BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
362
363  // Emit the body of the loop into the block.
364  EmitStmt(S.getBody());
365
366  BreakContinueStack.pop_back();
367
368  EmitBlock(DoCond);
369
370  // C99 6.8.5.2: "The evaluation of the controlling expression takes place
371  // after each execution of the loop body."
372
373  // Evaluate the conditional in the while header.
374  // C99 6.8.5p2/p4: The first substatement is executed if the expression
375  // compares unequal to 0.  The condition must be a scalar type.
376  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
377
378  // "do {} while (0)" is common in macros, avoid extra blocks.  Be sure
379  // to correctly handle break/continue though.
380  bool EmitBoolCondBranch = true;
381  if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
382    if (C->isZero())
383      EmitBoolCondBranch = false;
384
385  // As long as the condition is true, iterate the loop.
386  if (EmitBoolCondBranch)
387    Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
388
389  // Emit the exit block.
390  EmitBlock(AfterDo, true);
391
392  // If DoCond is a simple forwarding block then eliminate it.
393  if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
394    DoCond->replaceAllUsesWith(AfterDo);
395    DoCond->getTerminator()->eraseFromParent();
396    DoCond->eraseFromParent();
397  }
398}
399
400void CodeGenFunction::EmitForStmt(const ForStmt &S) {
401  // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
402  // which contains a continue/break?
403
404  // Evaluate the first part before the loop.
405  if (S.getInit())
406    EmitStmt(S.getInit());
407
408  // Start the loop with a block that tests the condition.
409  llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
410  llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
411
412  EmitBlock(CondBlock);
413
414  // Evaluate the condition if present.  If not, treat it as a
415  // non-zero-constant according to 6.8.5.3p2, aka, true.
416  if (S.getCond()) {
417    // As long as the condition is true, iterate the loop.
418    llvm::BasicBlock *ForBody = createBasicBlock("for.body");
419
420    // C99 6.8.5p2/p4: The first substatement is executed if the expression
421    // compares unequal to 0.  The condition must be a scalar type.
422    EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
423
424    EmitBlock(ForBody);
425  } else {
426    // Treat it as a non-zero constant.  Don't even create a new block for the
427    // body, just fall into it.
428  }
429
430  // If the for loop doesn't have an increment we can just use the
431  // condition as the continue block.
432  llvm::BasicBlock *ContinueBlock;
433  if (S.getInc())
434    ContinueBlock = createBasicBlock("for.inc");
435  else
436    ContinueBlock = CondBlock;
437
438  // Store the blocks to use for break and continue.
439  BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
440
441  // If the condition is true, execute the body of the for stmt.
442  EmitStmt(S.getBody());
443
444  BreakContinueStack.pop_back();
445
446  // If there is an increment, emit it next.
447  if (S.getInc()) {
448    EmitBlock(ContinueBlock);
449    EmitStmt(S.getInc());
450  }
451
452  // Finally, branch back up to the condition for the next iteration.
453  EmitBranch(CondBlock);
454
455  // Emit the fall-through block.
456  EmitBlock(AfterFor, true);
457}
458
459void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
460  if (RV.isScalar()) {
461    Builder.CreateStore(RV.getScalarVal(), ReturnValue);
462  } else if (RV.isAggregate()) {
463    EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
464  } else {
465    StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
466  }
467  EmitBranchThroughCleanup(ReturnBlock);
468}
469
470/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
471/// if the function returns void, or may be missing one if the function returns
472/// non-void.  Fun stuff :).
473void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
474  // Emit the result value, even if unused, to evalute the side effects.
475  const Expr *RV = S.getRetValue();
476
477  // FIXME: Clean this up by using an LValue for ReturnTemp,
478  // EmitStoreThroughLValue, and EmitAnyExpr.
479  if (!ReturnValue) {
480    // Make sure not to return anything, but evaluate the expression
481    // for side effects.
482    if (RV)
483      EmitAnyExpr(RV);
484  } else if (RV == 0) {
485    // Do nothing (return value is left uninitialized)
486  } else if (!hasAggregateLLVMType(RV->getType())) {
487    Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
488  } else if (RV->getType()->isAnyComplexType()) {
489    EmitComplexExprIntoAddr(RV, ReturnValue, false);
490  } else {
491    EmitAggExpr(RV, ReturnValue, false);
492  }
493
494  EmitBranchThroughCleanup(ReturnBlock);
495}
496
497void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
498  for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
499       I != E; ++I)
500    EmitDecl(**I);
501}
502
503void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
504  assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
505
506  // If this code is reachable then emit a stop point (if generating
507  // debug info). We have to do this ourselves because we are on the
508  // "simple" statement path.
509  if (HaveInsertPoint())
510    EmitStopPoint(&S);
511
512  llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
513  EmitBranchThroughCleanup(Block);
514}
515
516void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
517  assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
518
519  // If this code is reachable then emit a stop point (if generating
520  // debug info). We have to do this ourselves because we are on the
521  // "simple" statement path.
522  if (HaveInsertPoint())
523    EmitStopPoint(&S);
524
525  llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
526  EmitBranchThroughCleanup(Block);
527}
528
529/// EmitCaseStmtRange - If case statement range is not too big then
530/// add multiple cases to switch instruction, one for each value within
531/// the range. If range is too big then emit "if" condition check.
532void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
533  assert(S.getRHS() && "Expected RHS value in CaseStmt");
534
535  llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
536  llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
537
538  // Emit the code for this case. We do this first to make sure it is
539  // properly chained from our predecessor before generating the
540  // switch machinery to enter this block.
541  EmitBlock(createBasicBlock("sw.bb"));
542  llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
543  EmitStmt(S.getSubStmt());
544
545  // If range is empty, do nothing.
546  if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
547    return;
548
549  llvm::APInt Range = RHS - LHS;
550  // FIXME: parameters such as this should not be hardcoded.
551  if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
552    // Range is small enough to add multiple switch instruction cases.
553    for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
554      SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
555      LHS++;
556    }
557    return;
558  }
559
560  // The range is too big. Emit "if" condition into a new block,
561  // making sure to save and restore the current insertion point.
562  llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
563
564  // Push this test onto the chain of range checks (which terminates
565  // in the default basic block). The switch's default will be changed
566  // to the top of this chain after switch emission is complete.
567  llvm::BasicBlock *FalseDest = CaseRangeBlock;
568  CaseRangeBlock = createBasicBlock("sw.caserange");
569
570  CurFn->getBasicBlockList().push_back(CaseRangeBlock);
571  Builder.SetInsertPoint(CaseRangeBlock);
572
573  // Emit range check.
574  llvm::Value *Diff =
575    Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
576                      "tmp");
577  llvm::Value *Cond =
578    Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
579  Builder.CreateCondBr(Cond, CaseDest, FalseDest);
580
581  // Restore the appropriate insertion point.
582  if (RestoreBB)
583    Builder.SetInsertPoint(RestoreBB);
584  else
585    Builder.ClearInsertionPoint();
586}
587
588void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
589  if (S.getRHS()) {
590    EmitCaseStmtRange(S);
591    return;
592  }
593
594  EmitBlock(createBasicBlock("sw.bb"));
595  llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
596  llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
597  SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
598
599  // Recursively emitting the statement is acceptable, but is not wonderful for
600  // code where we have many case statements nested together, i.e.:
601  //  case 1:
602  //    case 2:
603  //      case 3: etc.
604  // Handling this recursively will create a new block for each case statement
605  // that falls through to the next case which is IR intensive.  It also causes
606  // deep recursion which can run into stack depth limitations.  Handle
607  // sequential non-range case statements specially.
608  const CaseStmt *CurCase = &S;
609  const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
610
611  // Otherwise, iteratively add consequtive cases to this switch stmt.
612  while (NextCase && NextCase->getRHS() == 0) {
613    CurCase = NextCase;
614    CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
615    SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
616
617    NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
618  }
619
620  // Normal default recursion for non-cases.
621  EmitStmt(CurCase->getSubStmt());
622}
623
624void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
625  llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
626  assert(DefaultBlock->empty() &&
627         "EmitDefaultStmt: Default block already defined?");
628  EmitBlock(DefaultBlock);
629  EmitStmt(S.getSubStmt());
630}
631
632void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
633  llvm::Value *CondV = EmitScalarExpr(S.getCond());
634
635  // Handle nested switch statements.
636  llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
637  llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
638
639  // Create basic block to hold stuff that comes after switch
640  // statement. We also need to create a default block now so that
641  // explicit case ranges tests can have a place to jump to on
642  // failure.
643  llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
644  llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
645  SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
646  CaseRangeBlock = DefaultBlock;
647
648  // Clear the insertion point to indicate we are in unreachable code.
649  Builder.ClearInsertionPoint();
650
651  // All break statements jump to NextBlock. If BreakContinueStack is non empty
652  // then reuse last ContinueBlock.
653  llvm::BasicBlock *ContinueBlock = 0;
654  if (!BreakContinueStack.empty())
655    ContinueBlock = BreakContinueStack.back().ContinueBlock;
656
657  // Ensure any vlas created between there and here, are undone
658  BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
659
660  // Emit switch body.
661  EmitStmt(S.getBody());
662
663  BreakContinueStack.pop_back();
664
665  // Update the default block in case explicit case range tests have
666  // been chained on top.
667  SwitchInsn->setSuccessor(0, CaseRangeBlock);
668
669  // If a default was never emitted then reroute any jumps to it and
670  // discard.
671  if (!DefaultBlock->getParent()) {
672    DefaultBlock->replaceAllUsesWith(NextBlock);
673    delete DefaultBlock;
674  }
675
676  // Emit continuation.
677  EmitBlock(NextBlock, true);
678
679  SwitchInsn = SavedSwitchInsn;
680  CaseRangeBlock = SavedCRBlock;
681}
682
683/// ConvertAsmString - Convert the GNU-style asm string to the LLVM-style asm
684/// string.
685static std::string ConvertAsmString(const AsmStmt& S, bool &Failed) {
686  Failed = false;
687
688  const char *StrStart = S.getAsmString()->getStrData();
689  const char *StrEnd = StrStart + S.getAsmString()->getByteLength();
690
691  // "Simple" inline asms have no constraints or operands, just convert the asm
692  // string to escape $'s.
693  if (S.isSimple()) {
694    std::string Result;
695    for (; StrStart != StrEnd; ++StrStart) {
696      switch (*StrStart) {
697      case '$':
698        Result += "$$";
699        break;
700      default:
701        Result += *StrStart;
702        break;
703      }
704    }
705    return Result;
706  }
707
708  std::string Result;
709
710  unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
711
712  while (1) {
713    // Done with the string?
714    if (StrStart == StrEnd)
715      return Result;
716
717    char CurChar = *StrStart++;
718    if (CurChar == '$') {
719      Result += "$$";
720      continue;
721    } else if (CurChar != '%') {
722      Result += CurChar;
723      continue;
724    }
725
726    // Escaped "%" character in asm string.
727    // FIXME: This should be caught during Sema.
728    assert(StrStart != StrEnd && "Trailing '%' in asm string.");
729
730    char EscapedChar = *StrStart++;
731    if (EscapedChar == '%') {  // %% -> %
732      // Escaped percentage sign.
733      Result += '%';
734      continue;
735    }
736
737    if (EscapedChar == '=') {  // %= -> Generate an unique ID.
738      Result += "${:uid}";
739      continue;
740    }
741
742    if (isdigit(EscapedChar)) {
743      // %n - Assembler operand n
744      char *End;
745      unsigned long N = strtoul(StrStart-1, &End, 10);
746      assert(End != StrStart-1 && "We know that EscapedChar is a digit!");
747
748      // FIXME: This should be caught during Sema.
749      assert(N < NumOperands && "Operand number out of range!");
750
751      Result += '$' + llvm::utostr(N);
752      StrStart = End;
753      continue;
754    }
755
756    if (isalpha(EscapedChar)) {
757      char *End;
758      // Skip the single letter escape and read the number, e.g. "%x4".
759      unsigned long N = strtoul(StrStart, &End, 10);
760      // FIXME: This should be caught during Sema.
761      assert(End != StrStart && "Missing operand!");
762      // FIXME: This should be caught during Sema.
763      assert(N < NumOperands && "Operand number out of range!");
764
765      Result += "${" + llvm::utostr(N) + ':' + EscapedChar + '}';
766      StrStart = End;
767      continue;
768    }
769
770    // Handle %[foo], a symbolic operand reference.
771    if (EscapedChar == '[') {
772      const char *NameEnd = (const char*)memchr(StrStart, ']', StrEnd-StrStart);
773      // FIXME: Should be caught by sema.
774      assert(NameEnd != 0 && "Could not parse symbolic name");
775
776      std::string SymbolicName(StrStart, NameEnd);
777
778      StrStart = NameEnd+1;
779
780      int Index = -1;
781
782      // Check if this is an output operand.
783      for (unsigned i = 0; i != S.getNumOutputs(); ++i) {
784        if (S.getOutputName(i) == SymbolicName) {
785          Index = i;
786          break;
787        }
788      }
789
790      if (Index == -1) {
791        for (unsigned i = 0; i != S.getNumInputs(); ++i) {
792          if (S.getInputName(i) == SymbolicName) {
793            Index = S.getNumOutputs() + i;
794            break;
795          }
796        }
797      }
798
799      assert(Index != -1 && "Did not find right operand!");
800
801      Result += '$' + llvm::utostr(Index);
802      continue;
803    }
804
805    Failed = true;
806    return "";
807  }
808}
809
810static std::string SimplifyConstraint(const char* Constraint,
811                                      TargetInfo &Target,
812                                      const std::string *OutputNamesBegin = 0,
813                                      const std::string *OutputNamesEnd = 0) {
814  std::string Result;
815
816  while (*Constraint) {
817    switch (*Constraint) {
818    default:
819      Result += Target.convertConstraint(*Constraint);
820      break;
821    // Ignore these
822    case '*':
823    case '?':
824    case '!':
825      break;
826    case 'g':
827      Result += "imr";
828      break;
829    case '[': {
830      assert(OutputNamesBegin && OutputNamesEnd &&
831             "Must pass output names to constraints with a symbolic name");
832      unsigned Index;
833      bool result = Target.resolveSymbolicName(Constraint,
834                                               OutputNamesBegin,
835                                               OutputNamesEnd, Index);
836      assert(result && "Could not resolve symbolic name"); result=result;
837      Result += llvm::utostr(Index);
838      break;
839    }
840    }
841
842    Constraint++;
843  }
844
845  return Result;
846}
847
848llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
849                                           TargetInfo::ConstraintInfo Info,
850                                           const Expr *InputExpr,
851                                           std::string &ConstraintStr) {
852  llvm::Value *Arg;
853  if ((Info & TargetInfo::CI_AllowsRegister) ||
854      !(Info & TargetInfo::CI_AllowsMemory)) {
855    const llvm::Type *Ty = ConvertType(InputExpr->getType());
856
857    if (Ty->isSingleValueType()) {
858      Arg = EmitScalarExpr(InputExpr);
859    } else {
860      LValue Dest = EmitLValue(InputExpr);
861
862      uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
863      if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
864        Ty = llvm::IntegerType::get(Size);
865        Ty = llvm::PointerType::getUnqual(Ty);
866
867        Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
868      } else {
869        Arg = Dest.getAddress();
870        ConstraintStr += '*';
871      }
872    }
873  } else {
874    LValue Dest = EmitLValue(InputExpr);
875    Arg = Dest.getAddress();
876    ConstraintStr += '*';
877  }
878
879  return Arg;
880}
881
882void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
883  bool Failed;
884  std::string AsmString = ConvertAsmString(S, Failed);
885
886  if (Failed) {
887    ErrorUnsupported(&S, "asm string");
888    return;
889  }
890
891  std::string Constraints;
892
893  llvm::Value *ResultAddr = 0;
894  const llvm::Type *ResultType = llvm::Type::VoidTy;
895
896  std::vector<const llvm::Type*> ArgTypes;
897  std::vector<llvm::Value*> Args;
898
899  // Keep track of inout constraints.
900  std::string InOutConstraints;
901  std::vector<llvm::Value*> InOutArgs;
902  std::vector<const llvm::Type*> InOutArgTypes;
903
904  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
905
906  for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
907    std::string OutputConstraint(S.getOutputConstraint(i));
908
909    TargetInfo::ConstraintInfo Info;
910    bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
911                                                  Info);
912    assert(result && "Failed to parse output constraint"); result=result;
913
914    OutputConstraintInfos.push_back(Info);
915
916    // Simplify the output constraint.
917    OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
918
919    LValue Dest = EmitLValue(S.getOutputExpr(i));
920    const llvm::Type *DestValueType =
921      cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
922
923    // If the first output operand is not a memory dest, we'll
924    // make it the return value.
925    if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
926        DestValueType->isSingleValueType()) {
927      ResultAddr = Dest.getAddress();
928      ResultType = DestValueType;
929      Constraints += "=" + OutputConstraint;
930    } else {
931      ArgTypes.push_back(Dest.getAddress()->getType());
932      Args.push_back(Dest.getAddress());
933      if (i != 0)
934        Constraints += ',';
935      Constraints += "=*";
936      Constraints += OutputConstraint;
937    }
938
939    if (Info & TargetInfo::CI_ReadWrite) {
940      InOutConstraints += ',';
941
942      const Expr *InputExpr = S.getOutputExpr(i);
943      llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
944
945      if (Info & TargetInfo::CI_AllowsRegister)
946        InOutConstraints += llvm::utostr(i);
947      else
948        InOutConstraints += OutputConstraint;
949
950      InOutArgTypes.push_back(Arg->getType());
951      InOutArgs.push_back(Arg);
952    }
953  }
954
955  unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
956
957  for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
958    const Expr *InputExpr = S.getInputExpr(i);
959
960    std::string InputConstraint(S.getInputConstraint(i));
961
962    TargetInfo::ConstraintInfo Info;
963    bool result = Target.validateInputConstraint(InputConstraint.c_str(),
964                                                 S.begin_output_names(),
965                                                 S.end_output_names(),
966                                                 &OutputConstraintInfos[0],
967                                                 Info); result=result;
968    assert(result && "Failed to parse input constraint");
969
970    if (i != 0 || S.getNumOutputs() > 0)
971      Constraints += ',';
972
973    // Simplify the input constraint.
974    InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
975                                         S.begin_output_names(),
976                                         S.end_output_names());
977
978    llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
979
980    ArgTypes.push_back(Arg->getType());
981    Args.push_back(Arg);
982    Constraints += InputConstraint;
983  }
984
985  // Append the "input" part of inout constraints last.
986  for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
987    ArgTypes.push_back(InOutArgTypes[i]);
988    Args.push_back(InOutArgs[i]);
989  }
990  Constraints += InOutConstraints;
991
992  // Clobbers
993  for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
994    std::string Clobber(S.getClobber(i)->getStrData(),
995                        S.getClobber(i)->getByteLength());
996
997    Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
998
999    if (i != 0 || NumConstraints != 0)
1000      Constraints += ',';
1001
1002    Constraints += "~{";
1003    Constraints += Clobber;
1004    Constraints += '}';
1005  }
1006
1007  // Add machine specific clobbers
1008  std::string MachineClobbers = Target.getClobbers();
1009  if (!MachineClobbers.empty()) {
1010    if (!Constraints.empty())
1011      Constraints += ',';
1012    Constraints += MachineClobbers;
1013  }
1014
1015  const llvm::FunctionType *FTy =
1016    llvm::FunctionType::get(ResultType, ArgTypes, false);
1017
1018  llvm::InlineAsm *IA =
1019    llvm::InlineAsm::get(FTy, AsmString, Constraints,
1020                         S.isVolatile() || S.getNumOutputs() == 0);
1021  llvm::CallInst *Result
1022    = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
1023  Result->addAttribute(~0, llvm::Attribute::NoUnwind);
1024
1025  if (ResultAddr) // FIXME: volatility
1026    Builder.CreateStore(Result, ResultAddr);
1027}
1028