1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===// 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 coordinates the per-function state used while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CodeGenModule.h" 16 #include "CGCXXABI.h" 17 #include "CGDebugInfo.h" 18 #include "CGException.h" 19 #include "clang/Basic/TargetInfo.h" 20 #include "clang/AST/APValue.h" 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/Decl.h" 23 #include "clang/AST/DeclCXX.h" 24 #include "clang/AST/StmtCXX.h" 25 #include "clang/Frontend/CodeGenOptions.h" 26 #include "llvm/Target/TargetData.h" 27 #include "llvm/Intrinsics.h" 28 using namespace clang; 29 using namespace CodeGen; 30 31 static void ResolveAllBranchFixups(CodeGenFunction &CGF, 32 llvm::SwitchInst *Switch, 33 llvm::BasicBlock *CleanupEntry); 34 35 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm) 36 : BlockFunction(cgm, *this, Builder), CGM(cgm), 37 Target(CGM.getContext().Target), 38 Builder(cgm.getModule().getContext()), 39 NormalCleanupDest(0), EHCleanupDest(0), NextCleanupDestIndex(1), 40 ExceptionSlot(0), DebugInfo(0), IndirectBranch(0), 41 SwitchInsn(0), CaseRangeBlock(0), 42 DidCallStackSave(false), UnreachableBlock(0), 43 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0), 44 OutermostConditional(0), TerminateLandingPad(0), TerminateHandler(0), 45 TrapBB(0) { 46 47 // Get some frequently used types. 48 LLVMPointerWidth = Target.getPointerWidth(0); 49 llvm::LLVMContext &LLVMContext = CGM.getLLVMContext(); 50 IntPtrTy = llvm::IntegerType::get(LLVMContext, LLVMPointerWidth); 51 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 52 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 53 54 Exceptions = getContext().getLangOptions().Exceptions; 55 CatchUndefined = getContext().getLangOptions().CatchUndefined; 56 CGM.getCXXABI().getMangleContext().startNewFunction(); 57 } 58 59 ASTContext &CodeGenFunction::getContext() const { 60 return CGM.getContext(); 61 } 62 63 64 const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 65 return CGM.getTypes().ConvertTypeForMem(T); 66 } 67 68 const llvm::Type *CodeGenFunction::ConvertType(QualType T) { 69 return CGM.getTypes().ConvertType(T); 70 } 71 72 bool CodeGenFunction::hasAggregateLLVMType(QualType T) { 73 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() || 74 T->isObjCObjectType(); 75 } 76 77 void CodeGenFunction::EmitReturnBlock() { 78 // For cleanliness, we try to avoid emitting the return block for 79 // simple cases. 80 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 81 82 if (CurBB) { 83 assert(!CurBB->getTerminator() && "Unexpected terminated block."); 84 85 // We have a valid insert point, reuse it if it is empty or there are no 86 // explicit jumps to the return block. 87 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) { 88 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB); 89 delete ReturnBlock.getBlock(); 90 } else 91 EmitBlock(ReturnBlock.getBlock()); 92 return; 93 } 94 95 // Otherwise, if the return block is the target of a single direct 96 // branch then we can just put the code in that block instead. This 97 // cleans up functions which started with a unified return block. 98 if (ReturnBlock.getBlock()->hasOneUse()) { 99 llvm::BranchInst *BI = 100 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin()); 101 if (BI && BI->isUnconditional() && 102 BI->getSuccessor(0) == ReturnBlock.getBlock()) { 103 // Reset insertion point and delete the branch. 104 Builder.SetInsertPoint(BI->getParent()); 105 BI->eraseFromParent(); 106 delete ReturnBlock.getBlock(); 107 return; 108 } 109 } 110 111 // FIXME: We are at an unreachable point, there is no reason to emit the block 112 // unless it has uses. However, we still need a place to put the debug 113 // region.end for now. 114 115 EmitBlock(ReturnBlock.getBlock()); 116 } 117 118 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { 119 if (!BB) return; 120 if (!BB->use_empty()) 121 return CGF.CurFn->getBasicBlockList().push_back(BB); 122 delete BB; 123 } 124 125 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 126 assert(BreakContinueStack.empty() && 127 "mismatched push/pop in break/continue stack!"); 128 129 // Emit function epilog (to return). 130 EmitReturnBlock(); 131 132 EmitFunctionInstrumentation("__cyg_profile_func_exit"); 133 134 // Emit debug descriptor for function end. 135 if (CGDebugInfo *DI = getDebugInfo()) { 136 DI->setLocation(EndLoc); 137 DI->EmitFunctionEnd(Builder); 138 } 139 140 EmitFunctionEpilog(*CurFnInfo); 141 EmitEndEHSpec(CurCodeDecl); 142 143 assert(EHStack.empty() && 144 "did not remove all scopes from cleanup stack!"); 145 146 // If someone did an indirect goto, emit the indirect goto block at the end of 147 // the function. 148 if (IndirectBranch) { 149 EmitBlock(IndirectBranch->getParent()); 150 Builder.ClearInsertionPoint(); 151 } 152 153 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 154 llvm::Instruction *Ptr = AllocaInsertPt; 155 AllocaInsertPt = 0; 156 Ptr->eraseFromParent(); 157 158 // If someone took the address of a label but never did an indirect goto, we 159 // made a zero entry PHI node, which is illegal, zap it now. 160 if (IndirectBranch) { 161 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 162 if (PN->getNumIncomingValues() == 0) { 163 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 164 PN->eraseFromParent(); 165 } 166 } 167 168 EmitIfUsed(*this, RethrowBlock.getBlock()); 169 EmitIfUsed(*this, TerminateLandingPad); 170 EmitIfUsed(*this, TerminateHandler); 171 EmitIfUsed(*this, UnreachableBlock); 172 173 if (CGM.getCodeGenOpts().EmitDeclMetadata) 174 EmitDeclMetadata(); 175 } 176 177 /// ShouldInstrumentFunction - Return true if the current function should be 178 /// instrumented with __cyg_profile_func_* calls 179 bool CodeGenFunction::ShouldInstrumentFunction() { 180 if (!CGM.getCodeGenOpts().InstrumentFunctions) 181 return false; 182 if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 183 return false; 184 return true; 185 } 186 187 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 188 /// instrumentation function with the current function and the call site, if 189 /// function instrumentation is enabled. 190 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) { 191 if (!ShouldInstrumentFunction()) 192 return; 193 194 const llvm::PointerType *PointerTy; 195 const llvm::FunctionType *FunctionTy; 196 std::vector<const llvm::Type*> ProfileFuncArgs; 197 198 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site); 199 PointerTy = llvm::Type::getInt8PtrTy(VMContext); 200 ProfileFuncArgs.push_back(PointerTy); 201 ProfileFuncArgs.push_back(PointerTy); 202 FunctionTy = llvm::FunctionType::get( 203 llvm::Type::getVoidTy(VMContext), 204 ProfileFuncArgs, false); 205 206 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn); 207 llvm::CallInst *CallSite = Builder.CreateCall( 208 CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0), 209 llvm::ConstantInt::get(Int32Ty, 0), 210 "callsite"); 211 212 Builder.CreateCall2(F, 213 llvm::ConstantExpr::getBitCast(CurFn, PointerTy), 214 CallSite); 215 } 216 217 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy, 218 llvm::Function *Fn, 219 const FunctionArgList &Args, 220 SourceLocation StartLoc) { 221 const Decl *D = GD.getDecl(); 222 223 DidCallStackSave = false; 224 CurCodeDecl = CurFuncDecl = D; 225 FnRetTy = RetTy; 226 CurFn = Fn; 227 assert(CurFn->isDeclaration() && "Function already has body?"); 228 229 // Pass inline keyword to optimizer if it appears explicitly on any 230 // declaration. 231 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 232 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(), 233 RE = FD->redecls_end(); RI != RE; ++RI) 234 if (RI->isInlineSpecified()) { 235 Fn->addFnAttr(llvm::Attribute::InlineHint); 236 break; 237 } 238 239 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 240 241 // Create a marker to make it easy to insert allocas into the entryblock 242 // later. Don't create this with the builder, because we don't want it 243 // folded. 244 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty); 245 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB); 246 if (Builder.isNamePreserving()) 247 AllocaInsertPt->setName("allocapt"); 248 249 ReturnBlock = getJumpDestInCurrentScope("return"); 250 251 Builder.SetInsertPoint(EntryBB); 252 253 // Emit subprogram debug descriptor. 254 if (CGDebugInfo *DI = getDebugInfo()) { 255 // FIXME: what is going on here and why does it ignore all these 256 // interesting type properties? 257 QualType FnType = 258 getContext().getFunctionType(RetTy, 0, 0, 259 FunctionProtoType::ExtProtoInfo()); 260 261 DI->setLocation(StartLoc); 262 DI->EmitFunctionStart(GD, FnType, CurFn, Builder); 263 } 264 265 EmitFunctionInstrumentation("__cyg_profile_func_enter"); 266 267 // FIXME: Leaked. 268 // CC info is ignored, hopefully? 269 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args, 270 FunctionType::ExtInfo()); 271 272 if (RetTy->isVoidType()) { 273 // Void type; nothing to return. 274 ReturnValue = 0; 275 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect && 276 hasAggregateLLVMType(CurFnInfo->getReturnType())) { 277 // Indirect aggregate return; emit returned value directly into sret slot. 278 // This reduces code size, and affects correctness in C++. 279 ReturnValue = CurFn->arg_begin(); 280 } else { 281 ReturnValue = CreateIRTemp(RetTy, "retval"); 282 } 283 284 EmitStartEHSpec(CurCodeDecl); 285 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 286 287 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) 288 CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 289 290 // If any of the arguments have a variably modified type, make sure to 291 // emit the type size. 292 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 293 i != e; ++i) { 294 QualType Ty = i->second; 295 296 if (Ty->isVariablyModifiedType()) 297 EmitVLASize(Ty); 298 } 299 } 300 301 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) { 302 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl()); 303 assert(FD->getBody()); 304 EmitStmt(FD->getBody()); 305 } 306 307 /// Tries to mark the given function nounwind based on the 308 /// non-existence of any throwing calls within it. We believe this is 309 /// lightweight enough to do at -O0. 310 static void TryMarkNoThrow(llvm::Function *F) { 311 // LLVM treats 'nounwind' on a function as part of the type, so we 312 // can't do this on functions that can be overwritten. 313 if (F->mayBeOverridden()) return; 314 315 for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) 316 for (llvm::BasicBlock::iterator 317 BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) 318 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) 319 if (!Call->doesNotThrow()) 320 return; 321 F->setDoesNotThrow(true); 322 } 323 324 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) { 325 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 326 327 // Check if we should generate debug info for this function. 328 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>()) 329 DebugInfo = CGM.getDebugInfo(); 330 331 FunctionArgList Args; 332 QualType ResTy = FD->getResultType(); 333 334 CurGD = GD; 335 if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance()) 336 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args); 337 338 if (FD->getNumParams()) { 339 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>(); 340 assert(FProto && "Function def must have prototype!"); 341 342 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) 343 Args.push_back(std::make_pair(FD->getParamDecl(i), 344 FProto->getArgType(i))); 345 } 346 347 SourceRange BodyRange; 348 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange(); 349 350 // Emit the standard function prologue. 351 StartFunction(GD, ResTy, Fn, Args, BodyRange.getBegin()); 352 353 // Generate the body of the function. 354 if (isa<CXXDestructorDecl>(FD)) 355 EmitDestructorBody(Args); 356 else if (isa<CXXConstructorDecl>(FD)) 357 EmitConstructorBody(Args); 358 else 359 EmitFunctionBody(Args); 360 361 // Emit the standard function epilogue. 362 FinishFunction(BodyRange.getEnd()); 363 364 // If we haven't marked the function nothrow through other means, do 365 // a quick pass now to see if we can. 366 if (!CurFn->doesNotThrow()) 367 TryMarkNoThrow(CurFn); 368 } 369 370 /// ContainsLabel - Return true if the statement contains a label in it. If 371 /// this statement is not executed normally, it not containing a label means 372 /// that we can just remove the code. 373 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 374 // Null statement, not a label! 375 if (S == 0) return false; 376 377 // If this is a label, we have to emit the code, consider something like: 378 // if (0) { ... foo: bar(); } goto foo; 379 if (isa<LabelStmt>(S)) 380 return true; 381 382 // If this is a case/default statement, and we haven't seen a switch, we have 383 // to emit the code. 384 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 385 return true; 386 387 // If this is a switch statement, we want to ignore cases below it. 388 if (isa<SwitchStmt>(S)) 389 IgnoreCaseStmts = true; 390 391 // Scan subexpressions for verboten labels. 392 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); 393 I != E; ++I) 394 if (ContainsLabel(*I, IgnoreCaseStmts)) 395 return true; 396 397 return false; 398 } 399 400 401 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to 402 /// a constant, or if it does but contains a label, return 0. If it constant 403 /// folds to 'true' and does not contain a label, return 1, if it constant folds 404 /// to 'false' and does not contain a label, return -1. 405 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) { 406 // FIXME: Rename and handle conversion of other evaluatable things 407 // to bool. 408 Expr::EvalResult Result; 409 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() || 410 Result.HasSideEffects) 411 return 0; // Not foldable, not integer or not fully evaluatable. 412 413 if (CodeGenFunction::ContainsLabel(Cond)) 414 return 0; // Contains a label. 415 416 return Result.Val.getInt().getBoolValue() ? 1 : -1; 417 } 418 419 420 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 421 /// statement) to the specified blocks. Based on the condition, this might try 422 /// to simplify the codegen of the conditional based on the branch. 423 /// 424 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 425 llvm::BasicBlock *TrueBlock, 426 llvm::BasicBlock *FalseBlock) { 427 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) 428 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock); 429 430 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 431 // Handle X && Y in a condition. 432 if (CondBOp->getOpcode() == BO_LAnd) { 433 // If we have "1 && X", simplify the code. "0 && X" would have constant 434 // folded if the case was simple enough. 435 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) { 436 // br(1 && X) -> br(X). 437 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 438 } 439 440 // If we have "X && 1", simplify the code to use an uncond branch. 441 // "X && 0" would have been constant folded to 0. 442 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) { 443 // br(X && 1) -> br(X). 444 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 445 } 446 447 // Emit the LHS as a conditional. If the LHS conditional is false, we 448 // want to jump to the FalseBlock. 449 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 450 451 ConditionalEvaluation eval(*this); 452 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock); 453 EmitBlock(LHSTrue); 454 455 // Any temporaries created here are conditional. 456 eval.begin(*this); 457 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 458 eval.end(*this); 459 460 return; 461 } else if (CondBOp->getOpcode() == BO_LOr) { 462 // If we have "0 || X", simplify the code. "1 || X" would have constant 463 // folded if the case was simple enough. 464 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) { 465 // br(0 || X) -> br(X). 466 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 467 } 468 469 // If we have "X || 0", simplify the code to use an uncond branch. 470 // "X || 1" would have been constant folded to 1. 471 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) { 472 // br(X || 0) -> br(X). 473 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 474 } 475 476 // Emit the LHS as a conditional. If the LHS conditional is true, we 477 // want to jump to the TrueBlock. 478 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 479 480 ConditionalEvaluation eval(*this); 481 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse); 482 EmitBlock(LHSFalse); 483 484 // Any temporaries created here are conditional. 485 eval.begin(*this); 486 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 487 eval.end(*this); 488 489 return; 490 } 491 } 492 493 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 494 // br(!x, t, f) -> br(x, f, t) 495 if (CondUOp->getOpcode() == UO_LNot) 496 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock); 497 } 498 499 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 500 // Handle ?: operator. 501 502 // Just ignore GNU ?: extension. 503 if (CondOp->getLHS()) { 504 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 505 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 506 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 507 508 ConditionalEvaluation cond(*this); 509 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock); 510 511 cond.begin(*this); 512 EmitBlock(LHSBlock); 513 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock); 514 cond.end(*this); 515 516 cond.begin(*this); 517 EmitBlock(RHSBlock); 518 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock); 519 cond.end(*this); 520 521 return; 522 } 523 } 524 525 // Emit the code with the fully general case. 526 llvm::Value *CondV = EvaluateExprAsBool(Cond); 527 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock); 528 } 529 530 /// ErrorUnsupported - Print out an error that codegen doesn't support the 531 /// specified stmt yet. 532 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type, 533 bool OmitOnError) { 534 CGM.ErrorUnsupported(S, Type, OmitOnError); 535 } 536 537 void 538 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) { 539 // Ignore empty classes in C++. 540 if (getContext().getLangOptions().CPlusPlus) { 541 if (const RecordType *RT = Ty->getAs<RecordType>()) { 542 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty()) 543 return; 544 } 545 } 546 547 // Cast the dest ptr to the appropriate i8 pointer type. 548 unsigned DestAS = 549 cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace(); 550 const llvm::Type *BP = Builder.getInt8PtrTy(DestAS); 551 if (DestPtr->getType() != BP) 552 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 553 554 // Get size and alignment info for this aggregate. 555 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 556 uint64_t Size = TypeInfo.first / 8; 557 unsigned Align = TypeInfo.second / 8; 558 559 llvm::Value *SizeVal; 560 bool vla; 561 562 // Don't bother emitting a zero-byte memset. 563 if (Size == 0) { 564 // But note that getTypeInfo returns 0 for a VLA. 565 if (const VariableArrayType *vlaType = 566 dyn_cast_or_null<VariableArrayType>( 567 getContext().getAsArrayType(Ty))) { 568 SizeVal = GetVLASize(vlaType); 569 vla = true; 570 } else { 571 return; 572 } 573 } else { 574 SizeVal = llvm::ConstantInt::get(IntPtrTy, Size); 575 vla = false; 576 } 577 578 // If the type contains a pointer to data member we can't memset it to zero. 579 // Instead, create a null constant and copy it to the destination. 580 if (!CGM.getTypes().isZeroInitializable(Ty)) { 581 // FIXME: variable-size types! 582 if (vla) return; 583 584 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty); 585 586 llvm::GlobalVariable *NullVariable = 587 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(), 588 /*isConstant=*/true, 589 llvm::GlobalVariable::PrivateLinkage, 590 NullConstant, llvm::Twine()); 591 llvm::Value *SrcPtr = 592 Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()); 593 594 // Get and call the appropriate llvm.memcpy overload. 595 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align, false); 596 return; 597 } 598 599 // Otherwise, just memset the whole thing to zero. This is legal 600 // because in LLVM, all default initializers (other than the ones we just 601 // handled above) are guaranteed to have a bit pattern of all zeros. 602 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, Align, false); 603 } 604 605 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) { 606 // Make sure that there is a block for the indirect goto. 607 if (IndirectBranch == 0) 608 GetIndirectGotoBlock(); 609 610 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock(); 611 612 // Make sure the indirect branch includes all of the address-taken blocks. 613 IndirectBranch->addDestination(BB); 614 return llvm::BlockAddress::get(CurFn, BB); 615 } 616 617 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 618 // If we already made the indirect branch for indirect goto, return its block. 619 if (IndirectBranch) return IndirectBranch->getParent(); 620 621 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto")); 622 623 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext); 624 625 // Create the PHI node that indirect gotos will add entries to. 626 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest"); 627 628 // Create the indirect branch instruction. 629 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 630 return IndirectBranch->getParent(); 631 } 632 633 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) { 634 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; 635 636 assert(SizeEntry && "Did not emit size for type"); 637 return SizeEntry; 638 } 639 640 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) { 641 assert(Ty->isVariablyModifiedType() && 642 "Must pass variably modified type to EmitVLASizes!"); 643 644 EnsureInsertPoint(); 645 646 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) { 647 // unknown size indication requires no size computation. 648 if (!VAT->getSizeExpr()) 649 return 0; 650 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; 651 652 if (!SizeEntry) { 653 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 654 655 // Get the element size; 656 QualType ElemTy = VAT->getElementType(); 657 llvm::Value *ElemSize; 658 if (ElemTy->isVariableArrayType()) 659 ElemSize = EmitVLASize(ElemTy); 660 else 661 ElemSize = llvm::ConstantInt::get(SizeTy, 662 getContext().getTypeSizeInChars(ElemTy).getQuantity()); 663 664 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr()); 665 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp"); 666 667 SizeEntry = Builder.CreateMul(ElemSize, NumElements); 668 } 669 670 return SizeEntry; 671 } 672 673 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 674 EmitVLASize(AT->getElementType()); 675 return 0; 676 } 677 678 if (const ParenType *PT = dyn_cast<ParenType>(Ty)) { 679 EmitVLASize(PT->getInnerType()); 680 return 0; 681 } 682 683 const PointerType *PT = Ty->getAs<PointerType>(); 684 assert(PT && "unknown VM type!"); 685 EmitVLASize(PT->getPointeeType()); 686 return 0; 687 } 688 689 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) { 690 if (getContext().getBuiltinVaListType()->isArrayType()) 691 return EmitScalarExpr(E); 692 return EmitLValue(E).getAddress(); 693 } 694 695 /// Pops cleanup blocks until the given savepoint is reached. 696 void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) { 697 assert(Old.isValid()); 698 699 while (EHStack.stable_begin() != Old) { 700 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin()); 701 702 // As long as Old strictly encloses the scope's enclosing normal 703 // cleanup, we're going to emit another normal cleanup which 704 // fallthrough can propagate through. 705 bool FallThroughIsBranchThrough = 706 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup()); 707 708 PopCleanupBlock(FallThroughIsBranchThrough); 709 } 710 } 711 712 static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF, 713 EHCleanupScope &Scope) { 714 assert(Scope.isNormalCleanup()); 715 llvm::BasicBlock *Entry = Scope.getNormalBlock(); 716 if (!Entry) { 717 Entry = CGF.createBasicBlock("cleanup"); 718 Scope.setNormalBlock(Entry); 719 } 720 return Entry; 721 } 722 723 static llvm::BasicBlock *CreateEHEntry(CodeGenFunction &CGF, 724 EHCleanupScope &Scope) { 725 assert(Scope.isEHCleanup()); 726 llvm::BasicBlock *Entry = Scope.getEHBlock(); 727 if (!Entry) { 728 Entry = CGF.createBasicBlock("eh.cleanup"); 729 Scope.setEHBlock(Entry); 730 } 731 return Entry; 732 } 733 734 /// Transitions the terminator of the given exit-block of a cleanup to 735 /// be a cleanup switch. 736 static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF, 737 llvm::BasicBlock *Block) { 738 // If it's a branch, turn it into a switch whose default 739 // destination is its original target. 740 llvm::TerminatorInst *Term = Block->getTerminator(); 741 assert(Term && "can't transition block without terminator"); 742 743 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) { 744 assert(Br->isUnconditional()); 745 llvm::LoadInst *Load = 746 new llvm::LoadInst(CGF.getNormalCleanupDestSlot(), "cleanup.dest", Term); 747 llvm::SwitchInst *Switch = 748 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block); 749 Br->eraseFromParent(); 750 return Switch; 751 } else { 752 return cast<llvm::SwitchInst>(Term); 753 } 754 } 755 756 /// Attempts to reduce a cleanup's entry block to a fallthrough. This 757 /// is basically llvm::MergeBlockIntoPredecessor, except 758 /// simplified/optimized for the tighter constraints on cleanup blocks. 759 /// 760 /// Returns the new block, whatever it is. 761 static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF, 762 llvm::BasicBlock *Entry) { 763 llvm::BasicBlock *Pred = Entry->getSinglePredecessor(); 764 if (!Pred) return Entry; 765 766 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator()); 767 if (!Br || Br->isConditional()) return Entry; 768 assert(Br->getSuccessor(0) == Entry); 769 770 // If we were previously inserting at the end of the cleanup entry 771 // block, we'll need to continue inserting at the end of the 772 // predecessor. 773 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry; 774 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end()); 775 776 // Kill the branch. 777 Br->eraseFromParent(); 778 779 // Merge the blocks. 780 Pred->getInstList().splice(Pred->end(), Entry->getInstList()); 781 782 // Replace all uses of the entry with the predecessor, in case there 783 // are phis in the cleanup. 784 Entry->replaceAllUsesWith(Pred); 785 786 // Kill the entry block. 787 Entry->eraseFromParent(); 788 789 if (WasInsertBlock) 790 CGF.Builder.SetInsertPoint(Pred); 791 792 return Pred; 793 } 794 795 static void EmitCleanup(CodeGenFunction &CGF, 796 EHScopeStack::Cleanup *Fn, 797 bool ForEH, 798 llvm::Value *ActiveFlag) { 799 // EH cleanups always occur within a terminate scope. 800 if (ForEH) CGF.EHStack.pushTerminate(); 801 802 // If there's an active flag, load it and skip the cleanup if it's 803 // false. 804 llvm::BasicBlock *ContBB = 0; 805 if (ActiveFlag) { 806 ContBB = CGF.createBasicBlock("cleanup.done"); 807 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action"); 808 llvm::Value *IsActive 809 = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active"); 810 CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB); 811 CGF.EmitBlock(CleanupBB); 812 } 813 814 // Ask the cleanup to emit itself. 815 Fn->Emit(CGF, ForEH); 816 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?"); 817 818 // Emit the continuation block if there was an active flag. 819 if (ActiveFlag) 820 CGF.EmitBlock(ContBB); 821 822 // Leave the terminate scope. 823 if (ForEH) CGF.EHStack.popTerminate(); 824 } 825 826 static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit, 827 llvm::BasicBlock *From, 828 llvm::BasicBlock *To) { 829 // Exit is the exit block of a cleanup, so it always terminates in 830 // an unconditional branch or a switch. 831 llvm::TerminatorInst *Term = Exit->getTerminator(); 832 833 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) { 834 assert(Br->isUnconditional() && Br->getSuccessor(0) == From); 835 Br->setSuccessor(0, To); 836 } else { 837 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term); 838 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I) 839 if (Switch->getSuccessor(I) == From) 840 Switch->setSuccessor(I, To); 841 } 842 } 843 844 /// Pops a cleanup block. If the block includes a normal cleanup, the 845 /// current insertion point is threaded through the cleanup, as are 846 /// any branch fixups on the cleanup. 847 void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { 848 assert(!EHStack.empty() && "cleanup stack is empty!"); 849 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!"); 850 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin()); 851 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups()); 852 853 // Remember activation information. 854 bool IsActive = Scope.isActive(); 855 llvm::Value *NormalActiveFlag = 856 Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag() : 0; 857 llvm::Value *EHActiveFlag = 858 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag() : 0; 859 860 // Check whether we need an EH cleanup. This is only true if we've 861 // generated a lazy EH cleanup block. 862 bool RequiresEHCleanup = Scope.hasEHBranches(); 863 864 // Check the three conditions which might require a normal cleanup: 865 866 // - whether there are branch fix-ups through this cleanup 867 unsigned FixupDepth = Scope.getFixupDepth(); 868 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth; 869 870 // - whether there are branch-throughs or branch-afters 871 bool HasExistingBranches = Scope.hasBranches(); 872 873 // - whether there's a fallthrough 874 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock(); 875 bool HasFallthrough = (FallthroughSource != 0 && IsActive); 876 877 // Branch-through fall-throughs leave the insertion point set to the 878 // end of the last cleanup, which points to the current scope. The 879 // rest of IR gen doesn't need to worry about this; it only happens 880 // during the execution of PopCleanupBlocks(). 881 bool HasPrebranchedFallthrough = 882 (FallthroughSource && FallthroughSource->getTerminator()); 883 884 // If this is a normal cleanup, then having a prebranched 885 // fallthrough implies that the fallthrough source unconditionally 886 // jumps here. 887 assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough || 888 (Scope.getNormalBlock() && 889 FallthroughSource->getTerminator()->getSuccessor(0) 890 == Scope.getNormalBlock())); 891 892 bool RequiresNormalCleanup = false; 893 if (Scope.isNormalCleanup() && 894 (HasFixups || HasExistingBranches || HasFallthrough)) { 895 RequiresNormalCleanup = true; 896 } 897 898 // Even if we don't need the normal cleanup, we might still have 899 // prebranched fallthrough to worry about. 900 if (Scope.isNormalCleanup() && !RequiresNormalCleanup && 901 HasPrebranchedFallthrough) { 902 assert(!IsActive); 903 904 llvm::BasicBlock *NormalEntry = Scope.getNormalBlock(); 905 906 // If we're branching through this cleanup, just forward the 907 // prebranched fallthrough to the next cleanup, leaving the insert 908 // point in the old block. 909 if (FallthroughIsBranchThrough) { 910 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup()); 911 llvm::BasicBlock *EnclosingEntry = 912 CreateNormalEntry(*this, cast<EHCleanupScope>(S)); 913 914 ForwardPrebranchedFallthrough(FallthroughSource, 915 NormalEntry, EnclosingEntry); 916 assert(NormalEntry->use_empty() && 917 "uses of entry remain after forwarding?"); 918 delete NormalEntry; 919 920 // Otherwise, we're branching out; just emit the next block. 921 } else { 922 EmitBlock(NormalEntry); 923 SimplifyCleanupEntry(*this, NormalEntry); 924 } 925 } 926 927 // If we don't need the cleanup at all, we're done. 928 if (!RequiresNormalCleanup && !RequiresEHCleanup) { 929 EHStack.popCleanup(); // safe because there are no fixups 930 assert(EHStack.getNumBranchFixups() == 0 || 931 EHStack.hasNormalCleanups()); 932 return; 933 } 934 935 // Copy the cleanup emission data out. Note that SmallVector 936 // guarantees maximal alignment for its buffer regardless of its 937 // type parameter. 938 llvm::SmallVector<char, 8*sizeof(void*)> CleanupBuffer; 939 CleanupBuffer.reserve(Scope.getCleanupSize()); 940 memcpy(CleanupBuffer.data(), 941 Scope.getCleanupBuffer(), Scope.getCleanupSize()); 942 CleanupBuffer.set_size(Scope.getCleanupSize()); 943 EHScopeStack::Cleanup *Fn = 944 reinterpret_cast<EHScopeStack::Cleanup*>(CleanupBuffer.data()); 945 946 // We want to emit the EH cleanup after the normal cleanup, but go 947 // ahead and do the setup for the EH cleanup while the scope is still 948 // alive. 949 llvm::BasicBlock *EHEntry = 0; 950 llvm::SmallVector<llvm::Instruction*, 2> EHInstsToAppend; 951 if (RequiresEHCleanup) { 952 EHEntry = CreateEHEntry(*this, Scope); 953 954 // Figure out the branch-through dest if necessary. 955 llvm::BasicBlock *EHBranchThroughDest = 0; 956 if (Scope.hasEHBranchThroughs()) { 957 assert(Scope.getEnclosingEHCleanup() != EHStack.stable_end()); 958 EHScope &S = *EHStack.find(Scope.getEnclosingEHCleanup()); 959 EHBranchThroughDest = CreateEHEntry(*this, cast<EHCleanupScope>(S)); 960 } 961 962 // If we have exactly one branch-after and no branch-throughs, we 963 // can dispatch it without a switch. 964 if (!Scope.hasEHBranchThroughs() && 965 Scope.getNumEHBranchAfters() == 1) { 966 assert(!EHBranchThroughDest); 967 968 // TODO: remove the spurious eh.cleanup.dest stores if this edge 969 // never went through any switches. 970 llvm::BasicBlock *BranchAfterDest = Scope.getEHBranchAfterBlock(0); 971 EHInstsToAppend.push_back(llvm::BranchInst::Create(BranchAfterDest)); 972 973 // Otherwise, if we have any branch-afters, we need a switch. 974 } else if (Scope.getNumEHBranchAfters()) { 975 // The default of the switch belongs to the branch-throughs if 976 // they exist. 977 llvm::BasicBlock *Default = 978 (EHBranchThroughDest ? EHBranchThroughDest : getUnreachableBlock()); 979 980 const unsigned SwitchCapacity = Scope.getNumEHBranchAfters(); 981 982 llvm::LoadInst *Load = 983 new llvm::LoadInst(getEHCleanupDestSlot(), "cleanup.dest"); 984 llvm::SwitchInst *Switch = 985 llvm::SwitchInst::Create(Load, Default, SwitchCapacity); 986 987 EHInstsToAppend.push_back(Load); 988 EHInstsToAppend.push_back(Switch); 989 990 for (unsigned I = 0, E = Scope.getNumEHBranchAfters(); I != E; ++I) 991 Switch->addCase(Scope.getEHBranchAfterIndex(I), 992 Scope.getEHBranchAfterBlock(I)); 993 994 // Otherwise, we have only branch-throughs; jump to the next EH 995 // cleanup. 996 } else { 997 assert(EHBranchThroughDest); 998 EHInstsToAppend.push_back(llvm::BranchInst::Create(EHBranchThroughDest)); 999 } 1000 } 1001 1002 if (!RequiresNormalCleanup) { 1003 EHStack.popCleanup(); 1004 } else { 1005 // If we have a fallthrough and no other need for the cleanup, 1006 // emit it directly. 1007 if (HasFallthrough && !HasPrebranchedFallthrough && 1008 !HasFixups && !HasExistingBranches) { 1009 1010 // Fixups can cause us to optimistically create a normal block, 1011 // only to later have no real uses for it. Just delete it in 1012 // this case. 1013 // TODO: we can potentially simplify all the uses after this. 1014 if (Scope.getNormalBlock()) { 1015 Scope.getNormalBlock()->replaceAllUsesWith(getUnreachableBlock()); 1016 delete Scope.getNormalBlock(); 1017 } 1018 1019 EHStack.popCleanup(); 1020 1021 EmitCleanup(*this, Fn, /*ForEH*/ false, NormalActiveFlag); 1022 1023 // Otherwise, the best approach is to thread everything through 1024 // the cleanup block and then try to clean up after ourselves. 1025 } else { 1026 // Force the entry block to exist. 1027 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope); 1028 1029 // I. Set up the fallthrough edge in. 1030 1031 // If there's a fallthrough, we need to store the cleanup 1032 // destination index. For fall-throughs this is always zero. 1033 if (HasFallthrough) { 1034 if (!HasPrebranchedFallthrough) 1035 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot()); 1036 1037 // Otherwise, clear the IP if we don't have fallthrough because 1038 // the cleanup is inactive. We don't need to save it because 1039 // it's still just FallthroughSource. 1040 } else if (FallthroughSource) { 1041 assert(!IsActive && "source without fallthrough for active cleanup"); 1042 Builder.ClearInsertionPoint(); 1043 } 1044 1045 // II. Emit the entry block. This implicitly branches to it if 1046 // we have fallthrough. All the fixups and existing branches 1047 // should already be branched to it. 1048 EmitBlock(NormalEntry); 1049 1050 // III. Figure out where we're going and build the cleanup 1051 // epilogue. 1052 1053 bool HasEnclosingCleanups = 1054 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end()); 1055 1056 // Compute the branch-through dest if we need it: 1057 // - if there are branch-throughs threaded through the scope 1058 // - if fall-through is a branch-through 1059 // - if there are fixups that will be optimistically forwarded 1060 // to the enclosing cleanup 1061 llvm::BasicBlock *BranchThroughDest = 0; 1062 if (Scope.hasBranchThroughs() || 1063 (FallthroughSource && FallthroughIsBranchThrough) || 1064 (HasFixups && HasEnclosingCleanups)) { 1065 assert(HasEnclosingCleanups); 1066 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup()); 1067 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S)); 1068 } 1069 1070 llvm::BasicBlock *FallthroughDest = 0; 1071 llvm::SmallVector<llvm::Instruction*, 2> InstsToAppend; 1072 1073 // If there's exactly one branch-after and no other threads, 1074 // we can route it without a switch. 1075 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough && 1076 Scope.getNumBranchAfters() == 1) { 1077 assert(!BranchThroughDest || !IsActive); 1078 1079 // TODO: clean up the possibly dead stores to the cleanup dest slot. 1080 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0); 1081 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter)); 1082 1083 // Build a switch-out if we need it: 1084 // - if there are branch-afters threaded through the scope 1085 // - if fall-through is a branch-after 1086 // - if there are fixups that have nowhere left to go and 1087 // so must be immediately resolved 1088 } else if (Scope.getNumBranchAfters() || 1089 (HasFallthrough && !FallthroughIsBranchThrough) || 1090 (HasFixups && !HasEnclosingCleanups)) { 1091 1092 llvm::BasicBlock *Default = 1093 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock()); 1094 1095 // TODO: base this on the number of branch-afters and fixups 1096 const unsigned SwitchCapacity = 10; 1097 1098 llvm::LoadInst *Load = 1099 new llvm::LoadInst(getNormalCleanupDestSlot(), "cleanup.dest"); 1100 llvm::SwitchInst *Switch = 1101 llvm::SwitchInst::Create(Load, Default, SwitchCapacity); 1102 1103 InstsToAppend.push_back(Load); 1104 InstsToAppend.push_back(Switch); 1105 1106 // Branch-after fallthrough. 1107 if (FallthroughSource && !FallthroughIsBranchThrough) { 1108 FallthroughDest = createBasicBlock("cleanup.cont"); 1109 if (HasFallthrough) 1110 Switch->addCase(Builder.getInt32(0), FallthroughDest); 1111 } 1112 1113 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) { 1114 Switch->addCase(Scope.getBranchAfterIndex(I), 1115 Scope.getBranchAfterBlock(I)); 1116 } 1117 1118 // If there aren't any enclosing cleanups, we can resolve all 1119 // the fixups now. 1120 if (HasFixups && !HasEnclosingCleanups) 1121 ResolveAllBranchFixups(*this, Switch, NormalEntry); 1122 } else { 1123 // We should always have a branch-through destination in this case. 1124 assert(BranchThroughDest); 1125 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest)); 1126 } 1127 1128 // IV. Pop the cleanup and emit it. 1129 EHStack.popCleanup(); 1130 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups); 1131 1132 EmitCleanup(*this, Fn, /*ForEH*/ false, NormalActiveFlag); 1133 1134 // Append the prepared cleanup prologue from above. 1135 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock(); 1136 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I) 1137 NormalExit->getInstList().push_back(InstsToAppend[I]); 1138 1139 // Optimistically hope that any fixups will continue falling through. 1140 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups(); 1141 I < E; ++I) { 1142 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I); 1143 if (!Fixup.Destination) continue; 1144 if (!Fixup.OptimisticBranchBlock) { 1145 new llvm::StoreInst(Builder.getInt32(Fixup.DestinationIndex), 1146 getNormalCleanupDestSlot(), 1147 Fixup.InitialBranch); 1148 Fixup.InitialBranch->setSuccessor(0, NormalEntry); 1149 } 1150 Fixup.OptimisticBranchBlock = NormalExit; 1151 } 1152 1153 // V. Set up the fallthrough edge out. 1154 1155 // Case 1: a fallthrough source exists but shouldn't branch to 1156 // the cleanup because the cleanup is inactive. 1157 if (!HasFallthrough && FallthroughSource) { 1158 assert(!IsActive); 1159 1160 // If we have a prebranched fallthrough, that needs to be 1161 // forwarded to the right block. 1162 if (HasPrebranchedFallthrough) { 1163 llvm::BasicBlock *Next; 1164 if (FallthroughIsBranchThrough) { 1165 Next = BranchThroughDest; 1166 assert(!FallthroughDest); 1167 } else { 1168 Next = FallthroughDest; 1169 } 1170 1171 ForwardPrebranchedFallthrough(FallthroughSource, NormalEntry, Next); 1172 } 1173 Builder.SetInsertPoint(FallthroughSource); 1174 1175 // Case 2: a fallthrough source exists and should branch to the 1176 // cleanup, but we're not supposed to branch through to the next 1177 // cleanup. 1178 } else if (HasFallthrough && FallthroughDest) { 1179 assert(!FallthroughIsBranchThrough); 1180 EmitBlock(FallthroughDest); 1181 1182 // Case 3: a fallthrough source exists and should branch to the 1183 // cleanup and then through to the next. 1184 } else if (HasFallthrough) { 1185 // Everything is already set up for this. 1186 1187 // Case 4: no fallthrough source exists. 1188 } else { 1189 Builder.ClearInsertionPoint(); 1190 } 1191 1192 // VI. Assorted cleaning. 1193 1194 // Check whether we can merge NormalEntry into a single predecessor. 1195 // This might invalidate (non-IR) pointers to NormalEntry. 1196 llvm::BasicBlock *NewNormalEntry = 1197 SimplifyCleanupEntry(*this, NormalEntry); 1198 1199 // If it did invalidate those pointers, and NormalEntry was the same 1200 // as NormalExit, go back and patch up the fixups. 1201 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit) 1202 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups(); 1203 I < E; ++I) 1204 CGF.EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry; 1205 } 1206 } 1207 1208 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0); 1209 1210 // Emit the EH cleanup if required. 1211 if (RequiresEHCleanup) { 1212 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP(); 1213 1214 EmitBlock(EHEntry); 1215 EmitCleanup(*this, Fn, /*ForEH*/ true, EHActiveFlag); 1216 1217 // Append the prepared cleanup prologue from above. 1218 llvm::BasicBlock *EHExit = Builder.GetInsertBlock(); 1219 for (unsigned I = 0, E = EHInstsToAppend.size(); I != E; ++I) 1220 EHExit->getInstList().push_back(EHInstsToAppend[I]); 1221 1222 Builder.restoreIP(SavedIP); 1223 1224 SimplifyCleanupEntry(*this, EHEntry); 1225 } 1226 } 1227 1228 /// Terminate the current block by emitting a branch which might leave 1229 /// the current cleanup-protected scope. The target scope may not yet 1230 /// be known, in which case this will require a fixup. 1231 /// 1232 /// As a side-effect, this method clears the insertion point. 1233 void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) { 1234 assert(Dest.getScopeDepth().encloses(EHStack.getInnermostNormalCleanup()) 1235 && "stale jump destination"); 1236 1237 if (!HaveInsertPoint()) 1238 return; 1239 1240 // Create the branch. 1241 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock()); 1242 1243 // Calculate the innermost active normal cleanup. 1244 EHScopeStack::stable_iterator 1245 TopCleanup = EHStack.getInnermostActiveNormalCleanup(); 1246 1247 // If we're not in an active normal cleanup scope, or if the 1248 // destination scope is within the innermost active normal cleanup 1249 // scope, we don't need to worry about fixups. 1250 if (TopCleanup == EHStack.stable_end() || 1251 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid 1252 Builder.ClearInsertionPoint(); 1253 return; 1254 } 1255 1256 // If we can't resolve the destination cleanup scope, just add this 1257 // to the current cleanup scope as a branch fixup. 1258 if (!Dest.getScopeDepth().isValid()) { 1259 BranchFixup &Fixup = EHStack.addBranchFixup(); 1260 Fixup.Destination = Dest.getBlock(); 1261 Fixup.DestinationIndex = Dest.getDestIndex(); 1262 Fixup.InitialBranch = BI; 1263 Fixup.OptimisticBranchBlock = 0; 1264 1265 Builder.ClearInsertionPoint(); 1266 return; 1267 } 1268 1269 // Otherwise, thread through all the normal cleanups in scope. 1270 1271 // Store the index at the start. 1272 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex()); 1273 new llvm::StoreInst(Index, getNormalCleanupDestSlot(), BI); 1274 1275 // Adjust BI to point to the first cleanup block. 1276 { 1277 EHCleanupScope &Scope = 1278 cast<EHCleanupScope>(*EHStack.find(TopCleanup)); 1279 BI->setSuccessor(0, CreateNormalEntry(*this, Scope)); 1280 } 1281 1282 // Add this destination to all the scopes involved. 1283 EHScopeStack::stable_iterator I = TopCleanup; 1284 EHScopeStack::stable_iterator E = Dest.getScopeDepth(); 1285 if (E.strictlyEncloses(I)) { 1286 while (true) { 1287 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I)); 1288 assert(Scope.isNormalCleanup()); 1289 I = Scope.getEnclosingNormalCleanup(); 1290 1291 // If this is the last cleanup we're propagating through, tell it 1292 // that there's a resolved jump moving through it. 1293 if (!E.strictlyEncloses(I)) { 1294 Scope.addBranchAfter(Index, Dest.getBlock()); 1295 break; 1296 } 1297 1298 // Otherwise, tell the scope that there's a jump propoagating 1299 // through it. If this isn't new information, all the rest of 1300 // the work has been done before. 1301 if (!Scope.addBranchThrough(Dest.getBlock())) 1302 break; 1303 } 1304 } 1305 1306 Builder.ClearInsertionPoint(); 1307 } 1308 1309 void CodeGenFunction::EmitBranchThroughEHCleanup(UnwindDest Dest) { 1310 // We should never get invalid scope depths for an UnwindDest; that 1311 // implies that the destination wasn't set up correctly. 1312 assert(Dest.getScopeDepth().isValid() && "invalid scope depth on EH dest?"); 1313 1314 if (!HaveInsertPoint()) 1315 return; 1316 1317 // Create the branch. 1318 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock()); 1319 1320 // Calculate the innermost active cleanup. 1321 EHScopeStack::stable_iterator 1322 InnermostCleanup = EHStack.getInnermostActiveEHCleanup(); 1323 1324 // If the destination is in the same EH cleanup scope as us, we 1325 // don't need to thread through anything. 1326 if (InnermostCleanup.encloses(Dest.getScopeDepth())) { 1327 Builder.ClearInsertionPoint(); 1328 return; 1329 } 1330 assert(InnermostCleanup != EHStack.stable_end()); 1331 1332 // Store the index at the start. 1333 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex()); 1334 new llvm::StoreInst(Index, getEHCleanupDestSlot(), BI); 1335 1336 // Adjust BI to point to the first cleanup block. 1337 { 1338 EHCleanupScope &Scope = 1339 cast<EHCleanupScope>(*EHStack.find(InnermostCleanup)); 1340 BI->setSuccessor(0, CreateEHEntry(*this, Scope)); 1341 } 1342 1343 // Add this destination to all the scopes involved. 1344 for (EHScopeStack::stable_iterator 1345 I = InnermostCleanup, E = Dest.getScopeDepth(); ; ) { 1346 assert(E.strictlyEncloses(I)); 1347 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I)); 1348 assert(Scope.isEHCleanup()); 1349 I = Scope.getEnclosingEHCleanup(); 1350 1351 // If this is the last cleanup we're propagating through, add this 1352 // as a branch-after. 1353 if (I == E) { 1354 Scope.addEHBranchAfter(Index, Dest.getBlock()); 1355 break; 1356 } 1357 1358 // Otherwise, add it as a branch-through. If this isn't new 1359 // information, all the rest of the work has been done before. 1360 if (!Scope.addEHBranchThrough(Dest.getBlock())) 1361 break; 1362 } 1363 1364 Builder.ClearInsertionPoint(); 1365 } 1366 1367 /// All the branch fixups on the EH stack have propagated out past the 1368 /// outermost normal cleanup; resolve them all by adding cases to the 1369 /// given switch instruction. 1370 static void ResolveAllBranchFixups(CodeGenFunction &CGF, 1371 llvm::SwitchInst *Switch, 1372 llvm::BasicBlock *CleanupEntry) { 1373 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded; 1374 1375 for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) { 1376 // Skip this fixup if its destination isn't set. 1377 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I); 1378 if (Fixup.Destination == 0) continue; 1379 1380 // If there isn't an OptimisticBranchBlock, then InitialBranch is 1381 // still pointing directly to its destination; forward it to the 1382 // appropriate cleanup entry. This is required in the specific 1383 // case of 1384 // { std::string s; goto lbl; } 1385 // lbl: 1386 // i.e. where there's an unresolved fixup inside a single cleanup 1387 // entry which we're currently popping. 1388 if (Fixup.OptimisticBranchBlock == 0) { 1389 new llvm::StoreInst(CGF.Builder.getInt32(Fixup.DestinationIndex), 1390 CGF.getNormalCleanupDestSlot(), 1391 Fixup.InitialBranch); 1392 Fixup.InitialBranch->setSuccessor(0, CleanupEntry); 1393 } 1394 1395 // Don't add this case to the switch statement twice. 1396 if (!CasesAdded.insert(Fixup.Destination)) continue; 1397 1398 Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex), 1399 Fixup.Destination); 1400 } 1401 1402 CGF.EHStack.clearFixups(); 1403 } 1404 1405 void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) { 1406 assert(Block && "resolving a null target block"); 1407 if (!EHStack.getNumBranchFixups()) return; 1408 1409 assert(EHStack.hasNormalCleanups() && 1410 "branch fixups exist with no normal cleanups on stack"); 1411 1412 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks; 1413 bool ResolvedAny = false; 1414 1415 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) { 1416 // Skip this fixup if its destination doesn't match. 1417 BranchFixup &Fixup = EHStack.getBranchFixup(I); 1418 if (Fixup.Destination != Block) continue; 1419 1420 Fixup.Destination = 0; 1421 ResolvedAny = true; 1422 1423 // If it doesn't have an optimistic branch block, LatestBranch is 1424 // already pointing to the right place. 1425 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock; 1426 if (!BranchBB) 1427 continue; 1428 1429 // Don't process the same optimistic branch block twice. 1430 if (!ModifiedOptimisticBlocks.insert(BranchBB)) 1431 continue; 1432 1433 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB); 1434 1435 // Add a case to the switch. 1436 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block); 1437 } 1438 1439 if (ResolvedAny) 1440 EHStack.popNullFixups(); 1441 } 1442 1443 static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack, 1444 EHScopeStack::stable_iterator C) { 1445 // If we needed a normal block for any reason, that counts. 1446 if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock()) 1447 return true; 1448 1449 // Check whether any enclosed cleanups were needed. 1450 for (EHScopeStack::stable_iterator 1451 I = EHStack.getInnermostNormalCleanup(); 1452 I != C; ) { 1453 assert(C.strictlyEncloses(I)); 1454 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I)); 1455 if (S.getNormalBlock()) return true; 1456 I = S.getEnclosingNormalCleanup(); 1457 } 1458 1459 return false; 1460 } 1461 1462 static bool IsUsedAsEHCleanup(EHScopeStack &EHStack, 1463 EHScopeStack::stable_iterator C) { 1464 // If we needed an EH block for any reason, that counts. 1465 if (cast<EHCleanupScope>(*EHStack.find(C)).getEHBlock()) 1466 return true; 1467 1468 // Check whether any enclosed cleanups were needed. 1469 for (EHScopeStack::stable_iterator 1470 I = EHStack.getInnermostEHCleanup(); I != C; ) { 1471 assert(C.strictlyEncloses(I)); 1472 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I)); 1473 if (S.getEHBlock()) return true; 1474 I = S.getEnclosingEHCleanup(); 1475 } 1476 1477 return false; 1478 } 1479 1480 enum ForActivation_t { 1481 ForActivation, 1482 ForDeactivation 1483 }; 1484 1485 /// The given cleanup block is changing activation state. Configure a 1486 /// cleanup variable if necessary. 1487 /// 1488 /// It would be good if we had some way of determining if there were 1489 /// extra uses *after* the change-over point. 1490 static void SetupCleanupBlockActivation(CodeGenFunction &CGF, 1491 EHScopeStack::stable_iterator C, 1492 ForActivation_t Kind) { 1493 EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C)); 1494 1495 // We always need the flag if we're activating the cleanup, because 1496 // we have to assume that the current location doesn't necessarily 1497 // dominate all future uses of the cleanup. 1498 bool NeedFlag = (Kind == ForActivation); 1499 1500 // Calculate whether the cleanup was used: 1501 1502 // - as a normal cleanup 1503 if (Scope.isNormalCleanup() && IsUsedAsNormalCleanup(CGF.EHStack, C)) { 1504 Scope.setTestFlagInNormalCleanup(); 1505 NeedFlag = true; 1506 } 1507 1508 // - as an EH cleanup 1509 if (Scope.isEHCleanup() && IsUsedAsEHCleanup(CGF.EHStack, C)) { 1510 Scope.setTestFlagInEHCleanup(); 1511 NeedFlag = true; 1512 } 1513 1514 // If it hasn't yet been used as either, we're done. 1515 if (!NeedFlag) return; 1516 1517 llvm::AllocaInst *Var = Scope.getActiveFlag(); 1518 if (!Var) { 1519 Var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "cleanup.isactive"); 1520 Scope.setActiveFlag(Var); 1521 1522 // Initialize to true or false depending on whether it was 1523 // active up to this point. 1524 CGF.InitTempAlloca(Var, CGF.Builder.getInt1(Kind == ForDeactivation)); 1525 } 1526 1527 CGF.Builder.CreateStore(CGF.Builder.getInt1(Kind == ForActivation), Var); 1528 } 1529 1530 /// Activate a cleanup that was created in an inactivated state. 1531 void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C) { 1532 assert(C != EHStack.stable_end() && "activating bottom of stack?"); 1533 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C)); 1534 assert(!Scope.isActive() && "double activation"); 1535 1536 SetupCleanupBlockActivation(*this, C, ForActivation); 1537 1538 Scope.setActive(true); 1539 } 1540 1541 /// Deactive a cleanup that was created in an active state. 1542 void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C) { 1543 assert(C != EHStack.stable_end() && "deactivating bottom of stack?"); 1544 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C)); 1545 assert(Scope.isActive() && "double deactivation"); 1546 1547 // If it's the top of the stack, just pop it. 1548 if (C == EHStack.stable_begin()) { 1549 // If it's a normal cleanup, we need to pretend that the 1550 // fallthrough is unreachable. 1551 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP(); 1552 PopCleanupBlock(); 1553 Builder.restoreIP(SavedIP); 1554 return; 1555 } 1556 1557 // Otherwise, follow the general case. 1558 SetupCleanupBlockActivation(*this, C, ForDeactivation); 1559 1560 Scope.setActive(false); 1561 } 1562 1563 llvm::Value *CodeGenFunction::getNormalCleanupDestSlot() { 1564 if (!NormalCleanupDest) 1565 NormalCleanupDest = 1566 CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot"); 1567 return NormalCleanupDest; 1568 } 1569 1570 llvm::Value *CodeGenFunction::getEHCleanupDestSlot() { 1571 if (!EHCleanupDest) 1572 EHCleanupDest = 1573 CreateTempAlloca(Builder.getInt32Ty(), "eh.cleanup.dest.slot"); 1574 return EHCleanupDest; 1575 } 1576 1577 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 1578 llvm::Constant *Init) { 1579 assert (Init && "Invalid DeclRefExpr initializer!"); 1580 if (CGDebugInfo *Dbg = getDebugInfo()) 1581 Dbg->EmitGlobalVariable(E->getDecl(), Init); 1582 } 1583