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