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 "TargetInfo.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/Basic/PrettyStackTrace.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/InlineAsm.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/Target/TargetData.h"
25 using namespace clang;
26 using namespace CodeGen;
27
28 //===----------------------------------------------------------------------===//
29 // Statement Emission
30 //===----------------------------------------------------------------------===//
31
EmitStopPoint(const Stmt * S)32 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
33 if (CGDebugInfo *DI = getDebugInfo()) {
34 if (isa<DeclStmt>(S))
35 DI->setLocation(S->getLocEnd());
36 else
37 DI->setLocation(S->getLocStart());
38 DI->UpdateLineDirectiveRegion(Builder);
39 DI->EmitStopPoint(Builder);
40 }
41 }
42
EmitStmt(const Stmt * S)43 void CodeGenFunction::EmitStmt(const Stmt *S) {
44 assert(S && "Null statement?");
45
46 // Check if we can handle this without bothering to generate an
47 // insert point or debug info.
48 if (EmitSimpleStmt(S))
49 return;
50
51 // Check if we are generating unreachable code.
52 if (!HaveInsertPoint()) {
53 // If so, and the statement doesn't contain a label, then we do not need to
54 // generate actual code. This is safe because (1) the current point is
55 // unreachable, so we don't need to execute the code, and (2) we've already
56 // handled the statements which update internal data structures (like the
57 // local variable map) which could be used by subsequent statements.
58 if (!ContainsLabel(S)) {
59 // Verify that any decl statements were handled as simple, they may be in
60 // scope of subsequent reachable statements.
61 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
62 return;
63 }
64
65 // Otherwise, make a new block to hold the code.
66 EnsureInsertPoint();
67 }
68
69 // Generate a stoppoint if we are emitting debug info.
70 EmitStopPoint(S);
71
72 switch (S->getStmtClass()) {
73 case Stmt::NoStmtClass:
74 case Stmt::CXXCatchStmtClass:
75 case Stmt::SEHExceptStmtClass:
76 case Stmt::SEHFinallyStmtClass:
77 llvm_unreachable("invalid statement class to emit generically");
78 case Stmt::NullStmtClass:
79 case Stmt::CompoundStmtClass:
80 case Stmt::DeclStmtClass:
81 case Stmt::LabelStmtClass:
82 case Stmt::GotoStmtClass:
83 case Stmt::BreakStmtClass:
84 case Stmt::ContinueStmtClass:
85 case Stmt::DefaultStmtClass:
86 case Stmt::CaseStmtClass:
87 llvm_unreachable("should have emitted these statements as simple");
88
89 #define STMT(Type, Base)
90 #define ABSTRACT_STMT(Op)
91 #define EXPR(Type, Base) \
92 case Stmt::Type##Class:
93 #include "clang/AST/StmtNodes.inc"
94 {
95 // Remember the block we came in on.
96 llvm::BasicBlock *incoming = Builder.GetInsertBlock();
97 assert(incoming && "expression emission must have an insertion point");
98
99 EmitIgnoredExpr(cast<Expr>(S));
100
101 llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
102 assert(outgoing && "expression emission cleared block!");
103
104 // The expression emitters assume (reasonably!) that the insertion
105 // point is always set. To maintain that, the call-emission code
106 // for noreturn functions has to enter a new block with no
107 // predecessors. We want to kill that block and mark the current
108 // insertion point unreachable in the common case of a call like
109 // "exit();". Since expression emission doesn't otherwise create
110 // blocks with no predecessors, we can just test for that.
111 // However, we must be careful not to do this to our incoming
112 // block, because *statement* emission does sometimes create
113 // reachable blocks which will have no predecessors until later in
114 // the function. This occurs with, e.g., labels that are not
115 // reachable by fallthrough.
116 if (incoming != outgoing && outgoing->use_empty()) {
117 outgoing->eraseFromParent();
118 Builder.ClearInsertionPoint();
119 }
120 break;
121 }
122
123 case Stmt::IndirectGotoStmtClass:
124 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
125
126 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
127 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
128 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
129 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
130
131 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
132
133 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
134 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
135
136 case Stmt::ObjCAtTryStmtClass:
137 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
138 break;
139 case Stmt::ObjCAtCatchStmtClass:
140 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
141 break;
142 case Stmt::ObjCAtFinallyStmtClass:
143 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
144 break;
145 case Stmt::ObjCAtThrowStmtClass:
146 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
147 break;
148 case Stmt::ObjCAtSynchronizedStmtClass:
149 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
150 break;
151 case Stmt::ObjCForCollectionStmtClass:
152 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
153 break;
154 case Stmt::ObjCAutoreleasePoolStmtClass:
155 EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
156 break;
157
158 case Stmt::CXXTryStmtClass:
159 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
160 break;
161 case Stmt::CXXForRangeStmtClass:
162 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
163 case Stmt::SEHTryStmtClass:
164 // FIXME Not yet implemented
165 break;
166 }
167 }
168
EmitSimpleStmt(const Stmt * S)169 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
170 switch (S->getStmtClass()) {
171 default: return false;
172 case Stmt::NullStmtClass: break;
173 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
174 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
175 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
176 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
177 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
178 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
179 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
180 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
181 }
182
183 return true;
184 }
185
186 /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
187 /// this captures the expression result of the last sub-statement and returns it
188 /// (for use by the statement expression extension).
EmitCompoundStmt(const CompoundStmt & S,bool GetLast,AggValueSlot AggSlot)189 RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
190 AggValueSlot AggSlot) {
191 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
192 "LLVM IR generation of compound statement ('{}')");
193
194 CGDebugInfo *DI = getDebugInfo();
195 if (DI) {
196 DI->setLocation(S.getLBracLoc());
197 DI->EmitRegionStart(Builder);
198 }
199
200 // Keep track of the current cleanup stack depth.
201 RunCleanupsScope Scope(*this);
202
203 for (CompoundStmt::const_body_iterator I = S.body_begin(),
204 E = S.body_end()-GetLast; I != E; ++I)
205 EmitStmt(*I);
206
207 if (DI) {
208 DI->setLocation(S.getRBracLoc());
209 DI->EmitRegionEnd(Builder);
210 }
211
212 RValue RV;
213 if (!GetLast)
214 RV = RValue::get(0);
215 else {
216 // We have to special case labels here. They are statements, but when put
217 // at the end of a statement expression, they yield the value of their
218 // subexpression. Handle this by walking through all labels we encounter,
219 // emitting them before we evaluate the subexpr.
220 const Stmt *LastStmt = S.body_back();
221 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
222 EmitLabel(LS->getDecl());
223 LastStmt = LS->getSubStmt();
224 }
225
226 EnsureInsertPoint();
227
228 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggSlot);
229 }
230
231 return RV;
232 }
233
SimplifyForwardingBlocks(llvm::BasicBlock * BB)234 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
235 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
236
237 // If there is a cleanup stack, then we it isn't worth trying to
238 // simplify this block (we would need to remove it from the scope map
239 // and cleanup entry).
240 if (!EHStack.empty())
241 return;
242
243 // Can only simplify direct branches.
244 if (!BI || !BI->isUnconditional())
245 return;
246
247 BB->replaceAllUsesWith(BI->getSuccessor(0));
248 BI->eraseFromParent();
249 BB->eraseFromParent();
250 }
251
EmitBlock(llvm::BasicBlock * BB,bool IsFinished)252 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
253 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
254
255 // Fall out of the current block (if necessary).
256 EmitBranch(BB);
257
258 if (IsFinished && BB->use_empty()) {
259 delete BB;
260 return;
261 }
262
263 // Place the block after the current block, if possible, or else at
264 // the end of the function.
265 if (CurBB && CurBB->getParent())
266 CurFn->getBasicBlockList().insertAfter(CurBB, BB);
267 else
268 CurFn->getBasicBlockList().push_back(BB);
269 Builder.SetInsertPoint(BB);
270 }
271
EmitBranch(llvm::BasicBlock * Target)272 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
273 // Emit a branch from the current block to the target one if this
274 // was a real block. If this was just a fall-through block after a
275 // terminator, don't emit it.
276 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
277
278 if (!CurBB || CurBB->getTerminator()) {
279 // If there is no insert point or the previous block is already
280 // terminated, don't touch it.
281 } else {
282 // Otherwise, create a fall-through branch.
283 Builder.CreateBr(Target);
284 }
285
286 Builder.ClearInsertionPoint();
287 }
288
289 CodeGenFunction::JumpDest
getJumpDestForLabel(const LabelDecl * D)290 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
291 JumpDest &Dest = LabelMap[D];
292 if (Dest.isValid()) return Dest;
293
294 // Create, but don't insert, the new block.
295 Dest = JumpDest(createBasicBlock(D->getName()),
296 EHScopeStack::stable_iterator::invalid(),
297 NextCleanupDestIndex++);
298 return Dest;
299 }
300
EmitLabel(const LabelDecl * D)301 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
302 JumpDest &Dest = LabelMap[D];
303
304 // If we didn't need a forward reference to this label, just go
305 // ahead and create a destination at the current scope.
306 if (!Dest.isValid()) {
307 Dest = getJumpDestInCurrentScope(D->getName());
308
309 // Otherwise, we need to give this label a target depth and remove
310 // it from the branch-fixups list.
311 } else {
312 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
313 Dest = JumpDest(Dest.getBlock(),
314 EHStack.stable_begin(),
315 Dest.getDestIndex());
316
317 ResolveBranchFixups(Dest.getBlock());
318 }
319
320 EmitBlock(Dest.getBlock());
321 }
322
323
EmitLabelStmt(const LabelStmt & S)324 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
325 EmitLabel(S.getDecl());
326 EmitStmt(S.getSubStmt());
327 }
328
EmitGotoStmt(const GotoStmt & S)329 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
330 // If this code is reachable then emit a stop point (if generating
331 // debug info). We have to do this ourselves because we are on the
332 // "simple" statement path.
333 if (HaveInsertPoint())
334 EmitStopPoint(&S);
335
336 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
337 }
338
339
EmitIndirectGotoStmt(const IndirectGotoStmt & S)340 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
341 if (const LabelDecl *Target = S.getConstantTarget()) {
342 EmitBranchThroughCleanup(getJumpDestForLabel(Target));
343 return;
344 }
345
346 // Ensure that we have an i8* for our PHI node.
347 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
348 Int8PtrTy, "addr");
349 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
350
351
352 // Get the basic block for the indirect goto.
353 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
354
355 // The first instruction in the block has to be the PHI for the switch dest,
356 // add an entry for this branch.
357 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
358
359 EmitBranch(IndGotoBB);
360 }
361
EmitIfStmt(const IfStmt & S)362 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
363 // C99 6.8.4.1: The first substatement is executed if the expression compares
364 // unequal to 0. The condition must be a scalar type.
365 RunCleanupsScope ConditionScope(*this);
366
367 if (S.getConditionVariable())
368 EmitAutoVarDecl(*S.getConditionVariable());
369
370 // If the condition constant folds and can be elided, try to avoid emitting
371 // the condition and the dead arm of the if/else.
372 bool CondConstant;
373 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) {
374 // Figure out which block (then or else) is executed.
375 const Stmt *Executed = S.getThen();
376 const Stmt *Skipped = S.getElse();
377 if (!CondConstant) // Condition false?
378 std::swap(Executed, Skipped);
379
380 // If the skipped block has no labels in it, just emit the executed block.
381 // This avoids emitting dead code and simplifies the CFG substantially.
382 if (!ContainsLabel(Skipped)) {
383 if (Executed) {
384 RunCleanupsScope ExecutedScope(*this);
385 EmitStmt(Executed);
386 }
387 return;
388 }
389 }
390
391 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
392 // the conditional branch.
393 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
394 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
395 llvm::BasicBlock *ElseBlock = ContBlock;
396 if (S.getElse())
397 ElseBlock = createBasicBlock("if.else");
398 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
399
400 // Emit the 'then' code.
401 EmitBlock(ThenBlock);
402 {
403 RunCleanupsScope ThenScope(*this);
404 EmitStmt(S.getThen());
405 }
406 EmitBranch(ContBlock);
407
408 // Emit the 'else' code if present.
409 if (const Stmt *Else = S.getElse()) {
410 // There is no need to emit line number for unconditional branch.
411 if (getDebugInfo())
412 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
413 EmitBlock(ElseBlock);
414 {
415 RunCleanupsScope ElseScope(*this);
416 EmitStmt(Else);
417 }
418 // There is no need to emit line number for unconditional branch.
419 if (getDebugInfo())
420 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
421 EmitBranch(ContBlock);
422 }
423
424 // Emit the continuation block for code after the if.
425 EmitBlock(ContBlock, true);
426 }
427
EmitWhileStmt(const WhileStmt & S)428 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
429 // Emit the header for the loop, which will also become
430 // the continue target.
431 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
432 EmitBlock(LoopHeader.getBlock());
433
434 // Create an exit block for when the condition fails, which will
435 // also become the break target.
436 JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
437
438 // Store the blocks to use for break and continue.
439 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
440
441 // C++ [stmt.while]p2:
442 // When the condition of a while statement is a declaration, the
443 // scope of the variable that is declared extends from its point
444 // of declaration (3.3.2) to the end of the while statement.
445 // [...]
446 // The object created in a condition is destroyed and created
447 // with each iteration of the loop.
448 RunCleanupsScope ConditionScope(*this);
449
450 if (S.getConditionVariable())
451 EmitAutoVarDecl(*S.getConditionVariable());
452
453 // Evaluate the conditional in the while header. C99 6.8.5.1: The
454 // evaluation of the controlling expression takes place before each
455 // execution of the loop body.
456 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
457
458 // while(1) is common, avoid extra exit blocks. Be sure
459 // to correctly handle break/continue though.
460 bool EmitBoolCondBranch = true;
461 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
462 if (C->isOne())
463 EmitBoolCondBranch = false;
464
465 // As long as the condition is true, go to the loop body.
466 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
467 if (EmitBoolCondBranch) {
468 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
469 if (ConditionScope.requiresCleanups())
470 ExitBlock = createBasicBlock("while.exit");
471
472 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
473
474 if (ExitBlock != LoopExit.getBlock()) {
475 EmitBlock(ExitBlock);
476 EmitBranchThroughCleanup(LoopExit);
477 }
478 }
479
480 // Emit the loop body. We have to emit this in a cleanup scope
481 // because it might be a singleton DeclStmt.
482 {
483 RunCleanupsScope BodyScope(*this);
484 EmitBlock(LoopBody);
485 EmitStmt(S.getBody());
486 }
487
488 BreakContinueStack.pop_back();
489
490 // Immediately force cleanup.
491 ConditionScope.ForceCleanup();
492
493 // Branch to the loop header again.
494 EmitBranch(LoopHeader.getBlock());
495
496 // Emit the exit block.
497 EmitBlock(LoopExit.getBlock(), true);
498
499 // The LoopHeader typically is just a branch if we skipped emitting
500 // a branch, try to erase it.
501 if (!EmitBoolCondBranch)
502 SimplifyForwardingBlocks(LoopHeader.getBlock());
503 }
504
EmitDoStmt(const DoStmt & S)505 void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
506 JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
507 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
508
509 // Store the blocks to use for break and continue.
510 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
511
512 // Emit the body of the loop.
513 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
514 EmitBlock(LoopBody);
515 {
516 RunCleanupsScope BodyScope(*this);
517 EmitStmt(S.getBody());
518 }
519
520 BreakContinueStack.pop_back();
521
522 EmitBlock(LoopCond.getBlock());
523
524 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
525 // after each execution of the loop body."
526
527 // Evaluate the conditional in the while header.
528 // C99 6.8.5p2/p4: The first substatement is executed if the expression
529 // compares unequal to 0. The condition must be a scalar type.
530 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
531
532 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
533 // to correctly handle break/continue though.
534 bool EmitBoolCondBranch = true;
535 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
536 if (C->isZero())
537 EmitBoolCondBranch = false;
538
539 // As long as the condition is true, iterate the loop.
540 if (EmitBoolCondBranch)
541 Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock());
542
543 // Emit the exit block.
544 EmitBlock(LoopExit.getBlock());
545
546 // The DoCond block typically is just a branch if we skipped
547 // emitting a branch, try to erase it.
548 if (!EmitBoolCondBranch)
549 SimplifyForwardingBlocks(LoopCond.getBlock());
550 }
551
EmitForStmt(const ForStmt & S)552 void CodeGenFunction::EmitForStmt(const ForStmt &S) {
553 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
554
555 RunCleanupsScope ForScope(*this);
556
557 CGDebugInfo *DI = getDebugInfo();
558 if (DI) {
559 DI->setLocation(S.getSourceRange().getBegin());
560 DI->EmitRegionStart(Builder);
561 }
562
563 // Evaluate the first part before the loop.
564 if (S.getInit())
565 EmitStmt(S.getInit());
566
567 // Start the loop with a block that tests the condition.
568 // If there's an increment, the continue scope will be overwritten
569 // later.
570 JumpDest Continue = getJumpDestInCurrentScope("for.cond");
571 llvm::BasicBlock *CondBlock = Continue.getBlock();
572 EmitBlock(CondBlock);
573
574 // Create a cleanup scope for the condition variable cleanups.
575 RunCleanupsScope ConditionScope(*this);
576
577 llvm::Value *BoolCondVal = 0;
578 if (S.getCond()) {
579 // If the for statement has a condition scope, emit the local variable
580 // declaration.
581 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
582 if (S.getConditionVariable()) {
583 EmitAutoVarDecl(*S.getConditionVariable());
584 }
585
586 // If there are any cleanups between here and the loop-exit scope,
587 // create a block to stage a loop exit along.
588 if (ForScope.requiresCleanups())
589 ExitBlock = createBasicBlock("for.cond.cleanup");
590
591 // As long as the condition is true, iterate the loop.
592 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
593
594 // C99 6.8.5p2/p4: The first substatement is executed if the expression
595 // compares unequal to 0. The condition must be a scalar type.
596 BoolCondVal = EvaluateExprAsBool(S.getCond());
597 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
598
599 if (ExitBlock != LoopExit.getBlock()) {
600 EmitBlock(ExitBlock);
601 EmitBranchThroughCleanup(LoopExit);
602 }
603
604 EmitBlock(ForBody);
605 } else {
606 // Treat it as a non-zero constant. Don't even create a new block for the
607 // body, just fall into it.
608 }
609
610 // If the for loop doesn't have an increment we can just use the
611 // condition as the continue block. Otherwise we'll need to create
612 // a block for it (in the current scope, i.e. in the scope of the
613 // condition), and that we will become our continue block.
614 if (S.getInc())
615 Continue = getJumpDestInCurrentScope("for.inc");
616
617 // Store the blocks to use for break and continue.
618 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
619
620 {
621 // Create a separate cleanup scope for the body, in case it is not
622 // a compound statement.
623 RunCleanupsScope BodyScope(*this);
624 EmitStmt(S.getBody());
625 }
626
627 // If there is an increment, emit it next.
628 if (S.getInc()) {
629 EmitBlock(Continue.getBlock());
630 EmitStmt(S.getInc());
631 }
632
633 BreakContinueStack.pop_back();
634
635 ConditionScope.ForceCleanup();
636 EmitBranch(CondBlock);
637
638 ForScope.ForceCleanup();
639
640 if (DI) {
641 DI->setLocation(S.getSourceRange().getEnd());
642 DI->EmitRegionEnd(Builder);
643 }
644
645 // Emit the fall-through block.
646 EmitBlock(LoopExit.getBlock(), true);
647 }
648
EmitCXXForRangeStmt(const CXXForRangeStmt & S)649 void CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S) {
650 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
651
652 RunCleanupsScope ForScope(*this);
653
654 CGDebugInfo *DI = getDebugInfo();
655 if (DI) {
656 DI->setLocation(S.getSourceRange().getBegin());
657 DI->EmitRegionStart(Builder);
658 }
659
660 // Evaluate the first pieces before the loop.
661 EmitStmt(S.getRangeStmt());
662 EmitStmt(S.getBeginEndStmt());
663
664 // Start the loop with a block that tests the condition.
665 // If there's an increment, the continue scope will be overwritten
666 // later.
667 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
668 EmitBlock(CondBlock);
669
670 // If there are any cleanups between here and the loop-exit scope,
671 // create a block to stage a loop exit along.
672 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
673 if (ForScope.requiresCleanups())
674 ExitBlock = createBasicBlock("for.cond.cleanup");
675
676 // The loop body, consisting of the specified body and the loop variable.
677 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
678
679 // The body is executed if the expression, contextually converted
680 // to bool, is true.
681 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
682 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
683
684 if (ExitBlock != LoopExit.getBlock()) {
685 EmitBlock(ExitBlock);
686 EmitBranchThroughCleanup(LoopExit);
687 }
688
689 EmitBlock(ForBody);
690
691 // Create a block for the increment. In case of a 'continue', we jump there.
692 JumpDest Continue = getJumpDestInCurrentScope("for.inc");
693
694 // Store the blocks to use for break and continue.
695 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
696
697 {
698 // Create a separate cleanup scope for the loop variable and body.
699 RunCleanupsScope BodyScope(*this);
700 EmitStmt(S.getLoopVarStmt());
701 EmitStmt(S.getBody());
702 }
703
704 // If there is an increment, emit it next.
705 EmitBlock(Continue.getBlock());
706 EmitStmt(S.getInc());
707
708 BreakContinueStack.pop_back();
709
710 EmitBranch(CondBlock);
711
712 ForScope.ForceCleanup();
713
714 if (DI) {
715 DI->setLocation(S.getSourceRange().getEnd());
716 DI->EmitRegionEnd(Builder);
717 }
718
719 // Emit the fall-through block.
720 EmitBlock(LoopExit.getBlock(), true);
721 }
722
EmitReturnOfRValue(RValue RV,QualType Ty)723 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
724 if (RV.isScalar()) {
725 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
726 } else if (RV.isAggregate()) {
727 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
728 } else {
729 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
730 }
731 EmitBranchThroughCleanup(ReturnBlock);
732 }
733
734 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
735 /// if the function returns void, or may be missing one if the function returns
736 /// non-void. Fun stuff :).
EmitReturnStmt(const ReturnStmt & S)737 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
738 // Emit the result value, even if unused, to evalute the side effects.
739 const Expr *RV = S.getRetValue();
740
741 // FIXME: Clean this up by using an LValue for ReturnTemp,
742 // EmitStoreThroughLValue, and EmitAnyExpr.
743 if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable() &&
744 !Target.useGlobalsForAutomaticVariables()) {
745 // Apply the named return value optimization for this return statement,
746 // which means doing nothing: the appropriate result has already been
747 // constructed into the NRVO variable.
748
749 // If there is an NRVO flag for this variable, set it to 1 into indicate
750 // that the cleanup code should not destroy the variable.
751 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
752 Builder.CreateStore(Builder.getTrue(), NRVOFlag);
753 } else if (!ReturnValue) {
754 // Make sure not to return anything, but evaluate the expression
755 // for side effects.
756 if (RV)
757 EmitAnyExpr(RV);
758 } else if (RV == 0) {
759 // Do nothing (return value is left uninitialized)
760 } else if (FnRetTy->isReferenceType()) {
761 // If this function returns a reference, take the address of the expression
762 // rather than the value.
763 RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0);
764 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
765 } else if (!hasAggregateLLVMType(RV->getType())) {
766 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
767 } else if (RV->getType()->isAnyComplexType()) {
768 EmitComplexExprIntoAddr(RV, ReturnValue, false);
769 } else {
770 EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Qualifiers(), true));
771 }
772
773 EmitBranchThroughCleanup(ReturnBlock);
774 }
775
EmitDeclStmt(const DeclStmt & S)776 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
777 // As long as debug info is modeled with instructions, we have to ensure we
778 // have a place to insert here and write the stop point here.
779 if (getDebugInfo() && HaveInsertPoint())
780 EmitStopPoint(&S);
781
782 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
783 I != E; ++I)
784 EmitDecl(**I);
785 }
786
EmitBreakStmt(const BreakStmt & S)787 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
788 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
789
790 // If this code is reachable then emit a stop point (if generating
791 // debug info). We have to do this ourselves because we are on the
792 // "simple" statement path.
793 if (HaveInsertPoint())
794 EmitStopPoint(&S);
795
796 JumpDest Block = BreakContinueStack.back().BreakBlock;
797 EmitBranchThroughCleanup(Block);
798 }
799
EmitContinueStmt(const ContinueStmt & S)800 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
801 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
802
803 // If this code is reachable then emit a stop point (if generating
804 // debug info). We have to do this ourselves because we are on the
805 // "simple" statement path.
806 if (HaveInsertPoint())
807 EmitStopPoint(&S);
808
809 JumpDest Block = BreakContinueStack.back().ContinueBlock;
810 EmitBranchThroughCleanup(Block);
811 }
812
813 /// EmitCaseStmtRange - If case statement range is not too big then
814 /// add multiple cases to switch instruction, one for each value within
815 /// the range. If range is too big then emit "if" condition check.
EmitCaseStmtRange(const CaseStmt & S)816 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
817 assert(S.getRHS() && "Expected RHS value in CaseStmt");
818
819 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
820 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
821
822 // Emit the code for this case. We do this first to make sure it is
823 // properly chained from our predecessor before generating the
824 // switch machinery to enter this block.
825 EmitBlock(createBasicBlock("sw.bb"));
826 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
827 EmitStmt(S.getSubStmt());
828
829 // If range is empty, do nothing.
830 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
831 return;
832
833 llvm::APInt Range = RHS - LHS;
834 // FIXME: parameters such as this should not be hardcoded.
835 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
836 // Range is small enough to add multiple switch instruction cases.
837 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
838 SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
839 LHS++;
840 }
841 return;
842 }
843
844 // The range is too big. Emit "if" condition into a new block,
845 // making sure to save and restore the current insertion point.
846 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
847
848 // Push this test onto the chain of range checks (which terminates
849 // in the default basic block). The switch's default will be changed
850 // to the top of this chain after switch emission is complete.
851 llvm::BasicBlock *FalseDest = CaseRangeBlock;
852 CaseRangeBlock = createBasicBlock("sw.caserange");
853
854 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
855 Builder.SetInsertPoint(CaseRangeBlock);
856
857 // Emit range check.
858 llvm::Value *Diff =
859 Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS), "tmp");
860 llvm::Value *Cond =
861 Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
862 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
863
864 // Restore the appropriate insertion point.
865 if (RestoreBB)
866 Builder.SetInsertPoint(RestoreBB);
867 else
868 Builder.ClearInsertionPoint();
869 }
870
EmitCaseStmt(const CaseStmt & S)871 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
872 // Handle case ranges.
873 if (S.getRHS()) {
874 EmitCaseStmtRange(S);
875 return;
876 }
877
878 llvm::ConstantInt *CaseVal =
879 Builder.getInt(S.getLHS()->EvaluateAsInt(getContext()));
880
881 // If the body of the case is just a 'break', and if there was no fallthrough,
882 // try to not emit an empty block.
883 if (isa<BreakStmt>(S.getSubStmt())) {
884 JumpDest Block = BreakContinueStack.back().BreakBlock;
885
886 // Only do this optimization if there are no cleanups that need emitting.
887 if (isObviouslyBranchWithoutCleanups(Block)) {
888 SwitchInsn->addCase(CaseVal, Block.getBlock());
889
890 // If there was a fallthrough into this case, make sure to redirect it to
891 // the end of the switch as well.
892 if (Builder.GetInsertBlock()) {
893 Builder.CreateBr(Block.getBlock());
894 Builder.ClearInsertionPoint();
895 }
896 return;
897 }
898 }
899
900 EmitBlock(createBasicBlock("sw.bb"));
901 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
902 SwitchInsn->addCase(CaseVal, CaseDest);
903
904 // Recursively emitting the statement is acceptable, but is not wonderful for
905 // code where we have many case statements nested together, i.e.:
906 // case 1:
907 // case 2:
908 // case 3: etc.
909 // Handling this recursively will create a new block for each case statement
910 // that falls through to the next case which is IR intensive. It also causes
911 // deep recursion which can run into stack depth limitations. Handle
912 // sequential non-range case statements specially.
913 const CaseStmt *CurCase = &S;
914 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
915
916 // Otherwise, iteratively add consecutive cases to this switch stmt.
917 while (NextCase && NextCase->getRHS() == 0) {
918 CurCase = NextCase;
919 llvm::ConstantInt *CaseVal =
920 Builder.getInt(CurCase->getLHS()->EvaluateAsInt(getContext()));
921 SwitchInsn->addCase(CaseVal, CaseDest);
922 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
923 }
924
925 // Normal default recursion for non-cases.
926 EmitStmt(CurCase->getSubStmt());
927 }
928
EmitDefaultStmt(const DefaultStmt & S)929 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
930 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
931 assert(DefaultBlock->empty() &&
932 "EmitDefaultStmt: Default block already defined?");
933 EmitBlock(DefaultBlock);
934 EmitStmt(S.getSubStmt());
935 }
936
937 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
938 /// constant value that is being switched on, see if we can dead code eliminate
939 /// the body of the switch to a simple series of statements to emit. Basically,
940 /// on a switch (5) we want to find these statements:
941 /// case 5:
942 /// printf(...); <--
943 /// ++i; <--
944 /// break;
945 ///
946 /// and add them to the ResultStmts vector. If it is unsafe to do this
947 /// transformation (for example, one of the elided statements contains a label
948 /// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
949 /// should include statements after it (e.g. the printf() line is a substmt of
950 /// the case) then return CSFC_FallThrough. If we handled it and found a break
951 /// statement, then return CSFC_Success.
952 ///
953 /// If Case is non-null, then we are looking for the specified case, checking
954 /// that nothing we jump over contains labels. If Case is null, then we found
955 /// the case and are looking for the break.
956 ///
957 /// If the recursive walk actually finds our Case, then we set FoundCase to
958 /// true.
959 ///
960 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
CollectStatementsForCase(const Stmt * S,const SwitchCase * Case,bool & FoundCase,llvm::SmallVectorImpl<const Stmt * > & ResultStmts)961 static CSFC_Result CollectStatementsForCase(const Stmt *S,
962 const SwitchCase *Case,
963 bool &FoundCase,
964 llvm::SmallVectorImpl<const Stmt*> &ResultStmts) {
965 // If this is a null statement, just succeed.
966 if (S == 0)
967 return Case ? CSFC_Success : CSFC_FallThrough;
968
969 // If this is the switchcase (case 4: or default) that we're looking for, then
970 // we're in business. Just add the substatement.
971 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
972 if (S == Case) {
973 FoundCase = true;
974 return CollectStatementsForCase(SC->getSubStmt(), 0, FoundCase,
975 ResultStmts);
976 }
977
978 // Otherwise, this is some other case or default statement, just ignore it.
979 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
980 ResultStmts);
981 }
982
983 // If we are in the live part of the code and we found our break statement,
984 // return a success!
985 if (Case == 0 && isa<BreakStmt>(S))
986 return CSFC_Success;
987
988 // If this is a switch statement, then it might contain the SwitchCase, the
989 // break, or neither.
990 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
991 // Handle this as two cases: we might be looking for the SwitchCase (if so
992 // the skipped statements must be skippable) or we might already have it.
993 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
994 if (Case) {
995 // Keep track of whether we see a skipped declaration. The code could be
996 // using the declaration even if it is skipped, so we can't optimize out
997 // the decl if the kept statements might refer to it.
998 bool HadSkippedDecl = false;
999
1000 // If we're looking for the case, just see if we can skip each of the
1001 // substatements.
1002 for (; Case && I != E; ++I) {
1003 HadSkippedDecl |= isa<DeclStmt>(*I);
1004
1005 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1006 case CSFC_Failure: return CSFC_Failure;
1007 case CSFC_Success:
1008 // A successful result means that either 1) that the statement doesn't
1009 // have the case and is skippable, or 2) does contain the case value
1010 // and also contains the break to exit the switch. In the later case,
1011 // we just verify the rest of the statements are elidable.
1012 if (FoundCase) {
1013 // If we found the case and skipped declarations, we can't do the
1014 // optimization.
1015 if (HadSkippedDecl)
1016 return CSFC_Failure;
1017
1018 for (++I; I != E; ++I)
1019 if (CodeGenFunction::ContainsLabel(*I, true))
1020 return CSFC_Failure;
1021 return CSFC_Success;
1022 }
1023 break;
1024 case CSFC_FallThrough:
1025 // If we have a fallthrough condition, then we must have found the
1026 // case started to include statements. Consider the rest of the
1027 // statements in the compound statement as candidates for inclusion.
1028 assert(FoundCase && "Didn't find case but returned fallthrough?");
1029 // We recursively found Case, so we're not looking for it anymore.
1030 Case = 0;
1031
1032 // If we found the case and skipped declarations, we can't do the
1033 // optimization.
1034 if (HadSkippedDecl)
1035 return CSFC_Failure;
1036 break;
1037 }
1038 }
1039 }
1040
1041 // If we have statements in our range, then we know that the statements are
1042 // live and need to be added to the set of statements we're tracking.
1043 for (; I != E; ++I) {
1044 switch (CollectStatementsForCase(*I, 0, FoundCase, ResultStmts)) {
1045 case CSFC_Failure: return CSFC_Failure;
1046 case CSFC_FallThrough:
1047 // A fallthrough result means that the statement was simple and just
1048 // included in ResultStmt, keep adding them afterwards.
1049 break;
1050 case CSFC_Success:
1051 // A successful result means that we found the break statement and
1052 // stopped statement inclusion. We just ensure that any leftover stmts
1053 // are skippable and return success ourselves.
1054 for (++I; I != E; ++I)
1055 if (CodeGenFunction::ContainsLabel(*I, true))
1056 return CSFC_Failure;
1057 return CSFC_Success;
1058 }
1059 }
1060
1061 return Case ? CSFC_Success : CSFC_FallThrough;
1062 }
1063
1064 // Okay, this is some other statement that we don't handle explicitly, like a
1065 // for statement or increment etc. If we are skipping over this statement,
1066 // just verify it doesn't have labels, which would make it invalid to elide.
1067 if (Case) {
1068 if (CodeGenFunction::ContainsLabel(S, true))
1069 return CSFC_Failure;
1070 return CSFC_Success;
1071 }
1072
1073 // Otherwise, we want to include this statement. Everything is cool with that
1074 // so long as it doesn't contain a break out of the switch we're in.
1075 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1076
1077 // Otherwise, everything is great. Include the statement and tell the caller
1078 // that we fall through and include the next statement as well.
1079 ResultStmts.push_back(S);
1080 return CSFC_FallThrough;
1081 }
1082
1083 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1084 /// then invoke CollectStatementsForCase to find the list of statements to emit
1085 /// for a switch on constant. See the comment above CollectStatementsForCase
1086 /// for more details.
FindCaseStatementsForValue(const SwitchStmt & S,const llvm::APInt & ConstantCondValue,llvm::SmallVectorImpl<const Stmt * > & ResultStmts,ASTContext & C)1087 static bool FindCaseStatementsForValue(const SwitchStmt &S,
1088 const llvm::APInt &ConstantCondValue,
1089 llvm::SmallVectorImpl<const Stmt*> &ResultStmts,
1090 ASTContext &C) {
1091 // First step, find the switch case that is being branched to. We can do this
1092 // efficiently by scanning the SwitchCase list.
1093 const SwitchCase *Case = S.getSwitchCaseList();
1094 const DefaultStmt *DefaultCase = 0;
1095
1096 for (; Case; Case = Case->getNextSwitchCase()) {
1097 // It's either a default or case. Just remember the default statement in
1098 // case we're not jumping to any numbered cases.
1099 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1100 DefaultCase = DS;
1101 continue;
1102 }
1103
1104 // Check to see if this case is the one we're looking for.
1105 const CaseStmt *CS = cast<CaseStmt>(Case);
1106 // Don't handle case ranges yet.
1107 if (CS->getRHS()) return false;
1108
1109 // If we found our case, remember it as 'case'.
1110 if (CS->getLHS()->EvaluateAsInt(C) == ConstantCondValue)
1111 break;
1112 }
1113
1114 // If we didn't find a matching case, we use a default if it exists, or we
1115 // elide the whole switch body!
1116 if (Case == 0) {
1117 // It is safe to elide the body of the switch if it doesn't contain labels
1118 // etc. If it is safe, return successfully with an empty ResultStmts list.
1119 if (DefaultCase == 0)
1120 return !CodeGenFunction::ContainsLabel(&S);
1121 Case = DefaultCase;
1122 }
1123
1124 // Ok, we know which case is being jumped to, try to collect all the
1125 // statements that follow it. This can fail for a variety of reasons. Also,
1126 // check to see that the recursive walk actually found our case statement.
1127 // Insane cases like this can fail to find it in the recursive walk since we
1128 // don't handle every stmt kind:
1129 // switch (4) {
1130 // while (1) {
1131 // case 4: ...
1132 bool FoundCase = false;
1133 return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1134 ResultStmts) != CSFC_Failure &&
1135 FoundCase;
1136 }
1137
EmitSwitchStmt(const SwitchStmt & S)1138 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1139 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1140
1141 RunCleanupsScope ConditionScope(*this);
1142
1143 if (S.getConditionVariable())
1144 EmitAutoVarDecl(*S.getConditionVariable());
1145
1146 // See if we can constant fold the condition of the switch and therefore only
1147 // emit the live case statement (if any) of the switch.
1148 llvm::APInt ConstantCondValue;
1149 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1150 llvm::SmallVector<const Stmt*, 4> CaseStmts;
1151 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1152 getContext())) {
1153 RunCleanupsScope ExecutedScope(*this);
1154
1155 // Okay, we can dead code eliminate everything except this case. Emit the
1156 // specified series of statements and we're good.
1157 for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1158 EmitStmt(CaseStmts[i]);
1159 return;
1160 }
1161 }
1162
1163 llvm::Value *CondV = EmitScalarExpr(S.getCond());
1164
1165 // Handle nested switch statements.
1166 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1167 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1168
1169 // Create basic block to hold stuff that comes after switch
1170 // statement. We also need to create a default block now so that
1171 // explicit case ranges tests can have a place to jump to on
1172 // failure.
1173 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1174 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1175 CaseRangeBlock = DefaultBlock;
1176
1177 // Clear the insertion point to indicate we are in unreachable code.
1178 Builder.ClearInsertionPoint();
1179
1180 // All break statements jump to NextBlock. If BreakContinueStack is non empty
1181 // then reuse last ContinueBlock.
1182 JumpDest OuterContinue;
1183 if (!BreakContinueStack.empty())
1184 OuterContinue = BreakContinueStack.back().ContinueBlock;
1185
1186 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1187
1188 // Emit switch body.
1189 EmitStmt(S.getBody());
1190
1191 BreakContinueStack.pop_back();
1192
1193 // Update the default block in case explicit case range tests have
1194 // been chained on top.
1195 SwitchInsn->setSuccessor(0, CaseRangeBlock);
1196
1197 // If a default was never emitted:
1198 if (!DefaultBlock->getParent()) {
1199 // If we have cleanups, emit the default block so that there's a
1200 // place to jump through the cleanups from.
1201 if (ConditionScope.requiresCleanups()) {
1202 EmitBlock(DefaultBlock);
1203
1204 // Otherwise, just forward the default block to the switch end.
1205 } else {
1206 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1207 delete DefaultBlock;
1208 }
1209 }
1210
1211 ConditionScope.ForceCleanup();
1212
1213 // Emit continuation.
1214 EmitBlock(SwitchExit.getBlock(), true);
1215
1216 SwitchInsn = SavedSwitchInsn;
1217 CaseRangeBlock = SavedCRBlock;
1218 }
1219
1220 static std::string
SimplifyConstraint(const char * Constraint,const TargetInfo & Target,llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> * OutCons=0)1221 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1222 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
1223 std::string Result;
1224
1225 while (*Constraint) {
1226 switch (*Constraint) {
1227 default:
1228 Result += Target.convertConstraint(Constraint);
1229 break;
1230 // Ignore these
1231 case '*':
1232 case '?':
1233 case '!':
1234 case '=': // Will see this and the following in mult-alt constraints.
1235 case '+':
1236 break;
1237 case ',':
1238 Result += "|";
1239 break;
1240 case 'g':
1241 Result += "imr";
1242 break;
1243 case '[': {
1244 assert(OutCons &&
1245 "Must pass output names to constraints with a symbolic name");
1246 unsigned Index;
1247 bool result = Target.resolveSymbolicName(Constraint,
1248 &(*OutCons)[0],
1249 OutCons->size(), Index);
1250 assert(result && "Could not resolve symbolic name"); (void)result;
1251 Result += llvm::utostr(Index);
1252 break;
1253 }
1254 }
1255
1256 Constraint++;
1257 }
1258
1259 return Result;
1260 }
1261
1262 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1263 /// as using a particular register add that as a constraint that will be used
1264 /// in this asm stmt.
1265 static std::string
AddVariableConstraints(const std::string & Constraint,const Expr & AsmExpr,const TargetInfo & Target,CodeGenModule & CGM,const AsmStmt & Stmt)1266 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1267 const TargetInfo &Target, CodeGenModule &CGM,
1268 const AsmStmt &Stmt) {
1269 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1270 if (!AsmDeclRef)
1271 return Constraint;
1272 const ValueDecl &Value = *AsmDeclRef->getDecl();
1273 const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1274 if (!Variable)
1275 return Constraint;
1276 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1277 if (!Attr)
1278 return Constraint;
1279 llvm::StringRef Register = Attr->getLabel();
1280 assert(Target.isValidGCCRegisterName(Register));
1281 // We're using validateOutputConstraint here because we only care if
1282 // this is a register constraint.
1283 TargetInfo::ConstraintInfo Info(Constraint, "");
1284 if (Target.validateOutputConstraint(Info) &&
1285 !Info.allowsRegister()) {
1286 CGM.ErrorUnsupported(&Stmt, "__asm__");
1287 return Constraint;
1288 }
1289 // Canonicalize the register here before returning it.
1290 Register = Target.getNormalizedGCCRegisterName(Register);
1291 return "{" + Register.str() + "}";
1292 }
1293
1294 llvm::Value*
EmitAsmInputLValue(const AsmStmt & S,const TargetInfo::ConstraintInfo & Info,LValue InputValue,QualType InputType,std::string & ConstraintStr)1295 CodeGenFunction::EmitAsmInputLValue(const AsmStmt &S,
1296 const TargetInfo::ConstraintInfo &Info,
1297 LValue InputValue, QualType InputType,
1298 std::string &ConstraintStr) {
1299 llvm::Value *Arg;
1300 if (Info.allowsRegister() || !Info.allowsMemory()) {
1301 if (!CodeGenFunction::hasAggregateLLVMType(InputType)) {
1302 Arg = EmitLoadOfLValue(InputValue).getScalarVal();
1303 } else {
1304 llvm::Type *Ty = ConvertType(InputType);
1305 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
1306 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1307 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1308 Ty = llvm::PointerType::getUnqual(Ty);
1309
1310 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1311 Ty));
1312 } else {
1313 Arg = InputValue.getAddress();
1314 ConstraintStr += '*';
1315 }
1316 }
1317 } else {
1318 Arg = InputValue.getAddress();
1319 ConstraintStr += '*';
1320 }
1321
1322 return Arg;
1323 }
1324
EmitAsmInput(const AsmStmt & S,const TargetInfo::ConstraintInfo & Info,const Expr * InputExpr,std::string & ConstraintStr)1325 llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
1326 const TargetInfo::ConstraintInfo &Info,
1327 const Expr *InputExpr,
1328 std::string &ConstraintStr) {
1329 if (Info.allowsRegister() || !Info.allowsMemory())
1330 if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType()))
1331 return EmitScalarExpr(InputExpr);
1332
1333 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1334 LValue Dest = EmitLValue(InputExpr);
1335 return EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(), ConstraintStr);
1336 }
1337
1338 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1339 /// asm call instruction. The !srcloc MDNode contains a list of constant
1340 /// integers which are the source locations of the start of each line in the
1341 /// asm.
getAsmSrcLocInfo(const StringLiteral * Str,CodeGenFunction & CGF)1342 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1343 CodeGenFunction &CGF) {
1344 llvm::SmallVector<llvm::Value *, 8> Locs;
1345 // Add the location of the first line to the MDNode.
1346 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1347 Str->getLocStart().getRawEncoding()));
1348 llvm::StringRef StrVal = Str->getString();
1349 if (!StrVal.empty()) {
1350 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1351 const LangOptions &LangOpts = CGF.CGM.getLangOptions();
1352
1353 // Add the location of the start of each subsequent line of the asm to the
1354 // MDNode.
1355 for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
1356 if (StrVal[i] != '\n') continue;
1357 SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
1358 CGF.Target);
1359 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1360 LineLoc.getRawEncoding()));
1361 }
1362 }
1363
1364 return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1365 }
1366
EmitAsmStmt(const AsmStmt & S)1367 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1368 // Analyze the asm string to decompose it into its pieces. We know that Sema
1369 // has already done this, so it is guaranteed to be successful.
1370 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
1371 unsigned DiagOffs;
1372 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
1373
1374 // Assemble the pieces into the final asm string.
1375 std::string AsmString;
1376 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
1377 if (Pieces[i].isString())
1378 AsmString += Pieces[i].getString();
1379 else if (Pieces[i].getModifier() == '\0')
1380 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
1381 else
1382 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
1383 Pieces[i].getModifier() + '}';
1384 }
1385
1386 // Get all the output and input constraints together.
1387 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1388 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1389
1390 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1391 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
1392 S.getOutputName(i));
1393 bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
1394 assert(IsValid && "Failed to parse output constraint");
1395 OutputConstraintInfos.push_back(Info);
1396 }
1397
1398 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1399 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
1400 S.getInputName(i));
1401 bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
1402 S.getNumOutputs(), Info);
1403 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1404 InputConstraintInfos.push_back(Info);
1405 }
1406
1407 std::string Constraints;
1408
1409 std::vector<LValue> ResultRegDests;
1410 std::vector<QualType> ResultRegQualTys;
1411 std::vector<llvm::Type *> ResultRegTypes;
1412 std::vector<llvm::Type *> ResultTruncRegTypes;
1413 std::vector<llvm::Type*> ArgTypes;
1414 std::vector<llvm::Value*> Args;
1415
1416 // Keep track of inout constraints.
1417 std::string InOutConstraints;
1418 std::vector<llvm::Value*> InOutArgs;
1419 std::vector<llvm::Type*> InOutArgTypes;
1420
1421 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1422 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1423
1424 // Simplify the output constraint.
1425 std::string OutputConstraint(S.getOutputConstraint(i));
1426 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
1427
1428 const Expr *OutExpr = S.getOutputExpr(i);
1429 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1430
1431 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1432 Target, CGM, S);
1433
1434 LValue Dest = EmitLValue(OutExpr);
1435 if (!Constraints.empty())
1436 Constraints += ',';
1437
1438 // If this is a register output, then make the inline asm return it
1439 // by-value. If this is a memory result, return the value by-reference.
1440 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
1441 Constraints += "=" + OutputConstraint;
1442 ResultRegQualTys.push_back(OutExpr->getType());
1443 ResultRegDests.push_back(Dest);
1444 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1445 ResultTruncRegTypes.push_back(ResultRegTypes.back());
1446
1447 // If this output is tied to an input, and if the input is larger, then
1448 // we need to set the actual result type of the inline asm node to be the
1449 // same as the input type.
1450 if (Info.hasMatchingInput()) {
1451 unsigned InputNo;
1452 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1453 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1454 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1455 break;
1456 }
1457 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1458
1459 QualType InputTy = S.getInputExpr(InputNo)->getType();
1460 QualType OutputType = OutExpr->getType();
1461
1462 uint64_t InputSize = getContext().getTypeSize(InputTy);
1463 if (getContext().getTypeSize(OutputType) < InputSize) {
1464 // Form the asm to return the value as a larger integer or fp type.
1465 ResultRegTypes.back() = ConvertType(InputTy);
1466 }
1467 }
1468 if (llvm::Type* AdjTy =
1469 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1470 ResultRegTypes.back()))
1471 ResultRegTypes.back() = AdjTy;
1472 } else {
1473 ArgTypes.push_back(Dest.getAddress()->getType());
1474 Args.push_back(Dest.getAddress());
1475 Constraints += "=*";
1476 Constraints += OutputConstraint;
1477 }
1478
1479 if (Info.isReadWrite()) {
1480 InOutConstraints += ',';
1481
1482 const Expr *InputExpr = S.getOutputExpr(i);
1483 llvm::Value *Arg = EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(),
1484 InOutConstraints);
1485
1486 if (Info.allowsRegister())
1487 InOutConstraints += llvm::utostr(i);
1488 else
1489 InOutConstraints += OutputConstraint;
1490
1491 InOutArgTypes.push_back(Arg->getType());
1492 InOutArgs.push_back(Arg);
1493 }
1494 }
1495
1496 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1497
1498 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1499 const Expr *InputExpr = S.getInputExpr(i);
1500
1501 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1502
1503 if (!Constraints.empty())
1504 Constraints += ',';
1505
1506 // Simplify the input constraint.
1507 std::string InputConstraint(S.getInputConstraint(i));
1508 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
1509 &OutputConstraintInfos);
1510
1511 InputConstraint =
1512 AddVariableConstraints(InputConstraint,
1513 *InputExpr->IgnoreParenNoopCasts(getContext()),
1514 Target, CGM, S);
1515
1516 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
1517
1518 // If this input argument is tied to a larger output result, extend the
1519 // input to be the same size as the output. The LLVM backend wants to see
1520 // the input and output of a matching constraint be the same size. Note
1521 // that GCC does not define what the top bits are here. We use zext because
1522 // that is usually cheaper, but LLVM IR should really get an anyext someday.
1523 if (Info.hasTiedOperand()) {
1524 unsigned Output = Info.getTiedOperand();
1525 QualType OutputType = S.getOutputExpr(Output)->getType();
1526 QualType InputTy = InputExpr->getType();
1527
1528 if (getContext().getTypeSize(OutputType) >
1529 getContext().getTypeSize(InputTy)) {
1530 // Use ptrtoint as appropriate so that we can do our extension.
1531 if (isa<llvm::PointerType>(Arg->getType()))
1532 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
1533 llvm::Type *OutputTy = ConvertType(OutputType);
1534 if (isa<llvm::IntegerType>(OutputTy))
1535 Arg = Builder.CreateZExt(Arg, OutputTy);
1536 else
1537 Arg = Builder.CreateFPExt(Arg, OutputTy);
1538 }
1539 }
1540 if (llvm::Type* AdjTy =
1541 getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
1542 Arg->getType()))
1543 Arg = Builder.CreateBitCast(Arg, AdjTy);
1544
1545 ArgTypes.push_back(Arg->getType());
1546 Args.push_back(Arg);
1547 Constraints += InputConstraint;
1548 }
1549
1550 // Append the "input" part of inout constraints last.
1551 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1552 ArgTypes.push_back(InOutArgTypes[i]);
1553 Args.push_back(InOutArgs[i]);
1554 }
1555 Constraints += InOutConstraints;
1556
1557 // Clobbers
1558 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1559 llvm::StringRef Clobber = S.getClobber(i)->getString();
1560
1561 if (Clobber != "memory" && Clobber != "cc")
1562 Clobber = Target.getNormalizedGCCRegisterName(Clobber);
1563
1564 if (i != 0 || NumConstraints != 0)
1565 Constraints += ',';
1566
1567 Constraints += "~{";
1568 Constraints += Clobber;
1569 Constraints += '}';
1570 }
1571
1572 // Add machine specific clobbers
1573 std::string MachineClobbers = Target.getClobbers();
1574 if (!MachineClobbers.empty()) {
1575 if (!Constraints.empty())
1576 Constraints += ',';
1577 Constraints += MachineClobbers;
1578 }
1579
1580 llvm::Type *ResultType;
1581 if (ResultRegTypes.empty())
1582 ResultType = llvm::Type::getVoidTy(getLLVMContext());
1583 else if (ResultRegTypes.size() == 1)
1584 ResultType = ResultRegTypes[0];
1585 else
1586 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
1587
1588 llvm::FunctionType *FTy =
1589 llvm::FunctionType::get(ResultType, ArgTypes, false);
1590
1591 llvm::InlineAsm *IA =
1592 llvm::InlineAsm::get(FTy, AsmString, Constraints,
1593 S.isVolatile() || S.getNumOutputs() == 0);
1594 llvm::CallInst *Result = Builder.CreateCall(IA, Args);
1595 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
1596
1597 // Slap the source location of the inline asm into a !srcloc metadata on the
1598 // call.
1599 Result->setMetadata("srcloc", getAsmSrcLocInfo(S.getAsmString(), *this));
1600
1601 // Extract all of the register value results from the asm.
1602 std::vector<llvm::Value*> RegResults;
1603 if (ResultRegTypes.size() == 1) {
1604 RegResults.push_back(Result);
1605 } else {
1606 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
1607 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
1608 RegResults.push_back(Tmp);
1609 }
1610 }
1611
1612 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1613 llvm::Value *Tmp = RegResults[i];
1614
1615 // If the result type of the LLVM IR asm doesn't match the result type of
1616 // the expression, do the conversion.
1617 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1618 llvm::Type *TruncTy = ResultTruncRegTypes[i];
1619
1620 // Truncate the integer result to the right size, note that TruncTy can be
1621 // a pointer.
1622 if (TruncTy->isFloatingPointTy())
1623 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
1624 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
1625 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
1626 Tmp = Builder.CreateTrunc(Tmp,
1627 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
1628 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
1629 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1630 uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType());
1631 Tmp = Builder.CreatePtrToInt(Tmp,
1632 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
1633 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1634 } else if (TruncTy->isIntegerTy()) {
1635 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1636 } else if (TruncTy->isVectorTy()) {
1637 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
1638 }
1639 }
1640
1641 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
1642 }
1643 }
1644