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