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