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