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