1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the per-function state used while generating code.
12 //===----------------------------------------------------------------------===//
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;
26 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
27 : BlockFunction(cgm, *this, Builder), CGM(cgm),
28 Target(CGM.getContext().Target),
29 Builder(cgm.getModule().getContext()),
30 #ifndef USEINDIRECTBRANCH
31 DebugInfo(0), IndirectGotoSwitch(0),
33 DebugInfo(0), IndirectBranch(0),
35 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
37 LLVMIntTy = ConvertType(getContext().IntTy);
38 LLVMPointerWidth = Target.getPointerWidth(0);
41 ASTContext &CodeGenFunction::getContext() const {
42 return CGM.getContext();
46 llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
47 llvm::BasicBlock *&BB = LabelMap[S];
50 // Create, but don't insert, the new block.
51 return BB = createBasicBlock(S->getName());
54 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
55 llvm::Value *Res = LocalDeclMap[VD];
56 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
61 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
62 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
65 const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
66 return CGM.getTypes().ConvertTypeForMem(T);
69 const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
70 return CGM.getTypes().ConvertType(T);
73 bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
74 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
75 T->isMemberFunctionPointerType();
78 void CodeGenFunction::EmitReturnBlock() {
79 // For cleanliness, we try to avoid emitting the return block for
81 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
84 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
86 // We have a valid insert point, reuse it if it is empty or there are no
87 // explicit jumps to the return block.
88 if (CurBB->empty() || ReturnBlock->use_empty()) {
89 ReturnBlock->replaceAllUsesWith(CurBB);
92 EmitBlock(ReturnBlock);
96 // Otherwise, if the return block is the target of a single direct
97 // branch then we can just put the code in that block instead. This
98 // cleans up functions which started with a unified return block.
99 if (ReturnBlock->hasOneUse()) {
100 llvm::BranchInst *BI =
101 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
102 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
103 // Reset insertion point and delete the branch.
104 Builder.SetInsertPoint(BI->getParent());
105 BI->eraseFromParent();
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.
115 EmitBlock(ReturnBlock);
118 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
119 assert(BreakContinueStack.empty() &&
120 "mismatched push/pop in break/continue stack!");
121 assert(BlockScopes.empty() &&
122 "did not remove all blocks from block scope map!");
123 assert(CleanupEntries.empty() &&
124 "mismatched push/pop in cleanup stack!");
126 // Emit function epilog (to return).
129 // Emit debug descriptor for function end.
130 if (CGDebugInfo *DI = getDebugInfo()) {
131 DI->setLocation(EndLoc);
132 DI->EmitRegionEnd(CurFn, Builder);
135 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
137 #ifdef USEINDIRECTBRANCH
138 // If someone did an indirect goto, emit the indirect goto block at the end of
140 if (IndirectBranch) {
141 EmitBlock(IndirectBranch->getParent());
142 Builder.ClearInsertionPoint();
147 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
148 llvm::Instruction *Ptr = AllocaInsertPt;
150 Ptr->eraseFromParent();
151 #ifdef USEINDIRECTBRANCH
153 // If someone took the address of a label but never did an indirect goto, we
154 // made a zero entry PHI node, which is illegal, zap it now.
155 if (IndirectBranch) {
156 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
157 if (PN->getNumIncomingValues() == 0) {
158 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
159 PN->eraseFromParent();
166 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
168 const FunctionArgList &Args,
169 SourceLocation StartLoc) {
170 const Decl *D = GD.getDecl();
172 DidCallStackSave = false;
173 CurCodeDecl = CurFuncDecl = D;
176 assert(CurFn->isDeclaration() && "Function already has body?");
178 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
180 // Create a marker to make it easy to insert allocas into the entryblock
181 // later. Don't create this with the builder, because we don't want it
183 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
184 AllocaInsertPt = new llvm::BitCastInst(Undef,
185 llvm::Type::getInt32Ty(VMContext), "",
187 if (Builder.isNamePreserving())
188 AllocaInsertPt->setName("allocapt");
190 ReturnBlock = createBasicBlock("return");
192 if (!RetTy->isVoidType())
193 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
195 Builder.SetInsertPoint(EntryBB);
197 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0);
199 // Emit subprogram debug descriptor.
200 // FIXME: The cast here is a huge hack.
201 if (CGDebugInfo *DI = getDebugInfo()) {
202 DI->setLocation(StartLoc);
203 if (isa<FunctionDecl>(D)) {
204 DI->EmitFunctionStart(CGM.getMangledName(GD), FnType, CurFn, Builder);
206 // Just use LLVM function name.
208 // FIXME: Remove unnecessary conversion to std::string when API settles.
209 DI->EmitFunctionStart(std::string(Fn->getName()).c_str(),
210 FnType, CurFn, Builder);
215 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
216 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
218 // If any of the arguments have a variably modified type, make sure to
219 // emit the type size.
220 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
222 QualType Ty = i->second;
224 if (Ty->isVariablyModifiedType())
229 void CodeGenFunction::GenerateCode(GlobalDecl GD,
230 llvm::Function *Fn) {
231 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
233 // Check if we should generate debug info for this function.
234 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
235 DebugInfo = CGM.getDebugInfo();
237 FunctionArgList Args;
239 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
240 if (MD->isInstance()) {
241 // Create the implicit 'this' decl.
242 // FIXME: I'm not entirely sure I like using a fake decl just for code
243 // generation. Maybe we can come up with a better way?
244 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
245 &getContext().Idents.get("this"),
246 MD->getThisType(getContext()));
247 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
251 if (FD->getNumParams()) {
252 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
253 assert(FProto && "Function def must have prototype!");
255 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
256 Args.push_back(std::make_pair(FD->getParamDecl(i),
257 FProto->getArgType(i)));
260 // FIXME: Support CXXTryStmt here, too.
261 if (const CompoundStmt *S = FD->getCompoundBody()) {
262 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
263 const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD);
264 llvm::BasicBlock *DtorEpilogue = 0;
266 DtorEpilogue = createBasicBlock("dtor.epilogue");
268 PushCleanupBlock(DtorEpilogue);
271 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
272 EmitCtorPrologue(CD, GD.getCtorType());
276 CleanupBlockInfo Info = PopCleanupBlock();
278 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
279 EmitBlock(DtorEpilogue);
280 EmitDtorEpilogue(DD, GD.getDtorType());
282 if (Info.SwitchBlock)
283 EmitBlock(Info.SwitchBlock);
285 EmitBlock(Info.EndBlock);
287 FinishFunction(S->getRBracLoc());
288 } else if (FD->isImplicit()) {
289 const CXXRecordDecl *ClassDecl =
290 cast<CXXRecordDecl>(FD->getDeclContext());
292 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
293 // FIXME: For C++0x, we want to look for implicit *definitions* of
294 // these special member functions, rather than implicit *declarations*.
295 if (CD->isCopyConstructor(getContext())) {
296 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
297 "Cannot synthesize a non-implicit copy constructor");
298 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
299 } else if (CD->isDefaultConstructor()) {
300 assert(!ClassDecl->hasUserDeclaredConstructor() &&
301 "Cannot synthesize a non-implicit default constructor.");
302 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
304 assert(false && "Implicit constructor cannot be synthesized");
306 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
307 assert(!ClassDecl->hasUserDeclaredDestructor() &&
308 "Cannot synthesize a non-implicit destructor");
309 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
310 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
311 assert(MD->isCopyAssignment() &&
312 !ClassDecl->hasUserDeclaredCopyAssignment() &&
313 "Cannot synthesize a method that is not an implicit-defined "
315 SynthesizeCXXCopyAssignment(MD, Fn, Args);
317 assert(false && "Cannot synthesize unknown implicit function");
321 // Destroy the 'this' declaration.
323 CXXThisDecl->Destroy(getContext());
326 /// ContainsLabel - Return true if the statement contains a label in it. If
327 /// this statement is not executed normally, it not containing a label means
328 /// that we can just remove the code.
329 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
330 // Null statement, not a label!
331 if (S == 0) return false;
333 // If this is a label, we have to emit the code, consider something like:
334 // if (0) { ... foo: bar(); } goto foo;
335 if (isa<LabelStmt>(S))
338 // If this is a case/default statement, and we haven't seen a switch, we have
340 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
343 // If this is a switch statement, we want to ignore cases below it.
344 if (isa<SwitchStmt>(S))
345 IgnoreCaseStmts = true;
347 // Scan subexpressions for verboten labels.
348 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
350 if (ContainsLabel(*I, IgnoreCaseStmts))
357 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
358 /// a constant, or if it does but contains a label, return 0. If it constant
359 /// folds to 'true' and does not contain a label, return 1, if it constant folds
360 /// to 'false' and does not contain a label, return -1.
361 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
362 // FIXME: Rename and handle conversion of other evaluatable things
364 Expr::EvalResult Result;
365 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
366 Result.HasSideEffects)
367 return 0; // Not foldable, not integer or not fully evaluatable.
369 if (CodeGenFunction::ContainsLabel(Cond))
370 return 0; // Contains a label.
372 return Result.Val.getInt().getBoolValue() ? 1 : -1;
376 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
377 /// statement) to the specified blocks. Based on the condition, this might try
378 /// to simplify the codegen of the conditional based on the branch.
380 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
381 llvm::BasicBlock *TrueBlock,
382 llvm::BasicBlock *FalseBlock) {
383 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
384 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
386 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
387 // Handle X && Y in a condition.
388 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
389 // If we have "1 && X", simplify the code. "0 && X" would have constant
390 // folded if the case was simple enough.
391 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
392 // br(1 && X) -> br(X).
393 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
396 // If we have "X && 1", simplify the code to use an uncond branch.
397 // "X && 0" would have been constant folded to 0.
398 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
399 // br(X && 1) -> br(X).
400 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
403 // Emit the LHS as a conditional. If the LHS conditional is false, we
404 // want to jump to the FalseBlock.
405 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
406 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
409 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
411 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
412 // If we have "0 || X", simplify the code. "1 || X" would have constant
413 // folded if the case was simple enough.
414 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
415 // br(0 || X) -> br(X).
416 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
419 // If we have "X || 0", simplify the code to use an uncond branch.
420 // "X || 1" would have been constant folded to 1.
421 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
422 // br(X || 0) -> br(X).
423 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
426 // Emit the LHS as a conditional. If the LHS conditional is true, we
427 // want to jump to the TrueBlock.
428 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
429 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
432 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
437 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
438 // br(!x, t, f) -> br(x, f, t)
439 if (CondUOp->getOpcode() == UnaryOperator::LNot)
440 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
443 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
444 // Handle ?: operator.
446 // Just ignore GNU ?: extension.
447 if (CondOp->getLHS()) {
448 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
449 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
450 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
451 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
453 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
455 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
460 // Emit the code with the fully general case.
461 llvm::Value *CondV = EvaluateExprAsBool(Cond);
462 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
465 /// ErrorUnsupported - Print out an error that codegen doesn't support the
466 /// specified stmt yet.
467 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
469 CGM.ErrorUnsupported(S, Type, OmitOnError);
472 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
473 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
474 if (DestPtr->getType() != BP)
475 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
477 // Get size and alignment info for this aggregate.
478 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
480 // Don't bother emitting a zero-byte memset.
481 if (TypeInfo.first == 0)
484 // FIXME: Handle variable sized types.
485 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
488 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
489 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
490 // TypeInfo.first describes size in bits.
491 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
492 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
496 #ifndef USEINDIRECTBRANCH
497 unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
498 // Use LabelIDs.size()+1 as the new ID if one hasn't been assigned.
499 unsigned &Entry = LabelIDs[L];
500 if (Entry) return Entry;
503 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
504 // Make sure that there is a block for the indirect goto.
505 if (IndirectBranch == 0)
506 GetIndirectGotoBlock();
509 #ifndef USEINDIRECTBRANCH
510 Entry = LabelIDs.size();
512 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
515 #ifndef USEINDIRECTBRANCH
516 // If this is the first "address taken" of a label and the indirect goto has
517 // already been seen, add this to it.
518 if (IndirectGotoSwitch) {
519 // If this is the first address-taken label, set it as the default dest.
521 IndirectGotoSwitch->setSuccessor(0, getBasicBlockForLabel(L));
523 // Otherwise add it to the switch as a new dest.
524 const llvm::IntegerType *Int32Ty = llvm::Type::getInt32Ty(VMContext);
525 IndirectGotoSwitch->addCase(llvm::ConstantInt::get(Int32Ty, Entry),
526 getBasicBlockForLabel(L));
532 // Make sure the indirect branch includes all of the address-taken blocks.
533 IndirectBranch->addDestination(BB);
534 return llvm::BlockAddress::get(CurFn, BB);
538 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
539 #ifndef USEINDIRECTBRANCH
540 // If we already made the switch stmt for indirect goto, return its block.
541 if (IndirectGotoSwitch) return IndirectGotoSwitch->getParent();
543 // If we already made the indirect branch for indirect goto, return its block.
544 if (IndirectBranch) return IndirectBranch->getParent();
547 #ifndef USEINDIRECTBRANCH
548 EmitBlock(createBasicBlock("indirectgoto"));
550 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
553 #ifndef USEINDIRECTBRANCH
554 const llvm::IntegerType *Int32Ty = llvm::Type::getInt32Ty(VMContext);
556 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
559 // Create the PHI node that indirect gotos will add entries to.
560 #ifndef USEINDIRECTBRANCH
561 llvm::Value *DestVal = Builder.CreatePHI(Int32Ty, "indirect.goto.dest");
563 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
566 #ifndef USEINDIRECTBRANCH
567 // Create the switch instruction. For now, set the insert block to this block
568 // which will be fixed as labels are added.
569 IndirectGotoSwitch = Builder.CreateSwitch(DestVal, Builder.GetInsertBlock());
571 // Clear the insertion point to indicate we are in unreachable code.
572 Builder.ClearInsertionPoint();
574 // If we already have labels created, add them.
575 if (!LabelIDs.empty()) {
576 // Invert LabelID's so that the order is determinstic.
577 std::vector<const LabelStmt*> AddrTakenLabelsByID;
578 AddrTakenLabelsByID.resize(LabelIDs.size());
580 for (std::map<const LabelStmt*,unsigned>::iterator
581 LI = LabelIDs.begin(), LE = LabelIDs.end(); LI != LE; ++LI) {
582 assert(LI->second-1 < AddrTakenLabelsByID.size() &&
583 "Numbering inconsistent");
584 AddrTakenLabelsByID[LI->second-1] = LI->first;
587 // Set the default entry as the first block.
588 IndirectGotoSwitch->setSuccessor(0,
589 getBasicBlockForLabel(AddrTakenLabelsByID[0]));
591 // FIXME: The iteration order of this is nondeterminstic!
592 for (unsigned i = 1, e = AddrTakenLabelsByID.size(); i != e; ++i)
593 IndirectGotoSwitch->addCase(llvm::ConstantInt::get(Int32Ty, i+1),
594 getBasicBlockForLabel(AddrTakenLabelsByID[i]));
596 // Otherwise, create a dead block and set it as the default dest. This will
597 // be removed by the optimizers after the indirect goto is set up.
598 llvm::BasicBlock *Dummy = createBasicBlock("indgoto.dummy");
600 IndirectGotoSwitch->setSuccessor(0, Dummy);
601 Builder.CreateUnreachable();
602 Builder.ClearInsertionPoint();
605 return IndirectGotoSwitch->getParent();
607 // Create the indirect branch instruction.
608 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
609 return IndirectBranch->getParent();
613 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
614 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
616 assert(SizeEntry && "Did not emit size for type");
620 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
621 assert(Ty->isVariablyModifiedType() &&
622 "Must pass variably modified type to EmitVLASizes!");
626 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
627 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
630 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
632 // Get the element size;
633 QualType ElemTy = VAT->getElementType();
634 llvm::Value *ElemSize;
635 if (ElemTy->isVariableArrayType())
636 ElemSize = EmitVLASize(ElemTy);
638 ElemSize = llvm::ConstantInt::get(SizeTy,
639 getContext().getTypeSize(ElemTy) / 8);
641 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
642 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
644 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
650 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
651 EmitVLASize(AT->getElementType());
655 const PointerType *PT = Ty->getAs<PointerType>();
656 assert(PT && "unknown VM type!");
657 EmitVLASize(PT->getPointeeType());
661 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
662 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
663 return EmitScalarExpr(E);
665 return EmitLValue(E).getAddress();
668 void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
669 llvm::BasicBlock *CleanupExitBlock) {
670 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock));
673 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
674 assert(CleanupEntries.size() >= OldCleanupStackSize &&
675 "Cleanup stack mismatch!");
677 while (CleanupEntries.size() > OldCleanupStackSize)
681 CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
682 CleanupEntry &CE = CleanupEntries.back();
684 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
686 std::vector<llvm::BasicBlock *> Blocks;
687 std::swap(Blocks, CE.Blocks);
689 std::vector<llvm::BranchInst *> BranchFixups;
690 std::swap(BranchFixups, CE.BranchFixups);
692 CleanupEntries.pop_back();
694 // Check if any branch fixups pointed to the scope we just popped. If so,
695 // we can remove them.
696 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
697 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
698 BlockScopeMap::iterator I = BlockScopes.find(Dest);
700 if (I == BlockScopes.end())
703 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
705 if (I->second == CleanupEntries.size()) {
706 // We don't need to do this branch fixup.
707 BranchFixups[i] = BranchFixups.back();
708 BranchFixups.pop_back();
715 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
716 llvm::BasicBlock *EndBlock = 0;
717 if (!BranchFixups.empty()) {
719 SwitchBlock = createBasicBlock("cleanup.switch");
720 EndBlock = createBasicBlock("cleanup.end");
722 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
724 Builder.SetInsertPoint(SwitchBlock);
726 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
728 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
730 // Create a switch instruction to determine where to jump next.
731 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
732 BranchFixups.size());
734 // Restore the current basic block (if any)
736 Builder.SetInsertPoint(CurBB);
738 // If we had a current basic block, we also need to emit an instruction
739 // to initialize the cleanup destination.
740 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
743 Builder.ClearInsertionPoint();
745 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
746 llvm::BranchInst *BI = BranchFixups[i];
747 llvm::BasicBlock *Dest = BI->getSuccessor(0);
749 // Fixup the branch instruction to point to the cleanup block.
750 BI->setSuccessor(0, CleanupEntryBlock);
752 if (CleanupEntries.empty()) {
753 llvm::ConstantInt *ID;
755 // Check if we already have a destination for this block.
756 if (Dest == SI->getDefaultDest())
757 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
759 ID = SI->findCaseDest(Dest);
761 // No code found, get a new unique one by using the number of
762 // switch successors.
763 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
764 SI->getNumSuccessors());
765 SI->addCase(ID, Dest);
769 // Store the jump destination before the branch instruction.
770 new llvm::StoreInst(ID, DestCodePtr, BI);
772 // We need to jump through another cleanup block. Create a pad block
773 // with a branch instruction that jumps to the final destination and
774 // add it as a branch fixup to the current cleanup scope.
776 // Create the pad block.
777 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
779 // Create a unique case ID.
780 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
781 SI->getNumSuccessors());
783 // Store the jump destination before the branch instruction.
784 new llvm::StoreInst(ID, DestCodePtr, BI);
786 // Add it as the destination.
787 SI->addCase(ID, CleanupPad);
789 // Create the branch to the final destination.
790 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
791 CleanupPad->getInstList().push_back(BI);
793 // And add it as a branch fixup.
794 CleanupEntries.back().BranchFixups.push_back(BI);
799 // Remove all blocks from the block scope map.
800 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
801 assert(BlockScopes.count(Blocks[i]) &&
802 "Did not find block in scope map!");
804 BlockScopes.erase(Blocks[i]);
807 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock);
810 void CodeGenFunction::EmitCleanupBlock() {
811 CleanupBlockInfo Info = PopCleanupBlock();
813 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
814 if (CurBB && !CurBB->getTerminator() &&
815 Info.CleanupBlock->getNumUses() == 0) {
816 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
817 delete Info.CleanupBlock;
819 EmitBlock(Info.CleanupBlock);
821 if (Info.SwitchBlock)
822 EmitBlock(Info.SwitchBlock);
824 EmitBlock(Info.EndBlock);
827 void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
828 assert(!CleanupEntries.empty() &&
829 "Trying to add branch fixup without cleanup block!");
831 // FIXME: We could be more clever here and check if there's already a branch
832 // fixup for this destination and recycle it.
833 CleanupEntries.back().BranchFixups.push_back(BI);
836 void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
837 if (!HaveInsertPoint())
840 llvm::BranchInst* BI = Builder.CreateBr(Dest);
842 Builder.ClearInsertionPoint();
844 // The stack is empty, no need to do any cleanup.
845 if (CleanupEntries.empty())
848 if (!Dest->getParent()) {
849 // We are trying to branch to a block that hasn't been inserted yet.
854 BlockScopeMap::iterator I = BlockScopes.find(Dest);
855 if (I == BlockScopes.end()) {
856 // We are trying to jump to a block that is outside of any cleanup scope.
861 assert(I->second < CleanupEntries.size() &&
862 "Trying to branch into cleanup region");
864 if (I->second == CleanupEntries.size() - 1) {
865 // We have a branch to a block in the same scope.