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/ASTContext.h" 19 #include "clang/AST/Decl.h" 20 #include "llvm/Analysis/Verifier.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) { 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 = llvm::BasicBlock::Create(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::ConvertType(QualType T) { 56 return CGM.getTypes().ConvertType(T); 57 } 58 59 bool CodeGenFunction::isObjCPointerType(QualType T) { 60 // All Objective-C types are pointers. 61 return T->isObjCInterfaceType() || 62 T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType(); 63 } 64 65 bool CodeGenFunction::hasAggregateLLVMType(QualType T) { 66 return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() && 67 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType(); 68 } 69 70 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 71 // Finish emission of indirect switches. 72 EmitIndirectSwitches(); 73 74 // Emit debug descriptor for function end. 75 if (CGDebugInfo *DI = CGM.getDebugInfo()) { 76 DI->setLocation(EndLoc); 77 DI->EmitRegionEnd(CurFn, Builder); 78 } 79 80 assert(BreakContinueStack.empty() && 81 "mismatched push/pop in break/continue stack!"); 82 83 // Emit function epilog (to return). This has the nice side effect 84 // of also automatically handling code that falls off the end. 85 EmitBlock(ReturnBlock); 86 EmitFunctionEpilog(FnRetTy, ReturnValue); 87 88 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 89 AllocaInsertPt->eraseFromParent(); 90 AllocaInsertPt = 0; 91 92 // Verify that the function is well formed. 93 if (verifyFunction(*CurFn, llvm::PrintMessageAction)) { 94 CurFn->dump(); 95 assert(0 && "Function failed verification!"); 96 } 97 } 98 99 void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy, 100 llvm::Function *Fn, 101 const FunctionArgList &Args, 102 SourceLocation StartLoc) { 103 CurFuncDecl = D; 104 FnRetTy = RetTy; 105 CurFn = Fn; 106 assert(CurFn->isDeclaration() && "Function already has body?"); 107 108 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn); 109 110 // Create a marker to make it easy to insert allocas into the entryblock 111 // later. Don't create this with the builder, because we don't want it 112 // folded. 113 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty); 114 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt", 115 EntryBB); 116 117 ReturnBlock = llvm::BasicBlock::Create("return"); 118 ReturnValue = 0; 119 if (!RetTy->isVoidType()) 120 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval"); 121 122 Builder.SetInsertPoint(EntryBB); 123 124 // Emit subprogram debug descriptor. 125 // FIXME: The cast here is a huge hack. 126 if (CGDebugInfo *DI = CGM.getDebugInfo()) { 127 DI->setLocation(StartLoc); 128 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 129 DI->EmitFunctionStart(FD->getName(), RetTy, CurFn, Builder); 130 } else { 131 // Just use LLVM function name. 132 DI->EmitFunctionStart(Fn->getName().c_str(), 133 RetTy, CurFn, Builder); 134 } 135 } 136 137 EmitFunctionProlog(CurFn, FnRetTy, Args); 138 } 139 140 void CodeGenFunction::GenerateCode(const FunctionDecl *FD, 141 llvm::Function *Fn) { 142 FunctionArgList Args; 143 if (FD->getNumParams()) { 144 const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto(); 145 assert(FProto && "Function def must have prototype!"); 146 147 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) 148 Args.push_back(std::make_pair(FD->getParamDecl(i), 149 FProto->getArgType(i))); 150 } 151 152 StartFunction(FD, FD->getResultType(), Fn, Args, 153 cast<CompoundStmt>(FD->getBody())->getLBracLoc()); 154 155 EmitStmt(FD->getBody()); 156 157 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody()); 158 if (S) { 159 FinishFunction(S->getRBracLoc()); 160 } else { 161 FinishFunction(); 162 } 163 } 164 165 /// isDummyBlock - Return true if BB is an empty basic block 166 /// with no predecessors. 167 bool CodeGenFunction::isDummyBlock(const llvm::BasicBlock *BB) { 168 if (BB->empty() && pred_begin(BB) == pred_end(BB) && !BB->hasName()) 169 return true; 170 return false; 171 } 172 173 /// StartBlock - Start new block named N. If insert block is a dummy block 174 /// then reuse it. 175 void CodeGenFunction::StartBlock(const char *N) { 176 llvm::BasicBlock *BB = Builder.GetInsertBlock(); 177 if (!isDummyBlock(BB)) 178 EmitBlock(llvm::BasicBlock::Create(N)); 179 else 180 BB->setName(N); 181 } 182 183 /// getCGRecordLayout - Return record layout info. 184 const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT, 185 QualType Ty) { 186 const RecordType *RTy = Ty->getAsRecordType(); 187 assert (RTy && "Unexpected type. RecordType expected here."); 188 189 return CGT.getCGRecordLayout(RTy->getDecl()); 190 } 191 192 /// ErrorUnsupported - Print out an error that codegen doesn't support the 193 /// specified stmt yet. 194 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type, 195 bool OmitOnError) { 196 CGM.ErrorUnsupported(S, Type, OmitOnError); 197 } 198 199 unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) { 200 // Use LabelIDs.size() as the new ID if one hasn't been assigned. 201 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second; 202 } 203 204 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) 205 { 206 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 207 if (DestPtr->getType() != BP) 208 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 209 210 // Get size and alignment info for this aggregate. 211 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 212 213 // FIXME: Handle variable sized types. 214 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth); 215 216 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr, 217 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty), 218 // TypeInfo.first describes size in bits. 219 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 220 llvm::ConstantInt::get(llvm::Type::Int32Ty, 221 TypeInfo.second/8)); 222 } 223 224 void CodeGenFunction::EmitIndirectSwitches() { 225 llvm::BasicBlock *Default; 226 227 if (IndirectSwitches.empty()) 228 return; 229 230 if (!LabelIDs.empty()) { 231 Default = getBasicBlockForLabel(LabelIDs.begin()->first); 232 } else { 233 // No possible targets for indirect goto, just emit an infinite 234 // loop. 235 Default = llvm::BasicBlock::Create("indirectgoto.loop", CurFn); 236 llvm::BranchInst::Create(Default, Default); 237 } 238 239 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(), 240 e = IndirectSwitches.end(); i != e; ++i) { 241 llvm::SwitchInst *I = *i; 242 243 I->setSuccessor(0, Default); 244 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(), 245 LE = LabelIDs.end(); LI != LE; ++LI) { 246 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty, 247 LI->second), 248 getBasicBlockForLabel(LI->first)); 249 } 250 } 251 } 252