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 "clang/AST/StmtCXX.h" 23 #include "llvm/Target/TargetData.h" 24 using namespace clang; 25 using namespace CodeGen; 26 27 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm) 28 : BlockFunction(cgm, *this, Builder), CGM(cgm), 29 Target(CGM.getContext().Target), 30 Builder(cgm.getModule().getContext()), 31 DebugInfo(0), IndirectBranch(0), 32 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0), 33 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0), 34 ConditionalBranchLevel(0), TerminateHandler(0), TrapBB(0), 35 UniqueAggrDestructorCount(0) { 36 LLVMIntTy = ConvertType(getContext().IntTy); 37 LLVMPointerWidth = Target.getPointerWidth(0); 38 Exceptions = getContext().getLangOptions().Exceptions; 39 CatchUndefined = getContext().getLangOptions().CatchUndefined; 40 } 41 42 ASTContext &CodeGenFunction::getContext() const { 43 return CGM.getContext(); 44 } 45 46 47 llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) { 48 llvm::BasicBlock *&BB = LabelMap[S]; 49 if (BB) return BB; 50 51 // Create, but don't insert, the new block. 52 return BB = createBasicBlock(S->getName()); 53 } 54 55 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) { 56 llvm::Value *Res = LocalDeclMap[VD]; 57 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!"); 58 return Res; 59 } 60 61 llvm::Constant * 62 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) { 63 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD)); 64 } 65 66 const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 67 return CGM.getTypes().ConvertTypeForMem(T); 68 } 69 70 const llvm::Type *CodeGenFunction::ConvertType(QualType T) { 71 return CGM.getTypes().ConvertType(T); 72 } 73 74 bool CodeGenFunction::hasAggregateLLVMType(QualType T) { 75 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() || 76 T->isMemberFunctionPointerType(); 77 } 78 79 void CodeGenFunction::EmitReturnBlock() { 80 // For cleanliness, we try to avoid emitting the return block for 81 // simple cases. 82 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 83 84 if (CurBB) { 85 assert(!CurBB->getTerminator() && "Unexpected terminated block."); 86 87 // We have a valid insert point, reuse it if it is empty or there are no 88 // explicit jumps to the return block. 89 if (CurBB->empty() || ReturnBlock->use_empty()) { 90 ReturnBlock->replaceAllUsesWith(CurBB); 91 delete ReturnBlock; 92 } else 93 EmitBlock(ReturnBlock); 94 return; 95 } 96 97 // Otherwise, if the return block is the target of a single direct 98 // branch then we can just put the code in that block instead. This 99 // cleans up functions which started with a unified return block. 100 if (ReturnBlock->hasOneUse()) { 101 llvm::BranchInst *BI = 102 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin()); 103 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) { 104 // Reset insertion point and delete the branch. 105 Builder.SetInsertPoint(BI->getParent()); 106 BI->eraseFromParent(); 107 delete ReturnBlock; 108 return; 109 } 110 } 111 112 // FIXME: We are at an unreachable point, there is no reason to emit the block 113 // unless it has uses. However, we still need a place to put the debug 114 // region.end for now. 115 116 EmitBlock(ReturnBlock); 117 } 118 119 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 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 EmitEndEHSpec(CurCodeDecl); 138 139 // If someone did an indirect goto, emit the indirect goto block at the end of 140 // the function. 141 if (IndirectBranch) { 142 EmitBlock(IndirectBranch->getParent()); 143 Builder.ClearInsertionPoint(); 144 } 145 146 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 147 llvm::Instruction *Ptr = AllocaInsertPt; 148 AllocaInsertPt = 0; 149 Ptr->eraseFromParent(); 150 151 // If someone took the address of a label but never did an indirect goto, we 152 // made a zero entry PHI node, which is illegal, zap it now. 153 if (IndirectBranch) { 154 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 155 if (PN->getNumIncomingValues() == 0) { 156 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 157 PN->eraseFromParent(); 158 } 159 } 160 } 161 162 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy, 163 llvm::Function *Fn, 164 const FunctionArgList &Args, 165 SourceLocation StartLoc) { 166 const Decl *D = GD.getDecl(); 167 168 DidCallStackSave = false; 169 CurCodeDecl = CurFuncDecl = D; 170 FnRetTy = RetTy; 171 CurFn = Fn; 172 assert(CurFn->isDeclaration() && "Function already has body?"); 173 174 // Pass inline keyword to optimizer if it appears explicitly on any 175 // declaration. 176 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 177 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(), 178 RE = FD->redecls_end(); RI != RE; ++RI) 179 if (RI->isInlineSpecified()) { 180 Fn->addFnAttr(llvm::Attribute::InlineHint); 181 break; 182 } 183 184 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 185 186 // Create a marker to make it easy to insert allocas into the entryblock 187 // later. Don't create this with the builder, because we don't want it 188 // folded. 189 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)); 190 AllocaInsertPt = new llvm::BitCastInst(Undef, 191 llvm::Type::getInt32Ty(VMContext), "", 192 EntryBB); 193 if (Builder.isNamePreserving()) 194 AllocaInsertPt->setName("allocapt"); 195 196 ReturnBlock = createBasicBlock("return"); 197 198 Builder.SetInsertPoint(EntryBB); 199 200 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0); 201 202 // Emit subprogram debug descriptor. 203 if (CGDebugInfo *DI = getDebugInfo()) { 204 DI->setLocation(StartLoc); 205 DI->EmitFunctionStart(GD, FnType, CurFn, Builder); 206 } 207 208 // FIXME: Leaked. 209 // CC info is ignored, hopefully? 210 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args, 211 CC_Default, false); 212 213 if (RetTy->isVoidType()) { 214 // Void type; nothing to return. 215 ReturnValue = 0; 216 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect && 217 hasAggregateLLVMType(CurFnInfo->getReturnType())) { 218 // Indirect aggregate return; emit returned value directly into sret slot. 219 // This reduces code size, and affects correctness in C++. 220 ReturnValue = CurFn->arg_begin(); 221 } else { 222 ReturnValue = CreateIRTemp(RetTy, "retval"); 223 } 224 225 EmitStartEHSpec(CurCodeDecl); 226 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 227 228 if (CXXThisDecl) 229 CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this"); 230 if (CXXVTTDecl) 231 CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt"); 232 233 // If any of the arguments have a variably modified type, make sure to 234 // emit the type size. 235 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 236 i != e; ++i) { 237 QualType Ty = i->second; 238 239 if (Ty->isVariablyModifiedType()) 240 EmitVLASize(Ty); 241 } 242 } 243 244 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) { 245 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 246 247 // Check if we should generate debug info for this function. 248 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>()) 249 DebugInfo = CGM.getDebugInfo(); 250 251 FunctionArgList Args; 252 253 CurGD = GD; 254 OuterTryBlock = 0; 255 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 256 if (MD->isInstance()) { 257 // Create the implicit 'this' decl. 258 // FIXME: I'm not entirely sure I like using a fake decl just for code 259 // generation. Maybe we can come up with a better way? 260 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, 261 FD->getLocation(), 262 &getContext().Idents.get("this"), 263 MD->getThisType(getContext())); 264 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType())); 265 266 // Check if we need a VTT parameter as well. 267 if (CGVtableInfo::needsVTTParameter(GD)) { 268 // FIXME: The comment about using a fake decl above applies here too. 269 QualType T = getContext().getPointerType(getContext().VoidPtrTy); 270 CXXVTTDecl = 271 ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(), 272 &getContext().Idents.get("vtt"), T); 273 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType())); 274 } 275 } 276 } 277 278 if (FD->getNumParams()) { 279 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>(); 280 assert(FProto && "Function def must have prototype!"); 281 282 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) 283 Args.push_back(std::make_pair(FD->getParamDecl(i), 284 FProto->getArgType(i))); 285 } 286 287 if (const CompoundStmt *S = FD->getCompoundBody()) { 288 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc()); 289 290 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 291 EmitCtorPrologue(CD, GD.getCtorType()); 292 EmitStmt(S); 293 294 // If any of the member initializers are temporaries bound to references 295 // make sure to emit their destructors. 296 EmitCleanupBlocks(0); 297 298 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) { 299 llvm::BasicBlock *DtorEpilogue = createBasicBlock("dtor.epilogue"); 300 PushCleanupBlock(DtorEpilogue); 301 302 InitializeVtablePtrs(DD->getParent()); 303 304 EmitStmt(S); 305 306 CleanupBlockInfo Info = PopCleanupBlock(); 307 308 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!"); 309 EmitBlock(DtorEpilogue); 310 EmitDtorEpilogue(DD, GD.getDtorType()); 311 312 if (Info.SwitchBlock) 313 EmitBlock(Info.SwitchBlock); 314 if (Info.EndBlock) 315 EmitBlock(Info.EndBlock); 316 } else { 317 // Just a regular function, emit its body. 318 EmitStmt(S); 319 } 320 321 FinishFunction(S->getRBracLoc()); 322 } else if (FD->isImplicit()) { 323 const CXXRecordDecl *ClassDecl = 324 cast<CXXRecordDecl>(FD->getDeclContext()); 325 (void) ClassDecl; 326 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 327 // FIXME: For C++0x, we want to look for implicit *definitions* of 328 // these special member functions, rather than implicit *declarations*. 329 if (CD->isCopyConstructor()) { 330 assert(!ClassDecl->hasUserDeclaredCopyConstructor() && 331 "Cannot synthesize a non-implicit copy constructor"); 332 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args); 333 } else if (CD->isDefaultConstructor()) { 334 assert(!ClassDecl->hasUserDeclaredConstructor() && 335 "Cannot synthesize a non-implicit default constructor."); 336 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args); 337 } else { 338 assert(false && "Implicit constructor cannot be synthesized"); 339 } 340 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) { 341 assert(!ClassDecl->hasUserDeclaredDestructor() && 342 "Cannot synthesize a non-implicit destructor"); 343 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args); 344 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 345 assert(MD->isCopyAssignment() && 346 !ClassDecl->hasUserDeclaredCopyAssignment() && 347 "Cannot synthesize a method that is not an implicit-defined " 348 "copy constructor"); 349 SynthesizeCXXCopyAssignment(MD, Fn, Args); 350 } else { 351 assert(false && "Cannot synthesize unknown implicit function"); 352 } 353 } else if (const Stmt *S = FD->getBody()) { 354 if (const CXXTryStmt *TS = dyn_cast<CXXTryStmt>(S)) { 355 OuterTryBlock = TS; 356 StartFunction(GD, FD->getResultType(), Fn, Args, TS->getTryLoc()); 357 EmitStmt(TS); 358 FinishFunction(TS->getEndLoc()); 359 } 360 } 361 362 // Destroy the 'this' declaration. 363 if (CXXThisDecl) 364 CXXThisDecl->Destroy(getContext()); 365 366 // Destroy the VTT declaration. 367 if (CXXVTTDecl) 368 CXXVTTDecl->Destroy(getContext()); 369 } 370 371 /// ContainsLabel - Return true if the statement contains a label in it. If 372 /// this statement is not executed normally, it not containing a label means 373 /// that we can just remove the code. 374 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 375 // Null statement, not a label! 376 if (S == 0) return false; 377 378 // If this is a label, we have to emit the code, consider something like: 379 // if (0) { ... foo: bar(); } goto foo; 380 if (isa<LabelStmt>(S)) 381 return true; 382 383 // If this is a case/default statement, and we haven't seen a switch, we have 384 // to emit the code. 385 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 386 return true; 387 388 // If this is a switch statement, we want to ignore cases below it. 389 if (isa<SwitchStmt>(S)) 390 IgnoreCaseStmts = true; 391 392 // Scan subexpressions for verboten labels. 393 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); 394 I != E; ++I) 395 if (ContainsLabel(*I, IgnoreCaseStmts)) 396 return true; 397 398 return false; 399 } 400 401 402 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to 403 /// a constant, or if it does but contains a label, return 0. If it constant 404 /// folds to 'true' and does not contain a label, return 1, if it constant folds 405 /// to 'false' and does not contain a label, return -1. 406 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) { 407 // FIXME: Rename and handle conversion of other evaluatable things 408 // to bool. 409 Expr::EvalResult Result; 410 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() || 411 Result.HasSideEffects) 412 return 0; // Not foldable, not integer or not fully evaluatable. 413 414 if (CodeGenFunction::ContainsLabel(Cond)) 415 return 0; // Contains a label. 416 417 return Result.Val.getInt().getBoolValue() ? 1 : -1; 418 } 419 420 421 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 422 /// statement) to the specified blocks. Based on the condition, this might try 423 /// to simplify the codegen of the conditional based on the branch. 424 /// 425 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 426 llvm::BasicBlock *TrueBlock, 427 llvm::BasicBlock *FalseBlock) { 428 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) 429 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock); 430 431 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 432 // Handle X && Y in a condition. 433 if (CondBOp->getOpcode() == BinaryOperator::LAnd) { 434 // If we have "1 && X", simplify the code. "0 && X" would have constant 435 // folded if the case was simple enough. 436 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) { 437 // br(1 && X) -> br(X). 438 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 439 } 440 441 // If we have "X && 1", simplify the code to use an uncond branch. 442 // "X && 0" would have been constant folded to 0. 443 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) { 444 // br(X && 1) -> br(X). 445 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 446 } 447 448 // Emit the LHS as a conditional. If the LHS conditional is false, we 449 // want to jump to the FalseBlock. 450 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 451 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock); 452 EmitBlock(LHSTrue); 453 454 // Any temporaries created here are conditional. 455 BeginConditionalBranch(); 456 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 457 EndConditionalBranch(); 458 459 return; 460 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) { 461 // If we have "0 || X", simplify the code. "1 || X" would have constant 462 // folded if the case was simple enough. 463 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) { 464 // br(0 || X) -> br(X). 465 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 466 } 467 468 // If we have "X || 0", simplify the code to use an uncond branch. 469 // "X || 1" would have been constant folded to 1. 470 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) { 471 // br(X || 0) -> br(X). 472 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 473 } 474 475 // Emit the LHS as a conditional. If the LHS conditional is true, we 476 // want to jump to the TrueBlock. 477 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 478 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse); 479 EmitBlock(LHSFalse); 480 481 // Any temporaries created here are conditional. 482 BeginConditionalBranch(); 483 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 484 EndConditionalBranch(); 485 486 return; 487 } 488 } 489 490 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 491 // br(!x, t, f) -> br(x, f, t) 492 if (CondUOp->getOpcode() == UnaryOperator::LNot) 493 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock); 494 } 495 496 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 497 // Handle ?: operator. 498 499 // Just ignore GNU ?: extension. 500 if (CondOp->getLHS()) { 501 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 502 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 503 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 504 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock); 505 EmitBlock(LHSBlock); 506 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock); 507 EmitBlock(RHSBlock); 508 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock); 509 return; 510 } 511 } 512 513 // Emit the code with the fully general case. 514 llvm::Value *CondV = EvaluateExprAsBool(Cond); 515 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock); 516 } 517 518 /// ErrorUnsupported - Print out an error that codegen doesn't support the 519 /// specified stmt yet. 520 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type, 521 bool OmitOnError) { 522 CGM.ErrorUnsupported(S, Type, OmitOnError); 523 } 524 525 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) { 526 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext); 527 if (DestPtr->getType() != BP) 528 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 529 530 // Get size and alignment info for this aggregate. 531 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 532 533 // Don't bother emitting a zero-byte memset. 534 if (TypeInfo.first == 0) 535 return; 536 537 // FIXME: Handle variable sized types. 538 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext, 539 LLVMPointerWidth); 540 541 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr, 542 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)), 543 // TypeInfo.first describes size in bits. 544 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 545 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 546 TypeInfo.second/8)); 547 } 548 549 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) { 550 // Make sure that there is a block for the indirect goto. 551 if (IndirectBranch == 0) 552 GetIndirectGotoBlock(); 553 554 llvm::BasicBlock *BB = getBasicBlockForLabel(L); 555 556 // Make sure the indirect branch includes all of the address-taken blocks. 557 IndirectBranch->addDestination(BB); 558 return llvm::BlockAddress::get(CurFn, BB); 559 } 560 561 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 562 // If we already made the indirect branch for indirect goto, return its block. 563 if (IndirectBranch) return IndirectBranch->getParent(); 564 565 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto")); 566 567 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext); 568 569 // Create the PHI node that indirect gotos will add entries to. 570 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest"); 571 572 // Create the indirect branch instruction. 573 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 574 return IndirectBranch->getParent(); 575 } 576 577 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) { 578 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; 579 580 assert(SizeEntry && "Did not emit size for type"); 581 return SizeEntry; 582 } 583 584 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) { 585 assert(Ty->isVariablyModifiedType() && 586 "Must pass variably modified type to EmitVLASizes!"); 587 588 EnsureInsertPoint(); 589 590 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) { 591 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; 592 593 if (!SizeEntry) { 594 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 595 596 // Get the element size; 597 QualType ElemTy = VAT->getElementType(); 598 llvm::Value *ElemSize; 599 if (ElemTy->isVariableArrayType()) 600 ElemSize = EmitVLASize(ElemTy); 601 else 602 ElemSize = llvm::ConstantInt::get(SizeTy, 603 getContext().getTypeSizeInChars(ElemTy).getQuantity()); 604 605 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr()); 606 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp"); 607 608 SizeEntry = Builder.CreateMul(ElemSize, NumElements); 609 } 610 611 return SizeEntry; 612 } 613 614 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 615 EmitVLASize(AT->getElementType()); 616 return 0; 617 } 618 619 const PointerType *PT = Ty->getAs<PointerType>(); 620 assert(PT && "unknown VM type!"); 621 EmitVLASize(PT->getPointeeType()); 622 return 0; 623 } 624 625 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) { 626 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) { 627 return EmitScalarExpr(E); 628 } 629 return EmitLValue(E).getAddress(); 630 } 631 632 void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock, 633 llvm::BasicBlock *CleanupExitBlock, 634 llvm::BasicBlock *PreviousInvokeDest, 635 bool EHOnly) { 636 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock, 637 PreviousInvokeDest, EHOnly)); 638 } 639 640 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) { 641 assert(CleanupEntries.size() >= OldCleanupStackSize && 642 "Cleanup stack mismatch!"); 643 644 while (CleanupEntries.size() > OldCleanupStackSize) 645 EmitCleanupBlock(); 646 } 647 648 CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() { 649 CleanupEntry &CE = CleanupEntries.back(); 650 651 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock; 652 653 std::vector<llvm::BasicBlock *> Blocks; 654 std::swap(Blocks, CE.Blocks); 655 656 std::vector<llvm::BranchInst *> BranchFixups; 657 std::swap(BranchFixups, CE.BranchFixups); 658 659 bool EHOnly = CE.EHOnly; 660 661 setInvokeDest(CE.PreviousInvokeDest); 662 663 CleanupEntries.pop_back(); 664 665 // Check if any branch fixups pointed to the scope we just popped. If so, 666 // we can remove them. 667 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) { 668 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0); 669 BlockScopeMap::iterator I = BlockScopes.find(Dest); 670 671 if (I == BlockScopes.end()) 672 continue; 673 674 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!"); 675 676 if (I->second == CleanupEntries.size()) { 677 // We don't need to do this branch fixup. 678 BranchFixups[i] = BranchFixups.back(); 679 BranchFixups.pop_back(); 680 i--; 681 e--; 682 continue; 683 } 684 } 685 686 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock; 687 llvm::BasicBlock *EndBlock = 0; 688 if (!BranchFixups.empty()) { 689 if (!SwitchBlock) 690 SwitchBlock = createBasicBlock("cleanup.switch"); 691 EndBlock = createBasicBlock("cleanup.end"); 692 693 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 694 695 Builder.SetInsertPoint(SwitchBlock); 696 697 llvm::Value *DestCodePtr 698 = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext), 699 "cleanup.dst"); 700 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp"); 701 702 // Create a switch instruction to determine where to jump next. 703 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock, 704 BranchFixups.size()); 705 706 // Restore the current basic block (if any) 707 if (CurBB) { 708 Builder.SetInsertPoint(CurBB); 709 710 // If we had a current basic block, we also need to emit an instruction 711 // to initialize the cleanup destination. 712 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)), 713 DestCodePtr); 714 } else 715 Builder.ClearInsertionPoint(); 716 717 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) { 718 llvm::BranchInst *BI = BranchFixups[i]; 719 llvm::BasicBlock *Dest = BI->getSuccessor(0); 720 721 // Fixup the branch instruction to point to the cleanup block. 722 BI->setSuccessor(0, CleanupEntryBlock); 723 724 if (CleanupEntries.empty()) { 725 llvm::ConstantInt *ID; 726 727 // Check if we already have a destination for this block. 728 if (Dest == SI->getDefaultDest()) 729 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0); 730 else { 731 ID = SI->findCaseDest(Dest); 732 if (!ID) { 733 // No code found, get a new unique one by using the number of 734 // switch successors. 735 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 736 SI->getNumSuccessors()); 737 SI->addCase(ID, Dest); 738 } 739 } 740 741 // Store the jump destination before the branch instruction. 742 new llvm::StoreInst(ID, DestCodePtr, BI); 743 } else { 744 // We need to jump through another cleanup block. Create a pad block 745 // with a branch instruction that jumps to the final destination and add 746 // it as a branch fixup to the current cleanup scope. 747 748 // Create the pad block. 749 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn); 750 751 // Create a unique case ID. 752 llvm::ConstantInt *ID 753 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 754 SI->getNumSuccessors()); 755 756 // Store the jump destination before the branch instruction. 757 new llvm::StoreInst(ID, DestCodePtr, BI); 758 759 // Add it as the destination. 760 SI->addCase(ID, CleanupPad); 761 762 // Create the branch to the final destination. 763 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest); 764 CleanupPad->getInstList().push_back(BI); 765 766 // And add it as a branch fixup. 767 CleanupEntries.back().BranchFixups.push_back(BI); 768 } 769 } 770 } 771 772 // Remove all blocks from the block scope map. 773 for (size_t i = 0, e = Blocks.size(); i != e; ++i) { 774 assert(BlockScopes.count(Blocks[i]) && 775 "Did not find block in scope map!"); 776 777 BlockScopes.erase(Blocks[i]); 778 } 779 780 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly); 781 } 782 783 void CodeGenFunction::EmitCleanupBlock() { 784 CleanupBlockInfo Info = PopCleanupBlock(); 785 786 if (Info.EHOnly) { 787 // FIXME: Add this to the exceptional edge 788 if (Info.CleanupBlock->getNumUses() == 0) 789 delete Info.CleanupBlock; 790 return; 791 } 792 793 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 794 if (CurBB && !CurBB->getTerminator() && 795 Info.CleanupBlock->getNumUses() == 0) { 796 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList()); 797 delete Info.CleanupBlock; 798 } else 799 EmitBlock(Info.CleanupBlock); 800 801 if (Info.SwitchBlock) 802 EmitBlock(Info.SwitchBlock); 803 if (Info.EndBlock) 804 EmitBlock(Info.EndBlock); 805 } 806 807 void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) { 808 assert(!CleanupEntries.empty() && 809 "Trying to add branch fixup without cleanup block!"); 810 811 // FIXME: We could be more clever here and check if there's already a branch 812 // fixup for this destination and recycle it. 813 CleanupEntries.back().BranchFixups.push_back(BI); 814 } 815 816 void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) { 817 if (!HaveInsertPoint()) 818 return; 819 820 llvm::BranchInst* BI = Builder.CreateBr(Dest); 821 822 Builder.ClearInsertionPoint(); 823 824 // The stack is empty, no need to do any cleanup. 825 if (CleanupEntries.empty()) 826 return; 827 828 if (!Dest->getParent()) { 829 // We are trying to branch to a block that hasn't been inserted yet. 830 AddBranchFixup(BI); 831 return; 832 } 833 834 BlockScopeMap::iterator I = BlockScopes.find(Dest); 835 if (I == BlockScopes.end()) { 836 // We are trying to jump to a block that is outside of any cleanup scope. 837 AddBranchFixup(BI); 838 return; 839 } 840 841 assert(I->second < CleanupEntries.size() && 842 "Trying to branch into cleanup region"); 843 844 if (I->second == CleanupEntries.size() - 1) { 845 // We have a branch to a block in the same scope. 846 return; 847 } 848 849 AddBranchFixup(BI); 850 } 851