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