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 "llvm/Support/CFG.h" 22 using namespace clang; 23 using namespace CodeGen; 24 25 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm) 26 : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL), 27 CaseRangeBlock(NULL), StackDepth(0) { 28 LLVMIntTy = ConvertType(getContext().IntTy); 29 LLVMPointerWidth = Target.getPointerWidth(0); 30 } 31 32 ASTContext &CodeGenFunction::getContext() const { 33 return CGM.getContext(); 34 } 35 36 37 llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) { 38 llvm::BasicBlock *&BB = LabelMap[S]; 39 if (BB) return BB; 40 41 // Create, but don't insert, the new block. 42 return BB = createBasicBlock(S->getName()); 43 } 44 45 llvm::Constant * 46 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) { 47 return cast<llvm::Constant>(LocalDeclMap[BVD]); 48 } 49 50 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) 51 { 52 return LocalDeclMap[VD]; 53 } 54 55 const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 56 return CGM.getTypes().ConvertTypeForMem(T); 57 } 58 59 const llvm::Type *CodeGenFunction::ConvertType(QualType T) { 60 return CGM.getTypes().ConvertType(T); 61 } 62 63 bool CodeGenFunction::isObjCPointerType(QualType T) { 64 // All Objective-C types are pointers. 65 return T->isObjCInterfaceType() || 66 T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType(); 67 } 68 69 bool CodeGenFunction::hasAggregateLLVMType(QualType T) { 70 // FIXME: Use positive checks instead of negative ones to be more 71 // robust in the face of extension. 72 return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() && 73 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() && 74 !T->isBlockPointerType(); 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 there are no explicit 86 // jumps to the return block. 87 if (ReturnBlock->use_empty()) 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 110 // the block unless it has uses. However, we still need a place to 111 // put the debug 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 = CGM.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 AllocaInsertPt->eraseFromParent(); 140 AllocaInsertPt = 0; 141 } 142 143 void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy, 144 llvm::Function *Fn, 145 const FunctionArgList &Args, 146 SourceLocation StartLoc) { 147 CurFuncDecl = D; 148 FnRetTy = RetTy; 149 CurFn = Fn; 150 assert(CurFn->isDeclaration() && "Function already has body?"); 151 152 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 153 154 // Create a marker to make it easy to insert allocas into the entryblock 155 // later. Don't create this with the builder, because we don't want it 156 // folded. 157 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty); 158 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt", 159 EntryBB); 160 161 ReturnBlock = createBasicBlock("return"); 162 ReturnValue = 0; 163 if (!RetTy->isVoidType()) 164 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval"); 165 166 Builder.SetInsertPoint(EntryBB); 167 168 // Emit subprogram debug descriptor. 169 // FIXME: The cast here is a huge hack. 170 if (CGDebugInfo *DI = CGM.getDebugInfo()) { 171 DI->setLocation(StartLoc); 172 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 173 DI->EmitFunctionStart(FD->getIdentifier()->getName(), 174 RetTy, CurFn, Builder); 175 } else { 176 // Just use LLVM function name. 177 DI->EmitFunctionStart(Fn->getName().c_str(), 178 RetTy, CurFn, Builder); 179 } 180 } 181 182 // FIXME: Leaked. 183 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args); 184 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 185 186 // If any of the arguments have a variably modified type, make sure to 187 // emit the type size. 188 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 189 i != e; ++i) { 190 QualType Ty = i->second; 191 192 if (Ty->isVariablyModifiedType()) 193 EmitVLASize(Ty); 194 } 195 } 196 197 void CodeGenFunction::GenerateCode(const FunctionDecl *FD, 198 llvm::Function *Fn) { 199 FunctionArgList Args; 200 if (FD->getNumParams()) { 201 const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto(); 202 assert(FProto && "Function def must have prototype!"); 203 204 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) 205 Args.push_back(std::make_pair(FD->getParamDecl(i), 206 FProto->getArgType(i))); 207 } 208 209 StartFunction(FD, FD->getResultType(), Fn, Args, 210 cast<CompoundStmt>(FD->getBody())->getLBracLoc()); 211 212 EmitStmt(FD->getBody()); 213 214 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody()); 215 if (S) { 216 FinishFunction(S->getRBracLoc()); 217 } else { 218 FinishFunction(); 219 } 220 } 221 222 /// ContainsLabel - Return true if the statement contains a label in it. If 223 /// this statement is not executed normally, it not containing a label means 224 /// that we can just remove the code. 225 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 226 // Null statement, not a label! 227 if (S == 0) return false; 228 229 // If this is a label, we have to emit the code, consider something like: 230 // if (0) { ... foo: bar(); } goto foo; 231 if (isa<LabelStmt>(S)) 232 return true; 233 234 // If this is a case/default statement, and we haven't seen a switch, we have 235 // to emit the code. 236 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 237 return true; 238 239 // If this is a switch statement, we want to ignore cases below it. 240 if (isa<SwitchStmt>(S)) 241 IgnoreCaseStmts = true; 242 243 // Scan subexpressions for verboten labels. 244 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); 245 I != E; ++I) 246 if (ContainsLabel(*I, IgnoreCaseStmts)) 247 return true; 248 249 return false; 250 } 251 252 253 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to 254 /// a constant, or if it does but contains a label, return 0. If it constant 255 /// folds to 'true' and does not contain a label, return 1, if it constant folds 256 /// to 'false' and does not contain a label, return -1. 257 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) { 258 // FIXME: Rename and handle conversion of other evaluatable things 259 // to bool. 260 Expr::EvalResult Result; 261 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() || 262 Result.HasSideEffects) 263 return 0; // Not foldable, not integer or not fully evaluatable. 264 265 if (CodeGenFunction::ContainsLabel(Cond)) 266 return 0; // Contains a label. 267 268 return Result.Val.getInt().getBoolValue() ? 1 : -1; 269 } 270 271 272 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 273 /// statement) to the specified blocks. Based on the condition, this might try 274 /// to simplify the codegen of the conditional based on the branch. 275 /// 276 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 277 llvm::BasicBlock *TrueBlock, 278 llvm::BasicBlock *FalseBlock) { 279 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) 280 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock); 281 282 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 283 // Handle X && Y in a condition. 284 if (CondBOp->getOpcode() == BinaryOperator::LAnd) { 285 // If we have "1 && X", simplify the code. "0 && X" would have constant 286 // folded if the case was simple enough. 287 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) { 288 // br(1 && X) -> br(X). 289 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 290 } 291 292 // If we have "X && 1", simplify the code to use an uncond branch. 293 // "X && 0" would have been constant folded to 0. 294 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) { 295 // br(X && 1) -> br(X). 296 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 297 } 298 299 // Emit the LHS as a conditional. If the LHS conditional is false, we 300 // want to jump to the FalseBlock. 301 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 302 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock); 303 EmitBlock(LHSTrue); 304 305 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 306 return; 307 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) { 308 // If we have "0 || X", simplify the code. "1 || X" would have constant 309 // folded if the case was simple enough. 310 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) { 311 // br(0 || X) -> br(X). 312 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 313 } 314 315 // If we have "X || 0", simplify the code to use an uncond branch. 316 // "X || 1" would have been constant folded to 1. 317 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) { 318 // br(X || 0) -> br(X). 319 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 320 } 321 322 // Emit the LHS as a conditional. If the LHS conditional is true, we 323 // want to jump to the TrueBlock. 324 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 325 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse); 326 EmitBlock(LHSFalse); 327 328 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 329 return; 330 } 331 } 332 333 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 334 // br(!x, t, f) -> br(x, f, t) 335 if (CondUOp->getOpcode() == UnaryOperator::LNot) 336 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock); 337 } 338 339 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 340 // Handle ?: operator. 341 342 // Just ignore GNU ?: extension. 343 if (CondOp->getLHS()) { 344 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 345 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 346 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 347 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock); 348 EmitBlock(LHSBlock); 349 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock); 350 EmitBlock(RHSBlock); 351 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock); 352 return; 353 } 354 } 355 356 // Emit the code with the fully general case. 357 llvm::Value *CondV = EvaluateExprAsBool(Cond); 358 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock); 359 } 360 361 /// getCGRecordLayout - Return record layout info. 362 const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT, 363 QualType Ty) { 364 const RecordType *RTy = Ty->getAsRecordType(); 365 assert (RTy && "Unexpected type. RecordType expected here."); 366 367 return CGT.getCGRecordLayout(RTy->getDecl()); 368 } 369 370 /// ErrorUnsupported - Print out an error that codegen doesn't support the 371 /// specified stmt yet. 372 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type, 373 bool OmitOnError) { 374 CGM.ErrorUnsupported(S, Type, OmitOnError); 375 } 376 377 unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) { 378 // Use LabelIDs.size() as the new ID if one hasn't been assigned. 379 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second; 380 } 381 382 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) 383 { 384 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 385 if (DestPtr->getType() != BP) 386 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 387 388 // Get size and alignment info for this aggregate. 389 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 390 391 // FIXME: Handle variable sized types. 392 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth); 393 394 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr, 395 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty), 396 // TypeInfo.first describes size in bits. 397 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 398 llvm::ConstantInt::get(llvm::Type::Int32Ty, 399 TypeInfo.second/8)); 400 } 401 402 void CodeGenFunction::EmitIndirectSwitches() { 403 llvm::BasicBlock *Default; 404 405 if (IndirectSwitches.empty()) 406 return; 407 408 if (!LabelIDs.empty()) { 409 Default = getBasicBlockForLabel(LabelIDs.begin()->first); 410 } else { 411 // No possible targets for indirect goto, just emit an infinite 412 // loop. 413 Default = createBasicBlock("indirectgoto.loop", CurFn); 414 llvm::BranchInst::Create(Default, Default); 415 } 416 417 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(), 418 e = IndirectSwitches.end(); i != e; ++i) { 419 llvm::SwitchInst *I = *i; 420 421 I->setSuccessor(0, Default); 422 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(), 423 LE = LabelIDs.end(); LI != LE; ++LI) { 424 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty, 425 LI->second), 426 getBasicBlockForLabel(LI->first)); 427 } 428 } 429 } 430 431 llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) 432 { 433 // FIXME: This entire method is hardcoded for 32-bit X86. 434 435 const char *TargetPrefix = getContext().Target.getTargetPrefix(); 436 437 if (strcmp(TargetPrefix, "x86") != 0 || 438 getContext().Target.getPointerWidth(0) != 32) 439 return 0; 440 441 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 442 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP); 443 444 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 445 "ap"); 446 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 447 llvm::Value *AddrTyped = 448 Builder.CreateBitCast(Addr, 449 llvm::PointerType::getUnqual(ConvertType(Ty))); 450 451 uint64_t SizeInBytes = getContext().getTypeSize(Ty) / 8; 452 const unsigned ArgumentSizeInBytes = 4; 453 if (SizeInBytes < ArgumentSizeInBytes) 454 SizeInBytes = ArgumentSizeInBytes; 455 456 llvm::Value *NextAddr = 457 Builder.CreateGEP(Addr, 458 llvm::ConstantInt::get(llvm::Type::Int32Ty, SizeInBytes), 459 "ap.next"); 460 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 461 462 return AddrTyped; 463 } 464 465 466 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) 467 { 468 llvm::Value *&SizeEntry = VLASizeMap[VAT]; 469 470 assert(SizeEntry && "Did not emit size for type"); 471 return SizeEntry; 472 } 473 474 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) 475 { 476 assert(Ty->isVariablyModifiedType() && 477 "Must pass variably modified type to EmitVLASizes!"); 478 479 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) { 480 llvm::Value *&SizeEntry = VLASizeMap[VAT]; 481 482 if (!SizeEntry) { 483 // Get the element size; 484 llvm::Value *ElemSize; 485 486 QualType ElemTy = VAT->getElementType(); 487 488 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 489 490 if (ElemTy->isVariableArrayType()) 491 ElemSize = EmitVLASize(ElemTy); 492 else { 493 ElemSize = llvm::ConstantInt::get(SizeTy, 494 getContext().getTypeSize(ElemTy) / 8); 495 } 496 497 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr()); 498 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp"); 499 500 SizeEntry = Builder.CreateMul(ElemSize, NumElements); 501 } 502 503 return SizeEntry; 504 } else if (const PointerType *PT = Ty->getAsPointerType()) 505 EmitVLASize(PT->getPointeeType()); 506 else { 507 assert(0 && "unknown VM type!"); 508 } 509 510 return 0; 511 } 512 513 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) { 514 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) { 515 return EmitScalarExpr(E); 516 } 517 return EmitLValue(E).getAddress(); 518 } 519 520 llvm::BasicBlock *CodeGenFunction::CreateCleanupBlock() 521 { 522 llvm::BasicBlock *CleanupBlock = createBasicBlock("cleanup"); 523 524 CleanupEntries.push_back(CleanupEntry(CleanupBlock)); 525 526 return CleanupBlock; 527 } 528 529 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) 530 { 531 assert(CleanupEntries.size() >= OldCleanupStackSize && 532 "Cleanup stack mismatch!"); 533 534 while (CleanupEntries.size() > OldCleanupStackSize) 535 EmitCleanupBlock(); 536 } 537 538 void CodeGenFunction::EmitCleanupBlock() 539 { 540 CleanupEntry &CE = CleanupEntries.back(); 541 542 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock; 543 544 std::vector<llvm::BasicBlock *> Blocks; 545 std::swap(Blocks, CE.Blocks); 546 547 std::vector<llvm::BranchInst *> BranchFixups; 548 std::swap(BranchFixups, CE.BranchFixups); 549 550 CleanupEntries.pop_back(); 551 552 EmitBlock(CleanupBlock); 553 554 // Remove all blocks from the block scope map. 555 for (size_t i = 0, e = Blocks.size(); i != e; ++i) { 556 assert(BlockScopes.count(Blocks[i]) && 557 "Did not find block in scope map!"); 558 559 BlockScopes.erase(Blocks[i]); 560 } 561 } 562 563