1193326Sed//===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===// 2193326Sed// 3193326Sed// The LLVM Compiler Infrastructure 4193326Sed// 5193326Sed// This file is distributed under the University of Illinois Open Source 6193326Sed// License. See LICENSE.TXT for details. 7193326Sed// 8193326Sed//===----------------------------------------------------------------------===// 9193326Sed// 10193326Sed// This contains code to emit Stmt nodes as LLVM code. 11193326Sed// 12193326Sed//===----------------------------------------------------------------------===// 13193326Sed 14252723Sdim#include "CodeGenFunction.h" 15193326Sed#include "CGDebugInfo.h" 16193326Sed#include "CodeGenModule.h" 17218893Sdim#include "TargetInfo.h" 18193326Sed#include "clang/AST/StmtVisitor.h" 19263509Sdim#include "clang/Sema/SemaDiagnostic.h" 20193326Sed#include "clang/Basic/PrettyStackTrace.h" 21193326Sed#include "clang/Basic/TargetInfo.h" 22193326Sed#include "llvm/ADT/StringExtras.h" 23252723Sdim#include "llvm/IR/DataLayout.h" 24252723Sdim#include "llvm/IR/InlineAsm.h" 25252723Sdim#include "llvm/IR/Intrinsics.h" 26263509Sdim#include "llvm/Support/CallSite.h" 27193326Sedusing namespace clang; 28193326Sedusing namespace CodeGen; 29193326Sed 30193326Sed//===----------------------------------------------------------------------===// 31193326Sed// Statement Emission 32193326Sed//===----------------------------------------------------------------------===// 33193326Sed 34193326Sedvoid CodeGenFunction::EmitStopPoint(const Stmt *S) { 35193326Sed if (CGDebugInfo *DI = getDebugInfo()) { 36226890Sdim SourceLocation Loc; 37263509Sdim Loc = S->getLocStart(); 38226890Sdim DI->EmitLocation(Builder, Loc); 39252723Sdim 40263509Sdim LastStopPoint = Loc; 41193326Sed } 42193326Sed} 43193326Sed 44193326Sedvoid CodeGenFunction::EmitStmt(const Stmt *S) { 45193326Sed assert(S && "Null statement?"); 46193326Sed 47226890Sdim // These statements have their own debug info handling. 48193326Sed if (EmitSimpleStmt(S)) 49193326Sed return; 50193326Sed 51198092Srdivacky // Check if we are generating unreachable code. 52198092Srdivacky if (!HaveInsertPoint()) { 53198092Srdivacky // If so, and the statement doesn't contain a label, then we do not need to 54198092Srdivacky // generate actual code. This is safe because (1) the current point is 55198092Srdivacky // unreachable, so we don't need to execute the code, and (2) we've already 56198092Srdivacky // handled the statements which update internal data structures (like the 57198092Srdivacky // local variable map) which could be used by subsequent statements. 58198092Srdivacky if (!ContainsLabel(S)) { 59198092Srdivacky // Verify that any decl statements were handled as simple, they may be in 60198092Srdivacky // scope of subsequent reachable statements. 61198092Srdivacky assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!"); 62198092Srdivacky return; 63198092Srdivacky } 64198092Srdivacky 65198092Srdivacky // Otherwise, make a new block to hold the code. 66198092Srdivacky EnsureInsertPoint(); 67198092Srdivacky } 68198092Srdivacky 69193326Sed // Generate a stoppoint if we are emitting debug info. 70193326Sed EmitStopPoint(S); 71193326Sed 72193326Sed switch (S->getStmtClass()) { 73218893Sdim case Stmt::NoStmtClass: 74218893Sdim case Stmt::CXXCatchStmtClass: 75221345Sdim case Stmt::SEHExceptStmtClass: 76221345Sdim case Stmt::SEHFinallyStmtClass: 77235633Sdim case Stmt::MSDependentExistsStmtClass: 78263509Sdim case Stmt::OMPParallelDirectiveClass: 79218893Sdim llvm_unreachable("invalid statement class to emit generically"); 80218893Sdim case Stmt::NullStmtClass: 81218893Sdim case Stmt::CompoundStmtClass: 82218893Sdim case Stmt::DeclStmtClass: 83218893Sdim case Stmt::LabelStmtClass: 84235633Sdim case Stmt::AttributedStmtClass: 85218893Sdim case Stmt::GotoStmtClass: 86218893Sdim case Stmt::BreakStmtClass: 87218893Sdim case Stmt::ContinueStmtClass: 88218893Sdim case Stmt::DefaultStmtClass: 89218893Sdim case Stmt::CaseStmtClass: 90218893Sdim llvm_unreachable("should have emitted these statements as simple"); 91198092Srdivacky 92218893Sdim#define STMT(Type, Base) 93218893Sdim#define ABSTRACT_STMT(Op) 94218893Sdim#define EXPR(Type, Base) \ 95218893Sdim case Stmt::Type##Class: 96218893Sdim#include "clang/AST/StmtNodes.inc" 97218893Sdim { 98218893Sdim // Remember the block we came in on. 99218893Sdim llvm::BasicBlock *incoming = Builder.GetInsertBlock(); 100218893Sdim assert(incoming && "expression emission must have an insertion point"); 101198092Srdivacky 102218893Sdim EmitIgnoredExpr(cast<Expr>(S)); 103218893Sdim 104218893Sdim llvm::BasicBlock *outgoing = Builder.GetInsertBlock(); 105218893Sdim assert(outgoing && "expression emission cleared block!"); 106218893Sdim 107218893Sdim // The expression emitters assume (reasonably!) that the insertion 108218893Sdim // point is always set. To maintain that, the call-emission code 109218893Sdim // for noreturn functions has to enter a new block with no 110218893Sdim // predecessors. We want to kill that block and mark the current 111218893Sdim // insertion point unreachable in the common case of a call like 112218893Sdim // "exit();". Since expression emission doesn't otherwise create 113218893Sdim // blocks with no predecessors, we can just test for that. 114218893Sdim // However, we must be careful not to do this to our incoming 115218893Sdim // block, because *statement* emission does sometimes create 116218893Sdim // reachable blocks which will have no predecessors until later in 117218893Sdim // the function. This occurs with, e.g., labels that are not 118218893Sdim // reachable by fallthrough. 119218893Sdim if (incoming != outgoing && outgoing->use_empty()) { 120218893Sdim outgoing->eraseFromParent(); 121218893Sdim Builder.ClearInsertionPoint(); 122193326Sed } 123193326Sed break; 124218893Sdim } 125218893Sdim 126198092Srdivacky case Stmt::IndirectGotoStmtClass: 127193326Sed EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break; 128193326Sed 129193326Sed case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break; 130193326Sed case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break; 131193326Sed case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break; 132193326Sed case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break; 133198092Srdivacky 134193326Sed case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break; 135193326Sed 136193326Sed case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break; 137245431Sdim case Stmt::GCCAsmStmtClass: // Intentional fall-through. 138245431Sdim case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break; 139263509Sdim case Stmt::CapturedStmtClass: { 140263509Sdim const CapturedStmt *CS = cast<CapturedStmt>(S); 141263509Sdim EmitCapturedStmt(*CS, CS->getCapturedRegionKind()); 142263509Sdim } 143252723Sdim break; 144193326Sed case Stmt::ObjCAtTryStmtClass: 145193326Sed EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S)); 146198092Srdivacky break; 147193326Sed case Stmt::ObjCAtCatchStmtClass: 148226890Sdim llvm_unreachable( 149226890Sdim "@catch statements should be handled by EmitObjCAtTryStmt"); 150193326Sed case Stmt::ObjCAtFinallyStmtClass: 151226890Sdim llvm_unreachable( 152226890Sdim "@finally statements should be handled by EmitObjCAtTryStmt"); 153193326Sed case Stmt::ObjCAtThrowStmtClass: 154193326Sed EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S)); 155193326Sed break; 156193326Sed case Stmt::ObjCAtSynchronizedStmtClass: 157193326Sed EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S)); 158193326Sed break; 159198092Srdivacky case Stmt::ObjCForCollectionStmtClass: 160193326Sed EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S)); 161193326Sed break; 162224145Sdim case Stmt::ObjCAutoreleasePoolStmtClass: 163224145Sdim EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S)); 164224145Sdim break; 165245431Sdim 166198092Srdivacky case Stmt::CXXTryStmtClass: 167198092Srdivacky EmitCXXTryStmt(cast<CXXTryStmt>(*S)); 168198092Srdivacky break; 169221345Sdim case Stmt::CXXForRangeStmtClass: 170221345Sdim EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S)); 171263509Sdim break; 172221345Sdim case Stmt::SEHTryStmtClass: 173263509Sdim EmitSEHTryStmt(cast<SEHTryStmt>(*S)); 174221345Sdim break; 175193326Sed } 176193326Sed} 177193326Sed 178193326Sedbool CodeGenFunction::EmitSimpleStmt(const Stmt *S) { 179193326Sed switch (S->getStmtClass()) { 180193326Sed default: return false; 181193326Sed case Stmt::NullStmtClass: break; 182193326Sed case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break; 183198092Srdivacky case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break; 184193326Sed case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break; 185235633Sdim case Stmt::AttributedStmtClass: 186235633Sdim EmitAttributedStmt(cast<AttributedStmt>(*S)); break; 187193326Sed case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break; 188193326Sed case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break; 189193326Sed case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break; 190193326Sed case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break; 191193326Sed case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break; 192193326Sed } 193193326Sed 194193326Sed return true; 195193326Sed} 196193326Sed 197193326Sed/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true, 198193326Sed/// this captures the expression result of the last sub-statement and returns it 199193326Sed/// (for use by the statement expression extension). 200263509Sdimllvm::Value* CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast, 201263509Sdim AggValueSlot AggSlot) { 202193326Sed PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(), 203193326Sed "LLVM IR generation of compound statement ('{}')"); 204198092Srdivacky 205235633Sdim // Keep track of the current cleanup stack depth, including debug scopes. 206235633Sdim LexicalScope Scope(*this, S.getSourceRange()); 207193326Sed 208252723Sdim return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot); 209252723Sdim} 210252723Sdim 211263509Sdimllvm::Value* 212263509SdimCodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S, 213263509Sdim bool GetLast, 214263509Sdim AggValueSlot AggSlot) { 215252723Sdim 216193326Sed for (CompoundStmt::const_body_iterator I = S.body_begin(), 217193326Sed E = S.body_end()-GetLast; I != E; ++I) 218193326Sed EmitStmt(*I); 219193326Sed 220263509Sdim llvm::Value *RetAlloca = 0; 221263509Sdim if (GetLast) { 222198092Srdivacky // We have to special case labels here. They are statements, but when put 223193326Sed // at the end of a statement expression, they yield the value of their 224193326Sed // subexpression. Handle this by walking through all labels we encounter, 225193326Sed // emitting them before we evaluate the subexpr. 226193326Sed const Stmt *LastStmt = S.body_back(); 227193326Sed while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) { 228218893Sdim EmitLabel(LS->getDecl()); 229193326Sed LastStmt = LS->getSubStmt(); 230193326Sed } 231198092Srdivacky 232193326Sed EnsureInsertPoint(); 233198092Srdivacky 234263509Sdim QualType ExprTy = cast<Expr>(LastStmt)->getType(); 235263509Sdim if (hasAggregateEvaluationKind(ExprTy)) { 236263509Sdim EmitAggExpr(cast<Expr>(LastStmt), AggSlot); 237263509Sdim } else { 238263509Sdim // We can't return an RValue here because there might be cleanups at 239263509Sdim // the end of the StmtExpr. Because of that, we have to emit the result 240263509Sdim // here into a temporary alloca. 241263509Sdim RetAlloca = CreateMemTemp(ExprTy); 242263509Sdim EmitAnyExprToMem(cast<Expr>(LastStmt), RetAlloca, Qualifiers(), 243263509Sdim /*IsInit*/false); 244263509Sdim } 245263509Sdim 246193326Sed } 247193326Sed 248263509Sdim return RetAlloca; 249193326Sed} 250193326Sed 251193326Sedvoid CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) { 252193326Sed llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator()); 253198092Srdivacky 254193326Sed // If there is a cleanup stack, then we it isn't worth trying to 255193326Sed // simplify this block (we would need to remove it from the scope map 256193326Sed // and cleanup entry). 257210299Sed if (!EHStack.empty()) 258193326Sed return; 259193326Sed 260193326Sed // Can only simplify direct branches. 261193326Sed if (!BI || !BI->isUnconditional()) 262193326Sed return; 263193326Sed 264245431Sdim // Can only simplify empty blocks. 265245431Sdim if (BI != BB->begin()) 266245431Sdim return; 267245431Sdim 268193326Sed BB->replaceAllUsesWith(BI->getSuccessor(0)); 269193326Sed BI->eraseFromParent(); 270193326Sed BB->eraseFromParent(); 271193326Sed} 272193326Sed 273193326Sedvoid CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) { 274207619Srdivacky llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 275207619Srdivacky 276193326Sed // Fall out of the current block (if necessary). 277193326Sed EmitBranch(BB); 278193326Sed 279193326Sed if (IsFinished && BB->use_empty()) { 280193326Sed delete BB; 281193326Sed return; 282193326Sed } 283193326Sed 284207619Srdivacky // Place the block after the current block, if possible, or else at 285207619Srdivacky // the end of the function. 286207619Srdivacky if (CurBB && CurBB->getParent()) 287207619Srdivacky CurFn->getBasicBlockList().insertAfter(CurBB, BB); 288207619Srdivacky else 289207619Srdivacky CurFn->getBasicBlockList().push_back(BB); 290193326Sed Builder.SetInsertPoint(BB); 291193326Sed} 292193326Sed 293193326Sedvoid CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) { 294193326Sed // Emit a branch from the current block to the target one if this 295193326Sed // was a real block. If this was just a fall-through block after a 296193326Sed // terminator, don't emit it. 297193326Sed llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 298193326Sed 299193326Sed if (!CurBB || CurBB->getTerminator()) { 300193326Sed // If there is no insert point or the previous block is already 301193326Sed // terminated, don't touch it. 302193326Sed } else { 303193326Sed // Otherwise, create a fall-through branch. 304193326Sed Builder.CreateBr(Target); 305193326Sed } 306193326Sed 307193326Sed Builder.ClearInsertionPoint(); 308193326Sed} 309193326Sed 310226890Sdimvoid CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) { 311226890Sdim bool inserted = false; 312226890Sdim for (llvm::BasicBlock::use_iterator 313226890Sdim i = block->use_begin(), e = block->use_end(); i != e; ++i) { 314226890Sdim if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(*i)) { 315226890Sdim CurFn->getBasicBlockList().insertAfter(insn->getParent(), block); 316226890Sdim inserted = true; 317226890Sdim break; 318226890Sdim } 319226890Sdim } 320226890Sdim 321226890Sdim if (!inserted) 322226890Sdim CurFn->getBasicBlockList().push_back(block); 323226890Sdim 324226890Sdim Builder.SetInsertPoint(block); 325226890Sdim} 326226890Sdim 327210299SedCodeGenFunction::JumpDest 328218893SdimCodeGenFunction::getJumpDestForLabel(const LabelDecl *D) { 329218893Sdim JumpDest &Dest = LabelMap[D]; 330212904Sdim if (Dest.isValid()) return Dest; 331210299Sed 332210299Sed // Create, but don't insert, the new block. 333218893Sdim Dest = JumpDest(createBasicBlock(D->getName()), 334212904Sdim EHScopeStack::stable_iterator::invalid(), 335212904Sdim NextCleanupDestIndex++); 336210299Sed return Dest; 337210299Sed} 338210299Sed 339218893Sdimvoid CodeGenFunction::EmitLabel(const LabelDecl *D) { 340252723Sdim // Add this label to the current lexical scope if we're within any 341252723Sdim // normal cleanups. Jumps "in" to this label --- when permitted by 342252723Sdim // the language --- may need to be routed around such cleanups. 343252723Sdim if (EHStack.hasNormalCleanups() && CurLexicalScope) 344252723Sdim CurLexicalScope->addLabel(D); 345252723Sdim 346218893Sdim JumpDest &Dest = LabelMap[D]; 347210299Sed 348212904Sdim // If we didn't need a forward reference to this label, just go 349210299Sed // ahead and create a destination at the current scope. 350212904Sdim if (!Dest.isValid()) { 351218893Sdim Dest = getJumpDestInCurrentScope(D->getName()); 352210299Sed 353210299Sed // Otherwise, we need to give this label a target depth and remove 354210299Sed // it from the branch-fixups list. 355210299Sed } else { 356212904Sdim assert(!Dest.getScopeDepth().isValid() && "already emitted label!"); 357252723Sdim Dest.setScopeDepth(EHStack.stable_begin()); 358212904Sdim ResolveBranchFixups(Dest.getBlock()); 359210299Sed } 360210299Sed 361212904Sdim EmitBlock(Dest.getBlock()); 362193326Sed} 363193326Sed 364252723Sdim/// Change the cleanup scope of the labels in this lexical scope to 365252723Sdim/// match the scope of the enclosing context. 366252723Sdimvoid CodeGenFunction::LexicalScope::rescopeLabels() { 367252723Sdim assert(!Labels.empty()); 368252723Sdim EHScopeStack::stable_iterator innermostScope 369252723Sdim = CGF.EHStack.getInnermostNormalCleanup(); 370193326Sed 371252723Sdim // Change the scope depth of all the labels. 372252723Sdim for (SmallVectorImpl<const LabelDecl*>::const_iterator 373252723Sdim i = Labels.begin(), e = Labels.end(); i != e; ++i) { 374252723Sdim assert(CGF.LabelMap.count(*i)); 375252723Sdim JumpDest &dest = CGF.LabelMap.find(*i)->second; 376252723Sdim assert(dest.getScopeDepth().isValid()); 377252723Sdim assert(innermostScope.encloses(dest.getScopeDepth())); 378252723Sdim dest.setScopeDepth(innermostScope); 379252723Sdim } 380252723Sdim 381252723Sdim // Reparent the labels if the new scope also has cleanups. 382252723Sdim if (innermostScope != EHScopeStack::stable_end() && ParentScope) { 383252723Sdim ParentScope->Labels.append(Labels.begin(), Labels.end()); 384252723Sdim } 385252723Sdim} 386252723Sdim 387252723Sdim 388193326Sedvoid CodeGenFunction::EmitLabelStmt(const LabelStmt &S) { 389218893Sdim EmitLabel(S.getDecl()); 390193326Sed EmitStmt(S.getSubStmt()); 391193326Sed} 392193326Sed 393235633Sdimvoid CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) { 394235633Sdim EmitStmt(S.getSubStmt()); 395235633Sdim} 396235633Sdim 397193326Sedvoid CodeGenFunction::EmitGotoStmt(const GotoStmt &S) { 398193326Sed // If this code is reachable then emit a stop point (if generating 399193326Sed // debug info). We have to do this ourselves because we are on the 400193326Sed // "simple" statement path. 401193326Sed if (HaveInsertPoint()) 402193326Sed EmitStopPoint(&S); 403193326Sed 404210299Sed EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel())); 405193326Sed} 406193326Sed 407198092Srdivacky 408193326Sedvoid CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) { 409218893Sdim if (const LabelDecl *Target = S.getConstantTarget()) { 410218893Sdim EmitBranchThroughCleanup(getJumpDestForLabel(Target)); 411218893Sdim return; 412218893Sdim } 413218893Sdim 414199482Srdivacky // Ensure that we have an i8* for our PHI node. 415198893Srdivacky llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()), 416218893Sdim Int8PtrTy, "addr"); 417198092Srdivacky llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 418193326Sed 419198092Srdivacky // Get the basic block for the indirect goto. 420198092Srdivacky llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock(); 421245431Sdim 422198092Srdivacky // The first instruction in the block has to be the PHI for the switch dest, 423198092Srdivacky // add an entry for this branch. 424198092Srdivacky cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB); 425245431Sdim 426198092Srdivacky EmitBranch(IndGotoBB); 427193326Sed} 428193326Sed 429193326Sedvoid CodeGenFunction::EmitIfStmt(const IfStmt &S) { 430193326Sed // C99 6.8.4.1: The first substatement is executed if the expression compares 431193326Sed // unequal to 0. The condition must be a scalar type. 432263509Sdim LexicalScope ConditionScope(*this, S.getSourceRange()); 433198092Srdivacky 434199990Srdivacky if (S.getConditionVariable()) 435218893Sdim EmitAutoVarDecl(*S.getConditionVariable()); 436199990Srdivacky 437193326Sed // If the condition constant folds and can be elided, try to avoid emitting 438193326Sed // the condition and the dead arm of the if/else. 439221345Sdim bool CondConstant; 440221345Sdim if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) { 441193326Sed // Figure out which block (then or else) is executed. 442221345Sdim const Stmt *Executed = S.getThen(); 443221345Sdim const Stmt *Skipped = S.getElse(); 444221345Sdim if (!CondConstant) // Condition false? 445193326Sed std::swap(Executed, Skipped); 446198092Srdivacky 447193326Sed // If the skipped block has no labels in it, just emit the executed block. 448193326Sed // This avoids emitting dead code and simplifies the CFG substantially. 449193326Sed if (!ContainsLabel(Skipped)) { 450199990Srdivacky if (Executed) { 451210299Sed RunCleanupsScope ExecutedScope(*this); 452193326Sed EmitStmt(Executed); 453199990Srdivacky } 454193326Sed return; 455193326Sed } 456193326Sed } 457193326Sed 458193326Sed // Otherwise, the condition did not fold, or we couldn't elide it. Just emit 459193326Sed // the conditional branch. 460193326Sed llvm::BasicBlock *ThenBlock = createBasicBlock("if.then"); 461193326Sed llvm::BasicBlock *ContBlock = createBasicBlock("if.end"); 462193326Sed llvm::BasicBlock *ElseBlock = ContBlock; 463193326Sed if (S.getElse()) 464193326Sed ElseBlock = createBasicBlock("if.else"); 465193326Sed EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock); 466198092Srdivacky 467193326Sed // Emit the 'then' code. 468199990Srdivacky EmitBlock(ThenBlock); 469199990Srdivacky { 470210299Sed RunCleanupsScope ThenScope(*this); 471199990Srdivacky EmitStmt(S.getThen()); 472199990Srdivacky } 473193326Sed EmitBranch(ContBlock); 474198092Srdivacky 475193326Sed // Emit the 'else' code if present. 476193326Sed if (const Stmt *Else = S.getElse()) { 477221345Sdim // There is no need to emit line number for unconditional branch. 478221345Sdim if (getDebugInfo()) 479221345Sdim Builder.SetCurrentDebugLocation(llvm::DebugLoc()); 480193326Sed EmitBlock(ElseBlock); 481199990Srdivacky { 482210299Sed RunCleanupsScope ElseScope(*this); 483199990Srdivacky EmitStmt(Else); 484199990Srdivacky } 485221345Sdim // There is no need to emit line number for unconditional branch. 486221345Sdim if (getDebugInfo()) 487221345Sdim Builder.SetCurrentDebugLocation(llvm::DebugLoc()); 488193326Sed EmitBranch(ContBlock); 489193326Sed } 490198092Srdivacky 491193326Sed // Emit the continuation block for code after the if. 492193326Sed EmitBlock(ContBlock, true); 493193326Sed} 494193326Sed 495193326Sedvoid CodeGenFunction::EmitWhileStmt(const WhileStmt &S) { 496210299Sed // Emit the header for the loop, which will also become 497210299Sed // the continue target. 498210299Sed JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond"); 499212904Sdim EmitBlock(LoopHeader.getBlock()); 500193326Sed 501210299Sed // Create an exit block for when the condition fails, which will 502210299Sed // also become the break target. 503210299Sed JumpDest LoopExit = getJumpDestInCurrentScope("while.end"); 504193326Sed 505193326Sed // Store the blocks to use for break and continue. 506210299Sed BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader)); 507198092Srdivacky 508199990Srdivacky // C++ [stmt.while]p2: 509199990Srdivacky // When the condition of a while statement is a declaration, the 510199990Srdivacky // scope of the variable that is declared extends from its point 511199990Srdivacky // of declaration (3.3.2) to the end of the while statement. 512199990Srdivacky // [...] 513199990Srdivacky // The object created in a condition is destroyed and created 514199990Srdivacky // with each iteration of the loop. 515210299Sed RunCleanupsScope ConditionScope(*this); 516199990Srdivacky 517210299Sed if (S.getConditionVariable()) 518218893Sdim EmitAutoVarDecl(*S.getConditionVariable()); 519245431Sdim 520193326Sed // Evaluate the conditional in the while header. C99 6.8.5.1: The 521193326Sed // evaluation of the controlling expression takes place before each 522193326Sed // execution of the loop body. 523193326Sed llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 524245431Sdim 525193326Sed // while(1) is common, avoid extra exit blocks. Be sure 526193326Sed // to correctly handle break/continue though. 527193326Sed bool EmitBoolCondBranch = true; 528198092Srdivacky if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) 529193326Sed if (C->isOne()) 530193326Sed EmitBoolCondBranch = false; 531198092Srdivacky 532193326Sed // As long as the condition is true, go to the loop body. 533210299Sed llvm::BasicBlock *LoopBody = createBasicBlock("while.body"); 534210299Sed if (EmitBoolCondBranch) { 535212904Sdim llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 536210299Sed if (ConditionScope.requiresCleanups()) 537210299Sed ExitBlock = createBasicBlock("while.exit"); 538210299Sed 539210299Sed Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock); 540210299Sed 541212904Sdim if (ExitBlock != LoopExit.getBlock()) { 542210299Sed EmitBlock(ExitBlock); 543210299Sed EmitBranchThroughCleanup(LoopExit); 544210299Sed } 545210299Sed } 546245431Sdim 547210299Sed // Emit the loop body. We have to emit this in a cleanup scope 548210299Sed // because it might be a singleton DeclStmt. 549199990Srdivacky { 550210299Sed RunCleanupsScope BodyScope(*this); 551199990Srdivacky EmitBlock(LoopBody); 552199990Srdivacky EmitStmt(S.getBody()); 553199990Srdivacky } 554193326Sed 555198092Srdivacky BreakContinueStack.pop_back(); 556198092Srdivacky 557210299Sed // Immediately force cleanup. 558210299Sed ConditionScope.ForceCleanup(); 559198092Srdivacky 560210299Sed // Branch to the loop header again. 561212904Sdim EmitBranch(LoopHeader.getBlock()); 562199990Srdivacky 563193326Sed // Emit the exit block. 564212904Sdim EmitBlock(LoopExit.getBlock(), true); 565193326Sed 566193326Sed // The LoopHeader typically is just a branch if we skipped emitting 567193326Sed // a branch, try to erase it. 568210299Sed if (!EmitBoolCondBranch) 569212904Sdim SimplifyForwardingBlocks(LoopHeader.getBlock()); 570193326Sed} 571193326Sed 572193326Sedvoid CodeGenFunction::EmitDoStmt(const DoStmt &S) { 573210299Sed JumpDest LoopExit = getJumpDestInCurrentScope("do.end"); 574210299Sed JumpDest LoopCond = getJumpDestInCurrentScope("do.cond"); 575193326Sed 576193326Sed // Store the blocks to use for break and continue. 577210299Sed BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond)); 578198092Srdivacky 579210299Sed // Emit the body of the loop. 580210299Sed llvm::BasicBlock *LoopBody = createBasicBlock("do.body"); 581210299Sed EmitBlock(LoopBody); 582210299Sed { 583210299Sed RunCleanupsScope BodyScope(*this); 584210299Sed EmitStmt(S.getBody()); 585210299Sed } 586198092Srdivacky 587193326Sed BreakContinueStack.pop_back(); 588198092Srdivacky 589212904Sdim EmitBlock(LoopCond.getBlock()); 590198092Srdivacky 591193326Sed // C99 6.8.5.2: "The evaluation of the controlling expression takes place 592193326Sed // after each execution of the loop body." 593198092Srdivacky 594193326Sed // Evaluate the conditional in the while header. 595193326Sed // C99 6.8.5p2/p4: The first substatement is executed if the expression 596193326Sed // compares unequal to 0. The condition must be a scalar type. 597193326Sed llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 598193326Sed 599193326Sed // "do {} while (0)" is common in macros, avoid extra blocks. Be sure 600193326Sed // to correctly handle break/continue though. 601193326Sed bool EmitBoolCondBranch = true; 602198092Srdivacky if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) 603193326Sed if (C->isZero()) 604193326Sed EmitBoolCondBranch = false; 605193326Sed 606193326Sed // As long as the condition is true, iterate the loop. 607193326Sed if (EmitBoolCondBranch) 608212904Sdim Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock()); 609198092Srdivacky 610193326Sed // Emit the exit block. 611212904Sdim EmitBlock(LoopExit.getBlock()); 612193326Sed 613193326Sed // The DoCond block typically is just a branch if we skipped 614193326Sed // emitting a branch, try to erase it. 615193326Sed if (!EmitBoolCondBranch) 616212904Sdim SimplifyForwardingBlocks(LoopCond.getBlock()); 617193326Sed} 618193326Sed 619193326Sedvoid CodeGenFunction::EmitForStmt(const ForStmt &S) { 620210299Sed JumpDest LoopExit = getJumpDestInCurrentScope("for.end"); 621193326Sed 622210299Sed RunCleanupsScope ForScope(*this); 623210299Sed 624212904Sdim CGDebugInfo *DI = getDebugInfo(); 625226890Sdim if (DI) 626226890Sdim DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin()); 627212904Sdim 628193326Sed // Evaluate the first part before the loop. 629193326Sed if (S.getInit()) 630193326Sed EmitStmt(S.getInit()); 631193326Sed 632193326Sed // Start the loop with a block that tests the condition. 633210299Sed // If there's an increment, the continue scope will be overwritten 634210299Sed // later. 635210299Sed JumpDest Continue = getJumpDestInCurrentScope("for.cond"); 636212904Sdim llvm::BasicBlock *CondBlock = Continue.getBlock(); 637193326Sed EmitBlock(CondBlock); 638193326Sed 639199990Srdivacky // Create a cleanup scope for the condition variable cleanups. 640210299Sed RunCleanupsScope ConditionScope(*this); 641245431Sdim 642193326Sed if (S.getCond()) { 643199990Srdivacky // If the for statement has a condition scope, emit the local variable 644199990Srdivacky // declaration. 645199990Srdivacky if (S.getConditionVariable()) { 646218893Sdim EmitAutoVarDecl(*S.getConditionVariable()); 647199990Srdivacky } 648210299Sed 649263509Sdim llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 650210299Sed // If there are any cleanups between here and the loop-exit scope, 651210299Sed // create a block to stage a loop exit along. 652210299Sed if (ForScope.requiresCleanups()) 653210299Sed ExitBlock = createBasicBlock("for.cond.cleanup"); 654245431Sdim 655193326Sed // As long as the condition is true, iterate the loop. 656193326Sed llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 657198092Srdivacky 658193326Sed // C99 6.8.5p2/p4: The first substatement is executed if the expression 659193326Sed // compares unequal to 0. The condition must be a scalar type. 660263509Sdim EmitBranchOnBoolExpr(S.getCond(), ForBody, ExitBlock); 661198092Srdivacky 662212904Sdim if (ExitBlock != LoopExit.getBlock()) { 663210299Sed EmitBlock(ExitBlock); 664210299Sed EmitBranchThroughCleanup(LoopExit); 665210299Sed } 666210299Sed 667198092Srdivacky EmitBlock(ForBody); 668193326Sed } else { 669193326Sed // Treat it as a non-zero constant. Don't even create a new block for the 670193326Sed // body, just fall into it. 671193326Sed } 672193326Sed 673198092Srdivacky // If the for loop doesn't have an increment we can just use the 674210299Sed // condition as the continue block. Otherwise we'll need to create 675210299Sed // a block for it (in the current scope, i.e. in the scope of the 676210299Sed // condition), and that we will become our continue block. 677193326Sed if (S.getInc()) 678210299Sed Continue = getJumpDestInCurrentScope("for.inc"); 679198092Srdivacky 680193326Sed // Store the blocks to use for break and continue. 681210299Sed BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 682193326Sed 683199990Srdivacky { 684199990Srdivacky // Create a separate cleanup scope for the body, in case it is not 685199990Srdivacky // a compound statement. 686210299Sed RunCleanupsScope BodyScope(*this); 687199990Srdivacky EmitStmt(S.getBody()); 688199990Srdivacky } 689199990Srdivacky 690193326Sed // If there is an increment, emit it next. 691193326Sed if (S.getInc()) { 692212904Sdim EmitBlock(Continue.getBlock()); 693193326Sed EmitStmt(S.getInc()); 694193326Sed } 695198092Srdivacky 696208600Srdivacky BreakContinueStack.pop_back(); 697199990Srdivacky 698210299Sed ConditionScope.ForceCleanup(); 699210299Sed EmitBranch(CondBlock); 700210299Sed 701210299Sed ForScope.ForceCleanup(); 702210299Sed 703226890Sdim if (DI) 704226890Sdim DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd()); 705193326Sed 706193326Sed // Emit the fall-through block. 707212904Sdim EmitBlock(LoopExit.getBlock(), true); 708193326Sed} 709193326Sed 710221345Sdimvoid CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S) { 711221345Sdim JumpDest LoopExit = getJumpDestInCurrentScope("for.end"); 712221345Sdim 713221345Sdim RunCleanupsScope ForScope(*this); 714221345Sdim 715221345Sdim CGDebugInfo *DI = getDebugInfo(); 716226890Sdim if (DI) 717226890Sdim DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin()); 718221345Sdim 719221345Sdim // Evaluate the first pieces before the loop. 720221345Sdim EmitStmt(S.getRangeStmt()); 721221345Sdim EmitStmt(S.getBeginEndStmt()); 722221345Sdim 723221345Sdim // Start the loop with a block that tests the condition. 724221345Sdim // If there's an increment, the continue scope will be overwritten 725221345Sdim // later. 726221345Sdim llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); 727221345Sdim EmitBlock(CondBlock); 728221345Sdim 729221345Sdim // If there are any cleanups between here and the loop-exit scope, 730221345Sdim // create a block to stage a loop exit along. 731221345Sdim llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 732221345Sdim if (ForScope.requiresCleanups()) 733221345Sdim ExitBlock = createBasicBlock("for.cond.cleanup"); 734245431Sdim 735221345Sdim // The loop body, consisting of the specified body and the loop variable. 736221345Sdim llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 737221345Sdim 738221345Sdim // The body is executed if the expression, contextually converted 739221345Sdim // to bool, is true. 740263509Sdim EmitBranchOnBoolExpr(S.getCond(), ForBody, ExitBlock); 741221345Sdim 742221345Sdim if (ExitBlock != LoopExit.getBlock()) { 743221345Sdim EmitBlock(ExitBlock); 744221345Sdim EmitBranchThroughCleanup(LoopExit); 745221345Sdim } 746221345Sdim 747221345Sdim EmitBlock(ForBody); 748221345Sdim 749221345Sdim // Create a block for the increment. In case of a 'continue', we jump there. 750221345Sdim JumpDest Continue = getJumpDestInCurrentScope("for.inc"); 751221345Sdim 752221345Sdim // Store the blocks to use for break and continue. 753221345Sdim BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 754221345Sdim 755221345Sdim { 756221345Sdim // Create a separate cleanup scope for the loop variable and body. 757221345Sdim RunCleanupsScope BodyScope(*this); 758221345Sdim EmitStmt(S.getLoopVarStmt()); 759221345Sdim EmitStmt(S.getBody()); 760221345Sdim } 761221345Sdim 762221345Sdim // If there is an increment, emit it next. 763221345Sdim EmitBlock(Continue.getBlock()); 764221345Sdim EmitStmt(S.getInc()); 765221345Sdim 766221345Sdim BreakContinueStack.pop_back(); 767221345Sdim 768221345Sdim EmitBranch(CondBlock); 769221345Sdim 770221345Sdim ForScope.ForceCleanup(); 771221345Sdim 772226890Sdim if (DI) 773226890Sdim DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd()); 774221345Sdim 775221345Sdim // Emit the fall-through block. 776221345Sdim EmitBlock(LoopExit.getBlock(), true); 777221345Sdim} 778221345Sdim 779193326Sedvoid CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) { 780193326Sed if (RV.isScalar()) { 781193326Sed Builder.CreateStore(RV.getScalarVal(), ReturnValue); 782193326Sed } else if (RV.isAggregate()) { 783193326Sed EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty); 784193326Sed } else { 785252723Sdim EmitStoreOfComplex(RV.getComplexVal(), 786252723Sdim MakeNaturalAlignAddrLValue(ReturnValue, Ty), 787252723Sdim /*init*/ true); 788193326Sed } 789193326Sed EmitBranchThroughCleanup(ReturnBlock); 790193326Sed} 791193326Sed 792193326Sed/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand 793193326Sed/// if the function returns void, or may be missing one if the function returns 794193326Sed/// non-void. Fun stuff :). 795193326Sedvoid CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) { 796193326Sed // Emit the result value, even if unused, to evalute the side effects. 797193326Sed const Expr *RV = S.getRetValue(); 798198092Srdivacky 799245431Sdim // Treat block literals in a return expression as if they appeared 800245431Sdim // in their own scope. This permits a small, easily-implemented 801245431Sdim // exception to our over-conservative rules about not jumping to 802245431Sdim // statements following block literals with non-trivial cleanups. 803245431Sdim RunCleanupsScope cleanupScope(*this); 804245431Sdim if (const ExprWithCleanups *cleanups = 805245431Sdim dyn_cast_or_null<ExprWithCleanups>(RV)) { 806245431Sdim enterFullExpression(cleanups); 807245431Sdim RV = cleanups->getSubExpr(); 808245431Sdim } 809245431Sdim 810193326Sed // FIXME: Clean this up by using an LValue for ReturnTemp, 811193326Sed // EmitStoreThroughLValue, and EmitAnyExpr. 812252723Sdim if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) { 813208600Srdivacky // Apply the named return value optimization for this return statement, 814208600Srdivacky // which means doing nothing: the appropriate result has already been 815208600Srdivacky // constructed into the NRVO variable. 816245431Sdim 817208600Srdivacky // If there is an NRVO flag for this variable, set it to 1 into indicate 818208600Srdivacky // that the cleanup code should not destroy the variable. 819218893Sdim if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()]) 820218893Sdim Builder.CreateStore(Builder.getTrue(), NRVOFlag); 821208600Srdivacky } else if (!ReturnValue) { 822193326Sed // Make sure not to return anything, but evaluate the expression 823193326Sed // for side effects. 824193326Sed if (RV) 825193326Sed EmitAnyExpr(RV); 826193326Sed } else if (RV == 0) { 827193326Sed // Do nothing (return value is left uninitialized) 828193326Sed } else if (FnRetTy->isReferenceType()) { 829193326Sed // If this function returns a reference, take the address of the expression 830193326Sed // rather than the value. 831263509Sdim RValue Result = EmitReferenceBindingToExpr(RV); 832206084Srdivacky Builder.CreateStore(Result.getScalarVal(), ReturnValue); 833193326Sed } else { 834252723Sdim switch (getEvaluationKind(RV->getType())) { 835252723Sdim case TEK_Scalar: 836252723Sdim Builder.CreateStore(EmitScalarExpr(RV), ReturnValue); 837252723Sdim break; 838252723Sdim case TEK_Complex: 839252723Sdim EmitComplexExprIntoLValue(RV, 840252723Sdim MakeNaturalAlignAddrLValue(ReturnValue, RV->getType()), 841252723Sdim /*isInit*/ true); 842252723Sdim break; 843252723Sdim case TEK_Aggregate: { 844252723Sdim CharUnits Alignment = getContext().getTypeAlignInChars(RV->getType()); 845252723Sdim EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Alignment, 846252723Sdim Qualifiers(), 847252723Sdim AggValueSlot::IsDestructed, 848252723Sdim AggValueSlot::DoesNotNeedGCBarriers, 849252723Sdim AggValueSlot::IsNotAliased)); 850252723Sdim break; 851252723Sdim } 852252723Sdim } 853193326Sed } 854193326Sed 855263509Sdim ++NumReturnExprs; 856252723Sdim if (RV == 0 || RV->isEvaluatable(getContext())) 857263509Sdim ++NumSimpleReturnExprs; 858252723Sdim 859245431Sdim cleanupScope.ForceCleanup(); 860193326Sed EmitBranchThroughCleanup(ReturnBlock); 861193326Sed} 862193326Sed 863193326Sedvoid CodeGenFunction::EmitDeclStmt(const DeclStmt &S) { 864198092Srdivacky // As long as debug info is modeled with instructions, we have to ensure we 865198092Srdivacky // have a place to insert here and write the stop point here. 866235633Sdim if (HaveInsertPoint()) 867198092Srdivacky EmitStopPoint(&S); 868198092Srdivacky 869193326Sed for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end(); 870193326Sed I != E; ++I) 871193326Sed EmitDecl(**I); 872193326Sed} 873193326Sed 874193326Sedvoid CodeGenFunction::EmitBreakStmt(const BreakStmt &S) { 875193326Sed assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!"); 876193326Sed 877193326Sed // If this code is reachable then emit a stop point (if generating 878193326Sed // debug info). We have to do this ourselves because we are on the 879193326Sed // "simple" statement path. 880193326Sed if (HaveInsertPoint()) 881193326Sed EmitStopPoint(&S); 882193326Sed 883210299Sed JumpDest Block = BreakContinueStack.back().BreakBlock; 884193326Sed EmitBranchThroughCleanup(Block); 885193326Sed} 886193326Sed 887193326Sedvoid CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) { 888193326Sed assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); 889193326Sed 890193326Sed // If this code is reachable then emit a stop point (if generating 891193326Sed // debug info). We have to do this ourselves because we are on the 892193326Sed // "simple" statement path. 893193326Sed if (HaveInsertPoint()) 894193326Sed EmitStopPoint(&S); 895193326Sed 896210299Sed JumpDest Block = BreakContinueStack.back().ContinueBlock; 897193326Sed EmitBranchThroughCleanup(Block); 898193326Sed} 899193326Sed 900193326Sed/// EmitCaseStmtRange - If case statement range is not too big then 901193326Sed/// add multiple cases to switch instruction, one for each value within 902193326Sed/// the range. If range is too big then emit "if" condition check. 903193326Sedvoid CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) { 904193326Sed assert(S.getRHS() && "Expected RHS value in CaseStmt"); 905193326Sed 906226890Sdim llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext()); 907226890Sdim llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext()); 908193326Sed 909193326Sed // Emit the code for this case. We do this first to make sure it is 910193326Sed // properly chained from our predecessor before generating the 911193326Sed // switch machinery to enter this block. 912193326Sed EmitBlock(createBasicBlock("sw.bb")); 913193326Sed llvm::BasicBlock *CaseDest = Builder.GetInsertBlock(); 914193326Sed EmitStmt(S.getSubStmt()); 915193326Sed 916193326Sed // If range is empty, do nothing. 917193326Sed if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS)) 918193326Sed return; 919193326Sed 920193326Sed llvm::APInt Range = RHS - LHS; 921193326Sed // FIXME: parameters such as this should not be hardcoded. 922193326Sed if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) { 923193326Sed // Range is small enough to add multiple switch instruction cases. 924193326Sed for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) { 925221345Sdim SwitchInsn->addCase(Builder.getInt(LHS), CaseDest); 926193326Sed LHS++; 927193326Sed } 928193326Sed return; 929198092Srdivacky } 930198092Srdivacky 931193326Sed // The range is too big. Emit "if" condition into a new block, 932193326Sed // making sure to save and restore the current insertion point. 933193326Sed llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock(); 934193326Sed 935193326Sed // Push this test onto the chain of range checks (which terminates 936193326Sed // in the default basic block). The switch's default will be changed 937193326Sed // to the top of this chain after switch emission is complete. 938193326Sed llvm::BasicBlock *FalseDest = CaseRangeBlock; 939193326Sed CaseRangeBlock = createBasicBlock("sw.caserange"); 940193326Sed 941193326Sed CurFn->getBasicBlockList().push_back(CaseRangeBlock); 942193326Sed Builder.SetInsertPoint(CaseRangeBlock); 943193326Sed 944193326Sed // Emit range check. 945198092Srdivacky llvm::Value *Diff = 946226890Sdim Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS)); 947198092Srdivacky llvm::Value *Cond = 948221345Sdim Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds"); 949193326Sed Builder.CreateCondBr(Cond, CaseDest, FalseDest); 950193326Sed 951193326Sed // Restore the appropriate insertion point. 952193326Sed if (RestoreBB) 953193326Sed Builder.SetInsertPoint(RestoreBB); 954193326Sed else 955193326Sed Builder.ClearInsertionPoint(); 956193326Sed} 957193326Sed 958193326Sedvoid CodeGenFunction::EmitCaseStmt(const CaseStmt &S) { 959235633Sdim // If there is no enclosing switch instance that we're aware of, then this 960235633Sdim // case statement and its block can be elided. This situation only happens 961235633Sdim // when we've constant-folded the switch, are emitting the constant case, 962235633Sdim // and part of the constant case includes another case statement. For 963235633Sdim // instance: switch (4) { case 4: do { case 5: } while (1); } 964235633Sdim if (!SwitchInsn) { 965235633Sdim EmitStmt(S.getSubStmt()); 966235633Sdim return; 967235633Sdim } 968235633Sdim 969221345Sdim // Handle case ranges. 970193326Sed if (S.getRHS()) { 971193326Sed EmitCaseStmtRange(S); 972193326Sed return; 973193326Sed } 974198092Srdivacky 975221345Sdim llvm::ConstantInt *CaseVal = 976226890Sdim Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext())); 977221345Sdim 978221345Sdim // If the body of the case is just a 'break', and if there was no fallthrough, 979221345Sdim // try to not emit an empty block. 980245431Sdim if ((CGM.getCodeGenOpts().OptimizationLevel > 0) && 981245431Sdim isa<BreakStmt>(S.getSubStmt())) { 982221345Sdim JumpDest Block = BreakContinueStack.back().BreakBlock; 983245431Sdim 984221345Sdim // Only do this optimization if there are no cleanups that need emitting. 985221345Sdim if (isObviouslyBranchWithoutCleanups(Block)) { 986221345Sdim SwitchInsn->addCase(CaseVal, Block.getBlock()); 987221345Sdim 988221345Sdim // If there was a fallthrough into this case, make sure to redirect it to 989221345Sdim // the end of the switch as well. 990221345Sdim if (Builder.GetInsertBlock()) { 991221345Sdim Builder.CreateBr(Block.getBlock()); 992221345Sdim Builder.ClearInsertionPoint(); 993221345Sdim } 994221345Sdim return; 995221345Sdim } 996221345Sdim } 997245431Sdim 998193326Sed EmitBlock(createBasicBlock("sw.bb")); 999193326Sed llvm::BasicBlock *CaseDest = Builder.GetInsertBlock(); 1000221345Sdim SwitchInsn->addCase(CaseVal, CaseDest); 1001198092Srdivacky 1002193326Sed // Recursively emitting the statement is acceptable, but is not wonderful for 1003193326Sed // code where we have many case statements nested together, i.e.: 1004193326Sed // case 1: 1005193326Sed // case 2: 1006193326Sed // case 3: etc. 1007193326Sed // Handling this recursively will create a new block for each case statement 1008193326Sed // that falls through to the next case which is IR intensive. It also causes 1009193326Sed // deep recursion which can run into stack depth limitations. Handle 1010193326Sed // sequential non-range case statements specially. 1011193326Sed const CaseStmt *CurCase = &S; 1012193326Sed const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt()); 1013193326Sed 1014221345Sdim // Otherwise, iteratively add consecutive cases to this switch stmt. 1015193326Sed while (NextCase && NextCase->getRHS() == 0) { 1016193326Sed CurCase = NextCase; 1017221345Sdim llvm::ConstantInt *CaseVal = 1018226890Sdim Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext())); 1019221345Sdim SwitchInsn->addCase(CaseVal, CaseDest); 1020193326Sed NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt()); 1021193326Sed } 1022198092Srdivacky 1023193326Sed // Normal default recursion for non-cases. 1024193326Sed EmitStmt(CurCase->getSubStmt()); 1025193326Sed} 1026193326Sed 1027193326Sedvoid CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) { 1028193326Sed llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest(); 1029198092Srdivacky assert(DefaultBlock->empty() && 1030193326Sed "EmitDefaultStmt: Default block already defined?"); 1031193326Sed EmitBlock(DefaultBlock); 1032193326Sed EmitStmt(S.getSubStmt()); 1033193326Sed} 1034193326Sed 1035221345Sdim/// CollectStatementsForCase - Given the body of a 'switch' statement and a 1036221345Sdim/// constant value that is being switched on, see if we can dead code eliminate 1037221345Sdim/// the body of the switch to a simple series of statements to emit. Basically, 1038221345Sdim/// on a switch (5) we want to find these statements: 1039221345Sdim/// case 5: 1040221345Sdim/// printf(...); <-- 1041221345Sdim/// ++i; <-- 1042221345Sdim/// break; 1043221345Sdim/// 1044221345Sdim/// and add them to the ResultStmts vector. If it is unsafe to do this 1045221345Sdim/// transformation (for example, one of the elided statements contains a label 1046221345Sdim/// that might be jumped to), return CSFC_Failure. If we handled it and 'S' 1047221345Sdim/// should include statements after it (e.g. the printf() line is a substmt of 1048221345Sdim/// the case) then return CSFC_FallThrough. If we handled it and found a break 1049221345Sdim/// statement, then return CSFC_Success. 1050221345Sdim/// 1051221345Sdim/// If Case is non-null, then we are looking for the specified case, checking 1052221345Sdim/// that nothing we jump over contains labels. If Case is null, then we found 1053221345Sdim/// the case and are looking for the break. 1054221345Sdim/// 1055221345Sdim/// If the recursive walk actually finds our Case, then we set FoundCase to 1056221345Sdim/// true. 1057221345Sdim/// 1058221345Sdimenum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success }; 1059221345Sdimstatic CSFC_Result CollectStatementsForCase(const Stmt *S, 1060221345Sdim const SwitchCase *Case, 1061221345Sdim bool &FoundCase, 1062226890Sdim SmallVectorImpl<const Stmt*> &ResultStmts) { 1063221345Sdim // If this is a null statement, just succeed. 1064221345Sdim if (S == 0) 1065221345Sdim return Case ? CSFC_Success : CSFC_FallThrough; 1066245431Sdim 1067221345Sdim // If this is the switchcase (case 4: or default) that we're looking for, then 1068221345Sdim // we're in business. Just add the substatement. 1069221345Sdim if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) { 1070221345Sdim if (S == Case) { 1071221345Sdim FoundCase = true; 1072221345Sdim return CollectStatementsForCase(SC->getSubStmt(), 0, FoundCase, 1073221345Sdim ResultStmts); 1074221345Sdim } 1075245431Sdim 1076221345Sdim // Otherwise, this is some other case or default statement, just ignore it. 1077221345Sdim return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase, 1078221345Sdim ResultStmts); 1079221345Sdim } 1080221345Sdim 1081221345Sdim // If we are in the live part of the code and we found our break statement, 1082221345Sdim // return a success! 1083221345Sdim if (Case == 0 && isa<BreakStmt>(S)) 1084221345Sdim return CSFC_Success; 1085245431Sdim 1086221345Sdim // If this is a switch statement, then it might contain the SwitchCase, the 1087221345Sdim // break, or neither. 1088221345Sdim if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) { 1089221345Sdim // Handle this as two cases: we might be looking for the SwitchCase (if so 1090221345Sdim // the skipped statements must be skippable) or we might already have it. 1091221345Sdim CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end(); 1092221345Sdim if (Case) { 1093221345Sdim // Keep track of whether we see a skipped declaration. The code could be 1094221345Sdim // using the declaration even if it is skipped, so we can't optimize out 1095221345Sdim // the decl if the kept statements might refer to it. 1096221345Sdim bool HadSkippedDecl = false; 1097245431Sdim 1098221345Sdim // If we're looking for the case, just see if we can skip each of the 1099221345Sdim // substatements. 1100221345Sdim for (; Case && I != E; ++I) { 1101223017Sdim HadSkippedDecl |= isa<DeclStmt>(*I); 1102245431Sdim 1103221345Sdim switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) { 1104221345Sdim case CSFC_Failure: return CSFC_Failure; 1105221345Sdim case CSFC_Success: 1106221345Sdim // A successful result means that either 1) that the statement doesn't 1107221345Sdim // have the case and is skippable, or 2) does contain the case value 1108221345Sdim // and also contains the break to exit the switch. In the later case, 1109221345Sdim // we just verify the rest of the statements are elidable. 1110221345Sdim if (FoundCase) { 1111221345Sdim // If we found the case and skipped declarations, we can't do the 1112221345Sdim // optimization. 1113221345Sdim if (HadSkippedDecl) 1114221345Sdim return CSFC_Failure; 1115245431Sdim 1116221345Sdim for (++I; I != E; ++I) 1117221345Sdim if (CodeGenFunction::ContainsLabel(*I, true)) 1118221345Sdim return CSFC_Failure; 1119221345Sdim return CSFC_Success; 1120221345Sdim } 1121221345Sdim break; 1122221345Sdim case CSFC_FallThrough: 1123221345Sdim // If we have a fallthrough condition, then we must have found the 1124221345Sdim // case started to include statements. Consider the rest of the 1125221345Sdim // statements in the compound statement as candidates for inclusion. 1126221345Sdim assert(FoundCase && "Didn't find case but returned fallthrough?"); 1127221345Sdim // We recursively found Case, so we're not looking for it anymore. 1128221345Sdim Case = 0; 1129245431Sdim 1130221345Sdim // If we found the case and skipped declarations, we can't do the 1131221345Sdim // optimization. 1132221345Sdim if (HadSkippedDecl) 1133221345Sdim return CSFC_Failure; 1134221345Sdim break; 1135221345Sdim } 1136221345Sdim } 1137221345Sdim } 1138221345Sdim 1139221345Sdim // If we have statements in our range, then we know that the statements are 1140221345Sdim // live and need to be added to the set of statements we're tracking. 1141221345Sdim for (; I != E; ++I) { 1142221345Sdim switch (CollectStatementsForCase(*I, 0, FoundCase, ResultStmts)) { 1143221345Sdim case CSFC_Failure: return CSFC_Failure; 1144221345Sdim case CSFC_FallThrough: 1145221345Sdim // A fallthrough result means that the statement was simple and just 1146221345Sdim // included in ResultStmt, keep adding them afterwards. 1147221345Sdim break; 1148221345Sdim case CSFC_Success: 1149221345Sdim // A successful result means that we found the break statement and 1150221345Sdim // stopped statement inclusion. We just ensure that any leftover stmts 1151221345Sdim // are skippable and return success ourselves. 1152221345Sdim for (++I; I != E; ++I) 1153221345Sdim if (CodeGenFunction::ContainsLabel(*I, true)) 1154221345Sdim return CSFC_Failure; 1155221345Sdim return CSFC_Success; 1156245431Sdim } 1157221345Sdim } 1158245431Sdim 1159221345Sdim return Case ? CSFC_Success : CSFC_FallThrough; 1160221345Sdim } 1161221345Sdim 1162221345Sdim // Okay, this is some other statement that we don't handle explicitly, like a 1163221345Sdim // for statement or increment etc. If we are skipping over this statement, 1164221345Sdim // just verify it doesn't have labels, which would make it invalid to elide. 1165221345Sdim if (Case) { 1166221345Sdim if (CodeGenFunction::ContainsLabel(S, true)) 1167221345Sdim return CSFC_Failure; 1168221345Sdim return CSFC_Success; 1169221345Sdim } 1170245431Sdim 1171221345Sdim // Otherwise, we want to include this statement. Everything is cool with that 1172221345Sdim // so long as it doesn't contain a break out of the switch we're in. 1173221345Sdim if (CodeGenFunction::containsBreak(S)) return CSFC_Failure; 1174245431Sdim 1175221345Sdim // Otherwise, everything is great. Include the statement and tell the caller 1176221345Sdim // that we fall through and include the next statement as well. 1177221345Sdim ResultStmts.push_back(S); 1178221345Sdim return CSFC_FallThrough; 1179221345Sdim} 1180221345Sdim 1181221345Sdim/// FindCaseStatementsForValue - Find the case statement being jumped to and 1182221345Sdim/// then invoke CollectStatementsForCase to find the list of statements to emit 1183221345Sdim/// for a switch on constant. See the comment above CollectStatementsForCase 1184221345Sdim/// for more details. 1185221345Sdimstatic bool FindCaseStatementsForValue(const SwitchStmt &S, 1186245431Sdim const llvm::APSInt &ConstantCondValue, 1187226890Sdim SmallVectorImpl<const Stmt*> &ResultStmts, 1188221345Sdim ASTContext &C) { 1189221345Sdim // First step, find the switch case that is being branched to. We can do this 1190221345Sdim // efficiently by scanning the SwitchCase list. 1191221345Sdim const SwitchCase *Case = S.getSwitchCaseList(); 1192221345Sdim const DefaultStmt *DefaultCase = 0; 1193245431Sdim 1194221345Sdim for (; Case; Case = Case->getNextSwitchCase()) { 1195221345Sdim // It's either a default or case. Just remember the default statement in 1196221345Sdim // case we're not jumping to any numbered cases. 1197221345Sdim if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) { 1198221345Sdim DefaultCase = DS; 1199221345Sdim continue; 1200221345Sdim } 1201245431Sdim 1202221345Sdim // Check to see if this case is the one we're looking for. 1203221345Sdim const CaseStmt *CS = cast<CaseStmt>(Case); 1204221345Sdim // Don't handle case ranges yet. 1205221345Sdim if (CS->getRHS()) return false; 1206245431Sdim 1207221345Sdim // If we found our case, remember it as 'case'. 1208226890Sdim if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue) 1209221345Sdim break; 1210221345Sdim } 1211245431Sdim 1212221345Sdim // If we didn't find a matching case, we use a default if it exists, or we 1213221345Sdim // elide the whole switch body! 1214221345Sdim if (Case == 0) { 1215221345Sdim // It is safe to elide the body of the switch if it doesn't contain labels 1216221345Sdim // etc. If it is safe, return successfully with an empty ResultStmts list. 1217221345Sdim if (DefaultCase == 0) 1218221345Sdim return !CodeGenFunction::ContainsLabel(&S); 1219221345Sdim Case = DefaultCase; 1220221345Sdim } 1221221345Sdim 1222221345Sdim // Ok, we know which case is being jumped to, try to collect all the 1223221345Sdim // statements that follow it. This can fail for a variety of reasons. Also, 1224221345Sdim // check to see that the recursive walk actually found our case statement. 1225221345Sdim // Insane cases like this can fail to find it in the recursive walk since we 1226221345Sdim // don't handle every stmt kind: 1227221345Sdim // switch (4) { 1228221345Sdim // while (1) { 1229221345Sdim // case 4: ... 1230221345Sdim bool FoundCase = false; 1231221345Sdim return CollectStatementsForCase(S.getBody(), Case, FoundCase, 1232221345Sdim ResultStmts) != CSFC_Failure && 1233221345Sdim FoundCase; 1234221345Sdim} 1235221345Sdim 1236193326Sedvoid CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) { 1237210299Sed JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog"); 1238199990Srdivacky 1239210299Sed RunCleanupsScope ConditionScope(*this); 1240210299Sed 1241199990Srdivacky if (S.getConditionVariable()) 1242218893Sdim EmitAutoVarDecl(*S.getConditionVariable()); 1243199990Srdivacky 1244235633Sdim // Handle nested switch statements. 1245235633Sdim llvm::SwitchInst *SavedSwitchInsn = SwitchInsn; 1246235633Sdim llvm::BasicBlock *SavedCRBlock = CaseRangeBlock; 1247235633Sdim 1248221345Sdim // See if we can constant fold the condition of the switch and therefore only 1249221345Sdim // emit the live case statement (if any) of the switch. 1250245431Sdim llvm::APSInt ConstantCondValue; 1251221345Sdim if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) { 1252226890Sdim SmallVector<const Stmt*, 4> CaseStmts; 1253221345Sdim if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts, 1254221345Sdim getContext())) { 1255221345Sdim RunCleanupsScope ExecutedScope(*this); 1256221345Sdim 1257235633Sdim // At this point, we are no longer "within" a switch instance, so 1258235633Sdim // we can temporarily enforce this to ensure that any embedded case 1259235633Sdim // statements are not emitted. 1260235633Sdim SwitchInsn = 0; 1261235633Sdim 1262221345Sdim // Okay, we can dead code eliminate everything except this case. Emit the 1263221345Sdim // specified series of statements and we're good. 1264221345Sdim for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i) 1265221345Sdim EmitStmt(CaseStmts[i]); 1266235633Sdim 1267235633Sdim // Now we want to restore the saved switch instance so that nested 1268235633Sdim // switches continue to function properly 1269235633Sdim SwitchInsn = SavedSwitchInsn; 1270235633Sdim 1271221345Sdim return; 1272221345Sdim } 1273221345Sdim } 1274245431Sdim 1275193326Sed llvm::Value *CondV = EmitScalarExpr(S.getCond()); 1276193326Sed 1277193326Sed // Create basic block to hold stuff that comes after switch 1278193326Sed // statement. We also need to create a default block now so that 1279193326Sed // explicit case ranges tests can have a place to jump to on 1280193326Sed // failure. 1281193326Sed llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default"); 1282193326Sed SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock); 1283193326Sed CaseRangeBlock = DefaultBlock; 1284193326Sed 1285193326Sed // Clear the insertion point to indicate we are in unreachable code. 1286193326Sed Builder.ClearInsertionPoint(); 1287193326Sed 1288193326Sed // All break statements jump to NextBlock. If BreakContinueStack is non empty 1289193326Sed // then reuse last ContinueBlock. 1290210299Sed JumpDest OuterContinue; 1291193326Sed if (!BreakContinueStack.empty()) 1292210299Sed OuterContinue = BreakContinueStack.back().ContinueBlock; 1293193326Sed 1294210299Sed BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue)); 1295193326Sed 1296193326Sed // Emit switch body. 1297193326Sed EmitStmt(S.getBody()); 1298198092Srdivacky 1299193326Sed BreakContinueStack.pop_back(); 1300193326Sed 1301193326Sed // Update the default block in case explicit case range tests have 1302193326Sed // been chained on top. 1303235633Sdim SwitchInsn->setDefaultDest(CaseRangeBlock); 1304198092Srdivacky 1305210299Sed // If a default was never emitted: 1306193326Sed if (!DefaultBlock->getParent()) { 1307210299Sed // If we have cleanups, emit the default block so that there's a 1308210299Sed // place to jump through the cleanups from. 1309210299Sed if (ConditionScope.requiresCleanups()) { 1310210299Sed EmitBlock(DefaultBlock); 1311210299Sed 1312210299Sed // Otherwise, just forward the default block to the switch end. 1313210299Sed } else { 1314212904Sdim DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock()); 1315210299Sed delete DefaultBlock; 1316210299Sed } 1317193326Sed } 1318193326Sed 1319212904Sdim ConditionScope.ForceCleanup(); 1320212904Sdim 1321193326Sed // Emit continuation. 1322212904Sdim EmitBlock(SwitchExit.getBlock(), true); 1323193326Sed 1324193326Sed SwitchInsn = SavedSwitchInsn; 1325193326Sed CaseRangeBlock = SavedCRBlock; 1326193326Sed} 1327193326Sed 1328193326Sedstatic std::string 1329199482SrdivackySimplifyConstraint(const char *Constraint, const TargetInfo &Target, 1330226890Sdim SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) { 1331193326Sed std::string Result; 1332198092Srdivacky 1333193326Sed while (*Constraint) { 1334193326Sed switch (*Constraint) { 1335193326Sed default: 1336223017Sdim Result += Target.convertConstraint(Constraint); 1337193326Sed break; 1338193326Sed // Ignore these 1339193326Sed case '*': 1340193326Sed case '?': 1341193326Sed case '!': 1342212904Sdim case '=': // Will see this and the following in mult-alt constraints. 1343212904Sdim case '+': 1344193326Sed break; 1345245431Sdim case '#': // Ignore the rest of the constraint alternative. 1346245431Sdim while (Constraint[1] && Constraint[1] != ',') 1347263509Sdim Constraint++; 1348245431Sdim break; 1349218893Sdim case ',': 1350218893Sdim Result += "|"; 1351212904Sdim break; 1352193326Sed case 'g': 1353193326Sed Result += "imr"; 1354193326Sed break; 1355193326Sed case '[': { 1356193326Sed assert(OutCons && 1357193326Sed "Must pass output names to constraints with a symbolic name"); 1358193326Sed unsigned Index; 1359198092Srdivacky bool result = Target.resolveSymbolicName(Constraint, 1360193326Sed &(*OutCons)[0], 1361193326Sed OutCons->size(), Index); 1362218893Sdim assert(result && "Could not resolve symbolic name"); (void)result; 1363193326Sed Result += llvm::utostr(Index); 1364193326Sed break; 1365193326Sed } 1366193326Sed } 1367198092Srdivacky 1368193326Sed Constraint++; 1369193326Sed } 1370198092Srdivacky 1371193326Sed return Result; 1372193326Sed} 1373193326Sed 1374218893Sdim/// AddVariableConstraints - Look at AsmExpr and if it is a variable declared 1375218893Sdim/// as using a particular register add that as a constraint that will be used 1376218893Sdim/// in this asm stmt. 1377218893Sdimstatic std::string 1378218893SdimAddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr, 1379218893Sdim const TargetInfo &Target, CodeGenModule &CGM, 1380218893Sdim const AsmStmt &Stmt) { 1381218893Sdim const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr); 1382218893Sdim if (!AsmDeclRef) 1383218893Sdim return Constraint; 1384218893Sdim const ValueDecl &Value = *AsmDeclRef->getDecl(); 1385218893Sdim const VarDecl *Variable = dyn_cast<VarDecl>(&Value); 1386218893Sdim if (!Variable) 1387218893Sdim return Constraint; 1388235633Sdim if (Variable->getStorageClass() != SC_Register) 1389235633Sdim return Constraint; 1390218893Sdim AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>(); 1391218893Sdim if (!Attr) 1392218893Sdim return Constraint; 1393226890Sdim StringRef Register = Attr->getLabel(); 1394218893Sdim assert(Target.isValidGCCRegisterName(Register)); 1395224145Sdim // We're using validateOutputConstraint here because we only care if 1396224145Sdim // this is a register constraint. 1397224145Sdim TargetInfo::ConstraintInfo Info(Constraint, ""); 1398224145Sdim if (Target.validateOutputConstraint(Info) && 1399224145Sdim !Info.allowsRegister()) { 1400218893Sdim CGM.ErrorUnsupported(&Stmt, "__asm__"); 1401218893Sdim return Constraint; 1402218893Sdim } 1403224145Sdim // Canonicalize the register here before returning it. 1404224145Sdim Register = Target.getNormalizedGCCRegisterName(Register); 1405218893Sdim return "{" + Register.str() + "}"; 1406218893Sdim} 1407218893Sdim 1408212904Sdimllvm::Value* 1409245431SdimCodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, 1410212904Sdim LValue InputValue, QualType InputType, 1411263509Sdim std::string &ConstraintStr, 1412263509Sdim SourceLocation Loc) { 1413193326Sed llvm::Value *Arg; 1414198092Srdivacky if (Info.allowsRegister() || !Info.allowsMemory()) { 1415252723Sdim if (CodeGenFunction::hasScalarEvaluationKind(InputType)) { 1416263509Sdim Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal(); 1417193326Sed } else { 1418226890Sdim llvm::Type *Ty = ConvertType(InputType); 1419245431Sdim uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty); 1420193326Sed if (Size <= 64 && llvm::isPowerOf2_64(Size)) { 1421218893Sdim Ty = llvm::IntegerType::get(getLLVMContext(), Size); 1422193326Sed Ty = llvm::PointerType::getUnqual(Ty); 1423198092Srdivacky 1424212904Sdim Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(), 1425212904Sdim Ty)); 1426193326Sed } else { 1427212904Sdim Arg = InputValue.getAddress(); 1428193326Sed ConstraintStr += '*'; 1429193326Sed } 1430193326Sed } 1431193326Sed } else { 1432212904Sdim Arg = InputValue.getAddress(); 1433193326Sed ConstraintStr += '*'; 1434193326Sed } 1435198092Srdivacky 1436193326Sed return Arg; 1437193326Sed} 1438193326Sed 1439245431Sdimllvm::Value* CodeGenFunction::EmitAsmInput( 1440212904Sdim const TargetInfo::ConstraintInfo &Info, 1441212904Sdim const Expr *InputExpr, 1442212904Sdim std::string &ConstraintStr) { 1443212904Sdim if (Info.allowsRegister() || !Info.allowsMemory()) 1444252723Sdim if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType())) 1445212904Sdim return EmitScalarExpr(InputExpr); 1446212904Sdim 1447212904Sdim InputExpr = InputExpr->IgnoreParenNoopCasts(getContext()); 1448212904Sdim LValue Dest = EmitLValue(InputExpr); 1449263509Sdim return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr, 1450263509Sdim InputExpr->getExprLoc()); 1451212904Sdim} 1452212904Sdim 1453218893Sdim/// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline 1454218893Sdim/// asm call instruction. The !srcloc MDNode contains a list of constant 1455218893Sdim/// integers which are the source locations of the start of each line in the 1456218893Sdim/// asm. 1457218893Sdimstatic llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str, 1458218893Sdim CodeGenFunction &CGF) { 1459226890Sdim SmallVector<llvm::Value *, 8> Locs; 1460218893Sdim // Add the location of the first line to the MDNode. 1461218893Sdim Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 1462218893Sdim Str->getLocStart().getRawEncoding())); 1463226890Sdim StringRef StrVal = Str->getString(); 1464218893Sdim if (!StrVal.empty()) { 1465218893Sdim const SourceManager &SM = CGF.CGM.getContext().getSourceManager(); 1466235633Sdim const LangOptions &LangOpts = CGF.CGM.getLangOpts(); 1467245431Sdim 1468218893Sdim // Add the location of the start of each subsequent line of the asm to the 1469218893Sdim // MDNode. 1470218893Sdim for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) { 1471218893Sdim if (StrVal[i] != '\n') continue; 1472218893Sdim SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts, 1473252723Sdim CGF.getTarget()); 1474218893Sdim Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 1475218893Sdim LineLoc.getRawEncoding())); 1476218893Sdim } 1477245431Sdim } 1478245431Sdim 1479221345Sdim return llvm::MDNode::get(CGF.getLLVMContext(), Locs); 1480218893Sdim} 1481218893Sdim 1482193326Sedvoid CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { 1483245431Sdim // Assemble the final asm string. 1484245431Sdim std::string AsmString = S.generateAsmString(getContext()); 1485198092Srdivacky 1486193326Sed // Get all the output and input constraints together. 1487226890Sdim SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 1488226890Sdim SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 1489193326Sed 1490198092Srdivacky for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { 1491252723Sdim StringRef Name; 1492252723Sdim if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S)) 1493252723Sdim Name = GAS->getOutputName(i); 1494252723Sdim TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name); 1495252723Sdim bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid; 1496204793Srdivacky assert(IsValid && "Failed to parse output constraint"); 1497193326Sed OutputConstraintInfos.push_back(Info); 1498198092Srdivacky } 1499198092Srdivacky 1500193326Sed for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { 1501252723Sdim StringRef Name; 1502252723Sdim if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S)) 1503252723Sdim Name = GAS->getInputName(i); 1504252723Sdim TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name); 1505252723Sdim bool IsValid = 1506252723Sdim getTarget().validateInputConstraint(OutputConstraintInfos.data(), 1507252723Sdim S.getNumOutputs(), Info); 1508204793Srdivacky assert(IsValid && "Failed to parse input constraint"); (void)IsValid; 1509193326Sed InputConstraintInfos.push_back(Info); 1510193326Sed } 1511198092Srdivacky 1512193326Sed std::string Constraints; 1513198092Srdivacky 1514193326Sed std::vector<LValue> ResultRegDests; 1515193326Sed std::vector<QualType> ResultRegQualTys; 1516224145Sdim std::vector<llvm::Type *> ResultRegTypes; 1517224145Sdim std::vector<llvm::Type *> ResultTruncRegTypes; 1518245431Sdim std::vector<llvm::Type *> ArgTypes; 1519193326Sed std::vector<llvm::Value*> Args; 1520193326Sed 1521193326Sed // Keep track of inout constraints. 1522193326Sed std::string InOutConstraints; 1523193326Sed std::vector<llvm::Value*> InOutArgs; 1524224145Sdim std::vector<llvm::Type*> InOutArgTypes; 1525193326Sed 1526198092Srdivacky for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { 1527193326Sed TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i]; 1528193326Sed 1529193326Sed // Simplify the output constraint. 1530193326Sed std::string OutputConstraint(S.getOutputConstraint(i)); 1531252723Sdim OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, 1532252723Sdim getTarget()); 1533198092Srdivacky 1534193326Sed const Expr *OutExpr = S.getOutputExpr(i); 1535193326Sed OutExpr = OutExpr->IgnoreParenNoopCasts(getContext()); 1536198092Srdivacky 1537223017Sdim OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr, 1538252723Sdim getTarget(), CGM, S); 1539218893Sdim 1540193326Sed LValue Dest = EmitLValue(OutExpr); 1541193326Sed if (!Constraints.empty()) 1542193326Sed Constraints += ','; 1543193326Sed 1544193326Sed // If this is a register output, then make the inline asm return it 1545193326Sed // by-value. If this is a memory result, return the value by-reference. 1546252723Sdim if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) { 1547193326Sed Constraints += "=" + OutputConstraint; 1548193326Sed ResultRegQualTys.push_back(OutExpr->getType()); 1549193326Sed ResultRegDests.push_back(Dest); 1550193326Sed ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType())); 1551193326Sed ResultTruncRegTypes.push_back(ResultRegTypes.back()); 1552198092Srdivacky 1553193326Sed // If this output is tied to an input, and if the input is larger, then 1554193326Sed // we need to set the actual result type of the inline asm node to be the 1555193326Sed // same as the input type. 1556193326Sed if (Info.hasMatchingInput()) { 1557193326Sed unsigned InputNo; 1558193326Sed for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) { 1559193326Sed TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo]; 1560207619Srdivacky if (Input.hasTiedOperand() && Input.getTiedOperand() == i) 1561193326Sed break; 1562193326Sed } 1563193326Sed assert(InputNo != S.getNumInputs() && "Didn't find matching input!"); 1564198092Srdivacky 1565193326Sed QualType InputTy = S.getInputExpr(InputNo)->getType(); 1566207619Srdivacky QualType OutputType = OutExpr->getType(); 1567198092Srdivacky 1568193326Sed uint64_t InputSize = getContext().getTypeSize(InputTy); 1569207619Srdivacky if (getContext().getTypeSize(OutputType) < InputSize) { 1570207619Srdivacky // Form the asm to return the value as a larger integer or fp type. 1571207619Srdivacky ResultRegTypes.back() = ConvertType(InputTy); 1572193326Sed } 1573193326Sed } 1574263509Sdim if (llvm::Type* AdjTy = 1575218893Sdim getTargetHooks().adjustInlineAsmType(*this, OutputConstraint, 1576218893Sdim ResultRegTypes.back())) 1577218893Sdim ResultRegTypes.back() = AdjTy; 1578263509Sdim else { 1579263509Sdim CGM.getDiags().Report(S.getAsmLoc(), 1580263509Sdim diag::err_asm_invalid_type_in_input) 1581263509Sdim << OutExpr->getType() << OutputConstraint; 1582263509Sdim } 1583193326Sed } else { 1584193326Sed ArgTypes.push_back(Dest.getAddress()->getType()); 1585193326Sed Args.push_back(Dest.getAddress()); 1586193326Sed Constraints += "=*"; 1587193326Sed Constraints += OutputConstraint; 1588193326Sed } 1589198092Srdivacky 1590193326Sed if (Info.isReadWrite()) { 1591193326Sed InOutConstraints += ','; 1592193326Sed 1593193326Sed const Expr *InputExpr = S.getOutputExpr(i); 1594245431Sdim llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(), 1595263509Sdim InOutConstraints, 1596263509Sdim InputExpr->getExprLoc()); 1597198092Srdivacky 1598235633Sdim if (llvm::Type* AdjTy = 1599263509Sdim getTargetHooks().adjustInlineAsmType(*this, OutputConstraint, 1600263509Sdim Arg->getType())) 1601235633Sdim Arg = Builder.CreateBitCast(Arg, AdjTy); 1602235633Sdim 1603193326Sed if (Info.allowsRegister()) 1604193326Sed InOutConstraints += llvm::utostr(i); 1605193326Sed else 1606193326Sed InOutConstraints += OutputConstraint; 1607193326Sed 1608193326Sed InOutArgTypes.push_back(Arg->getType()); 1609193326Sed InOutArgs.push_back(Arg); 1610193326Sed } 1611193326Sed } 1612198092Srdivacky 1613193326Sed unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs(); 1614198092Srdivacky 1615193326Sed for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { 1616193326Sed const Expr *InputExpr = S.getInputExpr(i); 1617193326Sed 1618193326Sed TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 1619193326Sed 1620193326Sed if (!Constraints.empty()) 1621193326Sed Constraints += ','; 1622198092Srdivacky 1623193326Sed // Simplify the input constraint. 1624193326Sed std::string InputConstraint(S.getInputConstraint(i)); 1625252723Sdim InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(), 1626193326Sed &OutputConstraintInfos); 1627193326Sed 1628218893Sdim InputConstraint = 1629218893Sdim AddVariableConstraints(InputConstraint, 1630218893Sdim *InputExpr->IgnoreParenNoopCasts(getContext()), 1631252723Sdim getTarget(), CGM, S); 1632218893Sdim 1633245431Sdim llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints); 1634198092Srdivacky 1635193326Sed // If this input argument is tied to a larger output result, extend the 1636193326Sed // input to be the same size as the output. The LLVM backend wants to see 1637193326Sed // the input and output of a matching constraint be the same size. Note 1638193326Sed // that GCC does not define what the top bits are here. We use zext because 1639193326Sed // that is usually cheaper, but LLVM IR should really get an anyext someday. 1640193326Sed if (Info.hasTiedOperand()) { 1641193326Sed unsigned Output = Info.getTiedOperand(); 1642207619Srdivacky QualType OutputType = S.getOutputExpr(Output)->getType(); 1643193326Sed QualType InputTy = InputExpr->getType(); 1644198092Srdivacky 1645207619Srdivacky if (getContext().getTypeSize(OutputType) > 1646193326Sed getContext().getTypeSize(InputTy)) { 1647193326Sed // Use ptrtoint as appropriate so that we can do our extension. 1648193326Sed if (isa<llvm::PointerType>(Arg->getType())) 1649210299Sed Arg = Builder.CreatePtrToInt(Arg, IntPtrTy); 1650226890Sdim llvm::Type *OutputTy = ConvertType(OutputType); 1651207619Srdivacky if (isa<llvm::IntegerType>(OutputTy)) 1652207619Srdivacky Arg = Builder.CreateZExt(Arg, OutputTy); 1653226890Sdim else if (isa<llvm::PointerType>(OutputTy)) 1654226890Sdim Arg = Builder.CreateZExt(Arg, IntPtrTy); 1655226890Sdim else { 1656226890Sdim assert(OutputTy->isFloatingPointTy() && "Unexpected output type"); 1657207619Srdivacky Arg = Builder.CreateFPExt(Arg, OutputTy); 1658226890Sdim } 1659193326Sed } 1660193326Sed } 1661235633Sdim if (llvm::Type* AdjTy = 1662218893Sdim getTargetHooks().adjustInlineAsmType(*this, InputConstraint, 1663218893Sdim Arg->getType())) 1664218893Sdim Arg = Builder.CreateBitCast(Arg, AdjTy); 1665263509Sdim else 1666263509Sdim CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input) 1667263509Sdim << InputExpr->getType() << InputConstraint; 1668198092Srdivacky 1669193326Sed ArgTypes.push_back(Arg->getType()); 1670193326Sed Args.push_back(Arg); 1671193326Sed Constraints += InputConstraint; 1672193326Sed } 1673198092Srdivacky 1674193326Sed // Append the "input" part of inout constraints last. 1675193326Sed for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) { 1676193326Sed ArgTypes.push_back(InOutArgTypes[i]); 1677193326Sed Args.push_back(InOutArgs[i]); 1678193326Sed } 1679193326Sed Constraints += InOutConstraints; 1680198092Srdivacky 1681193326Sed // Clobbers 1682193326Sed for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) { 1683245431Sdim StringRef Clobber = S.getClobber(i); 1684193326Sed 1685224145Sdim if (Clobber != "memory" && Clobber != "cc") 1686252723Sdim Clobber = getTarget().getNormalizedGCCRegisterName(Clobber); 1687198092Srdivacky 1688193326Sed if (i != 0 || NumConstraints != 0) 1689193326Sed Constraints += ','; 1690198092Srdivacky 1691193326Sed Constraints += "~{"; 1692193326Sed Constraints += Clobber; 1693193326Sed Constraints += '}'; 1694193326Sed } 1695198092Srdivacky 1696193326Sed // Add machine specific clobbers 1697252723Sdim std::string MachineClobbers = getTarget().getClobbers(); 1698193326Sed if (!MachineClobbers.empty()) { 1699193326Sed if (!Constraints.empty()) 1700193326Sed Constraints += ','; 1701193326Sed Constraints += MachineClobbers; 1702193326Sed } 1703193326Sed 1704226890Sdim llvm::Type *ResultType; 1705193326Sed if (ResultRegTypes.empty()) 1706235633Sdim ResultType = VoidTy; 1707193326Sed else if (ResultRegTypes.size() == 1) 1708193326Sed ResultType = ResultRegTypes[0]; 1709193326Sed else 1710218893Sdim ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes); 1711198092Srdivacky 1712226890Sdim llvm::FunctionType *FTy = 1713193326Sed llvm::FunctionType::get(ResultType, ArgTypes, false); 1714198092Srdivacky 1715245431Sdim bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0; 1716245431Sdim llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ? 1717245431Sdim llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT; 1718198092Srdivacky llvm::InlineAsm *IA = 1719245431Sdim llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect, 1720245431Sdim /* IsAlignStack */ false, AsmDialect); 1721224145Sdim llvm::CallInst *Result = Builder.CreateCall(IA, Args); 1722252723Sdim Result->addAttribute(llvm::AttributeSet::FunctionIndex, 1723252723Sdim llvm::Attribute::NoUnwind); 1724198092Srdivacky 1725207619Srdivacky // Slap the source location of the inline asm into a !srcloc metadata on the 1726245431Sdim // call. FIXME: Handle metadata for MS-style inline asms. 1727245431Sdim if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S)) 1728245431Sdim Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(), 1729245431Sdim *this)); 1730198092Srdivacky 1731193326Sed // Extract all of the register value results from the asm. 1732193326Sed std::vector<llvm::Value*> RegResults; 1733193326Sed if (ResultRegTypes.size() == 1) { 1734193326Sed RegResults.push_back(Result); 1735193326Sed } else { 1736193326Sed for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) { 1737193326Sed llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult"); 1738193326Sed RegResults.push_back(Tmp); 1739193326Sed } 1740193326Sed } 1741198092Srdivacky 1742193326Sed for (unsigned i = 0, e = RegResults.size(); i != e; ++i) { 1743193326Sed llvm::Value *Tmp = RegResults[i]; 1744198092Srdivacky 1745193326Sed // If the result type of the LLVM IR asm doesn't match the result type of 1746193326Sed // the expression, do the conversion. 1747193326Sed if (ResultRegTypes[i] != ResultTruncRegTypes[i]) { 1748226890Sdim llvm::Type *TruncTy = ResultTruncRegTypes[i]; 1749245431Sdim 1750207619Srdivacky // Truncate the integer result to the right size, note that TruncTy can be 1751207619Srdivacky // a pointer. 1752207619Srdivacky if (TruncTy->isFloatingPointTy()) 1753207619Srdivacky Tmp = Builder.CreateFPTrunc(Tmp, TruncTy); 1754207619Srdivacky else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) { 1755245431Sdim uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy); 1756218893Sdim Tmp = Builder.CreateTrunc(Tmp, 1757218893Sdim llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize)); 1758193326Sed Tmp = Builder.CreateIntToPtr(Tmp, TruncTy); 1759207619Srdivacky } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) { 1760245431Sdim uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType()); 1761218893Sdim Tmp = Builder.CreatePtrToInt(Tmp, 1762218893Sdim llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize)); 1763207619Srdivacky Tmp = Builder.CreateTrunc(Tmp, TruncTy); 1764207619Srdivacky } else if (TruncTy->isIntegerTy()) { 1765207619Srdivacky Tmp = Builder.CreateTrunc(Tmp, TruncTy); 1766218893Sdim } else if (TruncTy->isVectorTy()) { 1767218893Sdim Tmp = Builder.CreateBitCast(Tmp, TruncTy); 1768193326Sed } 1769193326Sed } 1770198092Srdivacky 1771224145Sdim EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]); 1772193326Sed } 1773193326Sed} 1774252723Sdim 1775263509Sdimstatic LValue InitCapturedStruct(CodeGenFunction &CGF, const CapturedStmt &S) { 1776263509Sdim const RecordDecl *RD = S.getCapturedRecordDecl(); 1777263509Sdim QualType RecordTy = CGF.getContext().getRecordType(RD); 1778263509Sdim 1779263509Sdim // Initialize the captured struct. 1780263509Sdim LValue SlotLV = CGF.MakeNaturalAlignAddrLValue( 1781263509Sdim CGF.CreateMemTemp(RecordTy, "agg.captured"), RecordTy); 1782263509Sdim 1783263509Sdim RecordDecl::field_iterator CurField = RD->field_begin(); 1784263509Sdim for (CapturedStmt::capture_init_iterator I = S.capture_init_begin(), 1785263509Sdim E = S.capture_init_end(); 1786263509Sdim I != E; ++I, ++CurField) { 1787263509Sdim LValue LV = CGF.EmitLValueForFieldInitialization(SlotLV, *CurField); 1788263509Sdim CGF.EmitInitializerForField(*CurField, LV, *I, ArrayRef<VarDecl *>()); 1789263509Sdim } 1790263509Sdim 1791263509Sdim return SlotLV; 1792252723Sdim} 1793263509Sdim 1794263509Sdim/// Generate an outlined function for the body of a CapturedStmt, store any 1795263509Sdim/// captured variables into the captured struct, and call the outlined function. 1796263509Sdimllvm::Function * 1797263509SdimCodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) { 1798263509Sdim const CapturedDecl *CD = S.getCapturedDecl(); 1799263509Sdim const RecordDecl *RD = S.getCapturedRecordDecl(); 1800263509Sdim assert(CD->hasBody() && "missing CapturedDecl body"); 1801263509Sdim 1802263509Sdim LValue CapStruct = InitCapturedStruct(*this, S); 1803263509Sdim 1804263509Sdim // Emit the CapturedDecl 1805263509Sdim CodeGenFunction CGF(CGM, true); 1806263509Sdim CGF.CapturedStmtInfo = new CGCapturedStmtInfo(S, K); 1807263509Sdim llvm::Function *F = CGF.GenerateCapturedStmtFunction(CD, RD, S.getLocStart()); 1808263509Sdim delete CGF.CapturedStmtInfo; 1809263509Sdim 1810263509Sdim // Emit call to the helper function. 1811263509Sdim EmitCallOrInvoke(F, CapStruct.getAddress()); 1812263509Sdim 1813263509Sdim return F; 1814263509Sdim} 1815263509Sdim 1816263509Sdim/// Creates the outlined function for a CapturedStmt. 1817263509Sdimllvm::Function * 1818263509SdimCodeGenFunction::GenerateCapturedStmtFunction(const CapturedDecl *CD, 1819263509Sdim const RecordDecl *RD, 1820263509Sdim SourceLocation Loc) { 1821263509Sdim assert(CapturedStmtInfo && 1822263509Sdim "CapturedStmtInfo should be set when generating the captured function"); 1823263509Sdim 1824263509Sdim // Build the argument list. 1825263509Sdim ASTContext &Ctx = CGM.getContext(); 1826263509Sdim FunctionArgList Args; 1827263509Sdim Args.append(CD->param_begin(), CD->param_end()); 1828263509Sdim 1829263509Sdim // Create the function declaration. 1830263509Sdim FunctionType::ExtInfo ExtInfo; 1831263509Sdim const CGFunctionInfo &FuncInfo = 1832263509Sdim CGM.getTypes().arrangeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo, 1833263509Sdim /*IsVariadic=*/false); 1834263509Sdim llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo); 1835263509Sdim 1836263509Sdim llvm::Function *F = 1837263509Sdim llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage, 1838263509Sdim CapturedStmtInfo->getHelperName(), &CGM.getModule()); 1839263509Sdim CGM.SetInternalFunctionAttributes(CD, F, FuncInfo); 1840263509Sdim 1841263509Sdim // Generate the function. 1842263509Sdim StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getBody()->getLocStart()); 1843263509Sdim 1844263509Sdim // Set the context parameter in CapturedStmtInfo. 1845263509Sdim llvm::Value *DeclPtr = LocalDeclMap[CD->getContextParam()]; 1846263509Sdim assert(DeclPtr && "missing context parameter for CapturedStmt"); 1847263509Sdim CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr)); 1848263509Sdim 1849263509Sdim // If 'this' is captured, load it into CXXThisValue. 1850263509Sdim if (CapturedStmtInfo->isCXXThisExprCaptured()) { 1851263509Sdim FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl(); 1852263509Sdim LValue LV = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(), 1853263509Sdim Ctx.getTagDeclType(RD)); 1854263509Sdim LValue ThisLValue = EmitLValueForField(LV, FD); 1855263509Sdim CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal(); 1856263509Sdim } 1857263509Sdim 1858263509Sdim CapturedStmtInfo->EmitBody(*this, CD->getBody()); 1859263509Sdim FinishFunction(CD->getBodyRBrace()); 1860263509Sdim 1861263509Sdim return F; 1862263509Sdim} 1863