1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This coordinates the per-function state used while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CodeGenModule.h" 16 #include "CGDebugInfo.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "clang/AST/APValue.h" 19 #include "clang/AST/ASTContext.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "llvm/Target/TargetData.h" 23 using namespace clang; 24 using namespace CodeGen; 25 26 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm) 27 : BlockFunction(cgm, *this, Builder), CGM(cgm), 28 Target(CGM.getContext().Target), 29 Builder(cgm.getModule().getContext()), 30 DebugInfo(0), SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0), 31 CXXThisDecl(0) { 32 LLVMIntTy = ConvertType(getContext().IntTy); 33 LLVMPointerWidth = Target.getPointerWidth(0); 34 } 35 36 ASTContext &CodeGenFunction::getContext() const { 37 return CGM.getContext(); 38 } 39 40 41 llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) { 42 llvm::BasicBlock *&BB = LabelMap[S]; 43 if (BB) return BB; 44 45 // Create, but don't insert, the new block. 46 return BB = createBasicBlock(S->getName()); 47 } 48 49 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) { 50 llvm::Value *Res = LocalDeclMap[VD]; 51 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!"); 52 return Res; 53 } 54 55 llvm::Constant * 56 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) { 57 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD)); 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 // FIXME: Use positive checks instead of negative ones to be more robust in 70 // the face of extension. 71 return !T->hasPointerRepresentation() && !T->isRealType() && 72 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() && 73 !T->isBlockPointerType() && !T->isMemberPointerType(); 74 } 75 76 void CodeGenFunction::EmitReturnBlock() { 77 // For cleanliness, we try to avoid emitting the return block for 78 // simple cases. 79 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 80 81 if (CurBB) { 82 assert(!CurBB->getTerminator() && "Unexpected terminated block."); 83 84 // We have a valid insert point, reuse it if it is empty or there are no 85 // explicit jumps to the return block. 86 if (CurBB->empty() || ReturnBlock->use_empty()) { 87 ReturnBlock->replaceAllUsesWith(CurBB); 88 delete ReturnBlock; 89 } else 90 EmitBlock(ReturnBlock); 91 return; 92 } 93 94 // Otherwise, if the return block is the target of a single direct 95 // branch then we can just put the code in that block instead. This 96 // cleans up functions which started with a unified return block. 97 if (ReturnBlock->hasOneUse()) { 98 llvm::BranchInst *BI = 99 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin()); 100 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) { 101 // Reset insertion point and delete the branch. 102 Builder.SetInsertPoint(BI->getParent()); 103 BI->eraseFromParent(); 104 delete ReturnBlock; 105 return; 106 } 107 } 108 109 // FIXME: We are at an unreachable point, there is no reason to emit the block 110 // unless it has uses. However, we still need a place to put the debug 111 // region.end for now. 112 113 EmitBlock(ReturnBlock); 114 } 115 116 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 117 // Finish emission of indirect switches. 118 EmitIndirectSwitches(); 119 120 assert(BreakContinueStack.empty() && 121 "mismatched push/pop in break/continue stack!"); 122 assert(BlockScopes.empty() && 123 "did not remove all blocks from block scope map!"); 124 assert(CleanupEntries.empty() && 125 "mismatched push/pop in cleanup stack!"); 126 127 // Emit function epilog (to return). 128 EmitReturnBlock(); 129 130 // Emit debug descriptor for function end. 131 if (CGDebugInfo *DI = getDebugInfo()) { 132 DI->setLocation(EndLoc); 133 DI->EmitRegionEnd(CurFn, Builder); 134 } 135 136 EmitFunctionEpilog(*CurFnInfo, ReturnValue); 137 138 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 139 llvm::Instruction *Ptr = AllocaInsertPt; 140 AllocaInsertPt = 0; 141 Ptr->eraseFromParent(); 142 } 143 144 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy, 145 llvm::Function *Fn, 146 const FunctionArgList &Args, 147 SourceLocation StartLoc) { 148 const Decl *D = GD.getDecl(); 149 150 DidCallStackSave = false; 151 CurCodeDecl = CurFuncDecl = D; 152 FnRetTy = RetTy; 153 CurFn = Fn; 154 assert(CurFn->isDeclaration() && "Function already has body?"); 155 156 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 157 158 // Create a marker to make it easy to insert allocas into the entryblock 159 // later. Don't create this with the builder, because we don't want it 160 // folded. 161 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)); 162 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::getInt32Ty(VMContext), "", 163 EntryBB); 164 if (Builder.isNamePreserving()) 165 AllocaInsertPt->setName("allocapt"); 166 167 ReturnBlock = createBasicBlock("return"); 168 ReturnValue = 0; 169 if (!RetTy->isVoidType()) 170 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval"); 171 172 Builder.SetInsertPoint(EntryBB); 173 174 // Emit subprogram debug descriptor. 175 // FIXME: The cast here is a huge hack. 176 if (CGDebugInfo *DI = getDebugInfo()) { 177 DI->setLocation(StartLoc); 178 if (isa<FunctionDecl>(D)) { 179 DI->EmitFunctionStart(CGM.getMangledName(GD), RetTy, CurFn, Builder); 180 } else { 181 // Just use LLVM function name. 182 183 // FIXME: Remove unnecessary conversion to std::string when API settles. 184 DI->EmitFunctionStart(std::string(Fn->getName()).c_str(), 185 RetTy, CurFn, Builder); 186 } 187 } 188 189 // FIXME: Leaked. 190 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args); 191 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 192 193 // If any of the arguments have a variably modified type, make sure to 194 // emit the type size. 195 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 196 i != e; ++i) { 197 QualType Ty = i->second; 198 199 if (Ty->isVariablyModifiedType()) 200 EmitVLASize(Ty); 201 } 202 } 203 204 void CodeGenFunction::GenerateCode(GlobalDecl GD, 205 llvm::Function *Fn) { 206 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 207 208 // Check if we should generate debug info for this function. 209 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>()) 210 DebugInfo = CGM.getDebugInfo(); 211 212 FunctionArgList Args; 213 214 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 215 if (MD->isInstance()) { 216 // Create the implicit 'this' decl. 217 // FIXME: I'm not entirely sure I like using a fake decl just for code 218 // generation. Maybe we can come up with a better way? 219 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 220 &getContext().Idents.get("this"), 221 MD->getThisType(getContext())); 222 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType())); 223 } 224 } 225 226 if (FD->getNumParams()) { 227 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>(); 228 assert(FProto && "Function def must have prototype!"); 229 230 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) 231 Args.push_back(std::make_pair(FD->getParamDecl(i), 232 FProto->getArgType(i))); 233 } 234 235 // FIXME: Support CXXTryStmt here, too. 236 if (const CompoundStmt *S = FD->getCompoundBody()) { 237 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc()); 238 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 239 EmitCtorPrologue(CD, GD.getCtorType()); 240 EmitStmt(S); 241 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) 242 EmitDtorEpilogue(DD, GD.getDtorType()); 243 FinishFunction(S->getRBracLoc()); 244 } 245 else 246 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 247 const CXXRecordDecl *ClassDecl = 248 cast<CXXRecordDecl>(CD->getDeclContext()); 249 (void) ClassDecl; 250 if (CD->isCopyConstructor(getContext())) { 251 assert(!ClassDecl->hasUserDeclaredCopyConstructor() && 252 "bogus constructor is being synthesize"); 253 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args); 254 } 255 else { 256 assert(!ClassDecl->hasUserDeclaredConstructor() && 257 "bogus constructor is being synthesize"); 258 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args); 259 } 260 } 261 else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) 262 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args); 263 else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 264 if (MD->isCopyAssignment()) 265 SynthesizeCXXCopyAssignment(MD, Fn, Args); 266 } 267 268 // Destroy the 'this' declaration. 269 if (CXXThisDecl) 270 CXXThisDecl->Destroy(getContext()); 271 } 272 273 /// ContainsLabel - Return true if the statement contains a label in it. If 274 /// this statement is not executed normally, it not containing a label means 275 /// that we can just remove the code. 276 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 277 // Null statement, not a label! 278 if (S == 0) return false; 279 280 // If this is a label, we have to emit the code, consider something like: 281 // if (0) { ... foo: bar(); } goto foo; 282 if (isa<LabelStmt>(S)) 283 return true; 284 285 // If this is a case/default statement, and we haven't seen a switch, we have 286 // to emit the code. 287 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 288 return true; 289 290 // If this is a switch statement, we want to ignore cases below it. 291 if (isa<SwitchStmt>(S)) 292 IgnoreCaseStmts = true; 293 294 // Scan subexpressions for verboten labels. 295 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); 296 I != E; ++I) 297 if (ContainsLabel(*I, IgnoreCaseStmts)) 298 return true; 299 300 return false; 301 } 302 303 304 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to 305 /// a constant, or if it does but contains a label, return 0. If it constant 306 /// folds to 'true' and does not contain a label, return 1, if it constant folds 307 /// to 'false' and does not contain a label, return -1. 308 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) { 309 // FIXME: Rename and handle conversion of other evaluatable things 310 // to bool. 311 Expr::EvalResult Result; 312 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() || 313 Result.HasSideEffects) 314 return 0; // Not foldable, not integer or not fully evaluatable. 315 316 if (CodeGenFunction::ContainsLabel(Cond)) 317 return 0; // Contains a label. 318 319 return Result.Val.getInt().getBoolValue() ? 1 : -1; 320 } 321 322 323 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 324 /// statement) to the specified blocks. Based on the condition, this might try 325 /// to simplify the codegen of the conditional based on the branch. 326 /// 327 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 328 llvm::BasicBlock *TrueBlock, 329 llvm::BasicBlock *FalseBlock) { 330 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) 331 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock); 332 333 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 334 // Handle X && Y in a condition. 335 if (CondBOp->getOpcode() == BinaryOperator::LAnd) { 336 // If we have "1 && X", simplify the code. "0 && X" would have constant 337 // folded if the case was simple enough. 338 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) { 339 // br(1 && X) -> br(X). 340 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 341 } 342 343 // If we have "X && 1", simplify the code to use an uncond branch. 344 // "X && 0" would have been constant folded to 0. 345 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) { 346 // br(X && 1) -> br(X). 347 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 348 } 349 350 // Emit the LHS as a conditional. If the LHS conditional is false, we 351 // want to jump to the FalseBlock. 352 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 353 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock); 354 EmitBlock(LHSTrue); 355 356 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 357 return; 358 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) { 359 // If we have "0 || X", simplify the code. "1 || X" would have constant 360 // folded if the case was simple enough. 361 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) { 362 // br(0 || X) -> br(X). 363 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 364 } 365 366 // If we have "X || 0", simplify the code to use an uncond branch. 367 // "X || 1" would have been constant folded to 1. 368 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) { 369 // br(X || 0) -> br(X). 370 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 371 } 372 373 // Emit the LHS as a conditional. If the LHS conditional is true, we 374 // want to jump to the TrueBlock. 375 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 376 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse); 377 EmitBlock(LHSFalse); 378 379 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 380 return; 381 } 382 } 383 384 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 385 // br(!x, t, f) -> br(x, f, t) 386 if (CondUOp->getOpcode() == UnaryOperator::LNot) 387 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock); 388 } 389 390 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 391 // Handle ?: operator. 392 393 // Just ignore GNU ?: extension. 394 if (CondOp->getLHS()) { 395 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 396 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 397 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 398 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock); 399 EmitBlock(LHSBlock); 400 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock); 401 EmitBlock(RHSBlock); 402 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock); 403 return; 404 } 405 } 406 407 // Emit the code with the fully general case. 408 llvm::Value *CondV = EvaluateExprAsBool(Cond); 409 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock); 410 } 411 412 /// ErrorUnsupported - Print out an error that codegen doesn't support the 413 /// specified stmt yet. 414 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type, 415 bool OmitOnError) { 416 CGM.ErrorUnsupported(S, Type, OmitOnError); 417 } 418 419 unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) { 420 // Use LabelIDs.size() as the new ID if one hasn't been assigned. 421 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second; 422 } 423 424 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) { 425 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 426 if (DestPtr->getType() != BP) 427 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 428 429 // Get size and alignment info for this aggregate. 430 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 431 432 // Don't bother emitting a zero-byte memset. 433 if (TypeInfo.first == 0) 434 return; 435 436 // FIXME: Handle variable sized types. 437 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext, 438 LLVMPointerWidth); 439 440 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr, 441 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)), 442 // TypeInfo.first describes size in bits. 443 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 444 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 445 TypeInfo.second/8)); 446 } 447 448 void CodeGenFunction::EmitIndirectSwitches() { 449 llvm::BasicBlock *Default; 450 451 if (IndirectSwitches.empty()) 452 return; 453 454 if (!LabelIDs.empty()) { 455 Default = getBasicBlockForLabel(LabelIDs.begin()->first); 456 } else { 457 // No possible targets for indirect goto, just emit an infinite 458 // loop. 459 Default = createBasicBlock("indirectgoto.loop", CurFn); 460 llvm::BranchInst::Create(Default, Default); 461 } 462 463 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(), 464 e = IndirectSwitches.end(); i != e; ++i) { 465 llvm::SwitchInst *I = *i; 466 467 I->setSuccessor(0, Default); 468 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(), 469 LE = LabelIDs.end(); LI != LE; ++LI) { 470 I->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 471 LI->second), 472 getBasicBlockForLabel(LI->first)); 473 } 474 } 475 } 476 477 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) { 478 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; 479 480 assert(SizeEntry && "Did not emit size for type"); 481 return SizeEntry; 482 } 483 484 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) { 485 assert(Ty->isVariablyModifiedType() && 486 "Must pass variably modified type to EmitVLASizes!"); 487 488 EnsureInsertPoint(); 489 490 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) { 491 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; 492 493 if (!SizeEntry) { 494 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 495 496 // Get the element size; 497 QualType ElemTy = VAT->getElementType(); 498 llvm::Value *ElemSize; 499 if (ElemTy->isVariableArrayType()) 500 ElemSize = EmitVLASize(ElemTy); 501 else 502 ElemSize = llvm::ConstantInt::get(SizeTy, 503 getContext().getTypeSize(ElemTy) / 8); 504 505 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr()); 506 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp"); 507 508 SizeEntry = Builder.CreateMul(ElemSize, NumElements); 509 } 510 511 return SizeEntry; 512 } 513 514 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 515 EmitVLASize(AT->getElementType()); 516 return 0; 517 } 518 519 const PointerType *PT = Ty->getAs<PointerType>(); 520 assert(PT && "unknown VM type!"); 521 EmitVLASize(PT->getPointeeType()); 522 return 0; 523 } 524 525 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) { 526 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) { 527 return EmitScalarExpr(E); 528 } 529 return EmitLValue(E).getAddress(); 530 } 531 532 void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock) { 533 CleanupEntries.push_back(CleanupEntry(CleanupBlock)); 534 } 535 536 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) { 537 assert(CleanupEntries.size() >= OldCleanupStackSize && 538 "Cleanup stack mismatch!"); 539 540 while (CleanupEntries.size() > OldCleanupStackSize) 541 EmitCleanupBlock(); 542 } 543 544 CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() { 545 CleanupEntry &CE = CleanupEntries.back(); 546 547 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock; 548 549 std::vector<llvm::BasicBlock *> Blocks; 550 std::swap(Blocks, CE.Blocks); 551 552 std::vector<llvm::BranchInst *> BranchFixups; 553 std::swap(BranchFixups, CE.BranchFixups); 554 555 CleanupEntries.pop_back(); 556 557 // Check if any branch fixups pointed to the scope we just popped. If so, 558 // we can remove them. 559 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) { 560 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0); 561 BlockScopeMap::iterator I = BlockScopes.find(Dest); 562 563 if (I == BlockScopes.end()) 564 continue; 565 566 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!"); 567 568 if (I->second == CleanupEntries.size()) { 569 // We don't need to do this branch fixup. 570 BranchFixups[i] = BranchFixups.back(); 571 BranchFixups.pop_back(); 572 i--; 573 e--; 574 continue; 575 } 576 } 577 578 llvm::BasicBlock *SwitchBlock = 0; 579 llvm::BasicBlock *EndBlock = 0; 580 if (!BranchFixups.empty()) { 581 SwitchBlock = createBasicBlock("cleanup.switch"); 582 EndBlock = createBasicBlock("cleanup.end"); 583 584 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 585 586 Builder.SetInsertPoint(SwitchBlock); 587 588 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext), 589 "cleanup.dst"); 590 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp"); 591 592 // Create a switch instruction to determine where to jump next. 593 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock, 594 BranchFixups.size()); 595 596 // Restore the current basic block (if any) 597 if (CurBB) { 598 Builder.SetInsertPoint(CurBB); 599 600 // If we had a current basic block, we also need to emit an instruction 601 // to initialize the cleanup destination. 602 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)), 603 DestCodePtr); 604 } else 605 Builder.ClearInsertionPoint(); 606 607 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) { 608 llvm::BranchInst *BI = BranchFixups[i]; 609 llvm::BasicBlock *Dest = BI->getSuccessor(0); 610 611 // Fixup the branch instruction to point to the cleanup block. 612 BI->setSuccessor(0, CleanupBlock); 613 614 if (CleanupEntries.empty()) { 615 llvm::ConstantInt *ID; 616 617 // Check if we already have a destination for this block. 618 if (Dest == SI->getDefaultDest()) 619 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0); 620 else { 621 ID = SI->findCaseDest(Dest); 622 if (!ID) { 623 // No code found, get a new unique one by using the number of 624 // switch successors. 625 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 626 SI->getNumSuccessors()); 627 SI->addCase(ID, Dest); 628 } 629 } 630 631 // Store the jump destination before the branch instruction. 632 new llvm::StoreInst(ID, DestCodePtr, BI); 633 } else { 634 // We need to jump through another cleanup block. Create a pad block 635 // with a branch instruction that jumps to the final destination and 636 // add it as a branch fixup to the current cleanup scope. 637 638 // Create the pad block. 639 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn); 640 641 // Create a unique case ID. 642 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 643 SI->getNumSuccessors()); 644 645 // Store the jump destination before the branch instruction. 646 new llvm::StoreInst(ID, DestCodePtr, BI); 647 648 // Add it as the destination. 649 SI->addCase(ID, CleanupPad); 650 651 // Create the branch to the final destination. 652 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest); 653 CleanupPad->getInstList().push_back(BI); 654 655 // And add it as a branch fixup. 656 CleanupEntries.back().BranchFixups.push_back(BI); 657 } 658 } 659 } 660 661 // Remove all blocks from the block scope map. 662 for (size_t i = 0, e = Blocks.size(); i != e; ++i) { 663 assert(BlockScopes.count(Blocks[i]) && 664 "Did not find block in scope map!"); 665 666 BlockScopes.erase(Blocks[i]); 667 } 668 669 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock); 670 } 671 672 void CodeGenFunction::EmitCleanupBlock() { 673 CleanupBlockInfo Info = PopCleanupBlock(); 674 675 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 676 if (CurBB && !CurBB->getTerminator() && 677 Info.CleanupBlock->getNumUses() == 0) { 678 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList()); 679 delete Info.CleanupBlock; 680 } else 681 EmitBlock(Info.CleanupBlock); 682 683 if (Info.SwitchBlock) 684 EmitBlock(Info.SwitchBlock); 685 if (Info.EndBlock) 686 EmitBlock(Info.EndBlock); 687 } 688 689 void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) { 690 assert(!CleanupEntries.empty() && 691 "Trying to add branch fixup without cleanup block!"); 692 693 // FIXME: We could be more clever here and check if there's already a branch 694 // fixup for this destination and recycle it. 695 CleanupEntries.back().BranchFixups.push_back(BI); 696 } 697 698 void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) { 699 if (!HaveInsertPoint()) 700 return; 701 702 llvm::BranchInst* BI = Builder.CreateBr(Dest); 703 704 Builder.ClearInsertionPoint(); 705 706 // The stack is empty, no need to do any cleanup. 707 if (CleanupEntries.empty()) 708 return; 709 710 if (!Dest->getParent()) { 711 // We are trying to branch to a block that hasn't been inserted yet. 712 AddBranchFixup(BI); 713 return; 714 } 715 716 BlockScopeMap::iterator I = BlockScopes.find(Dest); 717 if (I == BlockScopes.end()) { 718 // We are trying to jump to a block that is outside of any cleanup scope. 719 AddBranchFixup(BI); 720 return; 721 } 722 723 assert(I->second < CleanupEntries.size() && 724 "Trying to branch into cleanup region"); 725 726 if (I->second == CleanupEntries.size() - 1) { 727 // We have a branch to a block in the same scope. 728 return; 729 } 730 731 AddBranchFixup(BI); 732 } 733