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