CodeGenFunction.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. #include "CodeGenFunction.h"
  14. #include "CodeGenModule.h"
  15. #include "clang/Basic/TargetInfo.h"
  16. #include "clang/AST/AST.h"
  17. #include "llvm/CallingConv.h"
  18. #include "llvm/Constants.h"
  19. #include "llvm/DerivedTypes.h"
  20. #include "llvm/Function.h"
  21. #include "llvm/Analysis/Verifier.h"
  22. #include "llvm/Support/CFG.h"
  23. using namespace clang;
  24. using namespace CodeGen;
  25. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
  26. : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
  27. CaseRangeBlock(NULL) {}
  28. ASTContext &CodeGenFunction::getContext() const {
  29. return CGM.getContext();
  30. }
  31. llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
  32. llvm::BasicBlock *&BB = LabelMap[S];
  33. if (BB) return BB;
  34. // Create, but don't insert, the new block.
  35. return BB = new llvm::BasicBlock(S->getName());
  36. }
  37. llvm::Constant *
  38. CodeGenFunction::GetAddrOfStaticLocalVar(const BlockVarDecl *BVD) {
  39. return cast<llvm::Constant>(LocalDeclMap[BVD]);
  40. }
  41. const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  42. return CGM.getTypes().ConvertType(T);
  43. }
  44. bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
  45. return !T->isRealType() && !T->isPointerType() && !T->isReferenceType() &&
  46. !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
  47. }
  48. /// Generate an Objective-C method. An Objective-C method is a C function with
  49. /// its pointer, name, and types registered in the class struture.
  50. // FIXME: This method contains a lot of code copied and pasted from
  51. // GenerateCode. This should be factored out.
  52. void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
  53. llvm::SmallVector<const llvm::Type *, 16> ParamTypes;
  54. for (unsigned i=0 ; i<OMD->param_size() ; i++) {
  55. ParamTypes.push_back(ConvertType(OMD->getParamDecl(i)->getType()));
  56. }
  57. CurFn = CGM.getObjCRuntime()->MethodPreamble(ConvertType(OMD->getResultType()),
  58. llvm::PointerType::getUnqual(llvm::Type::Int32Ty),
  59. ParamTypes.begin(),
  60. OMD->param_size(),
  61. OMD->isVariadic());
  62. llvm::BasicBlock *EntryBB = new llvm::BasicBlock("entry", CurFn);
  63. // Create a marker to make it easy to insert allocas into the entryblock
  64. // later. Don't create this with the builder, because we don't want it
  65. // folded.
  66. llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
  67. AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
  68. EntryBB);
  69. FnRetTy = OMD->getResultType();
  70. Builder.SetInsertPoint(EntryBB);
  71. // Emit allocs for param decls. Give the LLVM Argument nodes names.
  72. llvm::Function::arg_iterator AI = CurFn->arg_begin();
  73. // Name the struct return argument.
  74. // FIXME: Probably should be in the runtime, or it will trample the other
  75. // hidden arguments.
  76. if (hasAggregateLLVMType(OMD->getResultType())) {
  77. AI->setName("agg.result");
  78. ++AI;
  79. }
  80. // Add implicit parameters to the decl map.
  81. // TODO: Add something to AST to let the runtime specify the names and types
  82. // of these.
  83. llvm::Value *&DMEntry = LocalDeclMap[&(*OMD->getSelfDecl())];
  84. DMEntry = AI;
  85. ++AI; ++AI;
  86. for (unsigned i = 0, e = OMD->getNumParams(); i != e; ++i, ++AI) {
  87. assert(AI != CurFn->arg_end() && "Argument mismatch!");
  88. EmitParmDecl(*OMD->getParamDecl(i), AI);
  89. }
  90. // Emit the function body.
  91. EmitStmt(OMD->getBody());
  92. // Emit a return for code that falls off the end. If insert point
  93. // is a dummy block with no predecessors then remove the block itself.
  94. llvm::BasicBlock *BB = Builder.GetInsertBlock();
  95. if (isDummyBlock(BB))
  96. BB->eraseFromParent();
  97. else {
  98. if (CurFn->getReturnType() == llvm::Type::VoidTy)
  99. Builder.CreateRetVoid();
  100. else
  101. Builder.CreateRet(llvm::UndefValue::get(CurFn->getReturnType()));
  102. }
  103. assert(BreakContinueStack.empty() &&
  104. "mismatched push/pop in break/continue stack!");
  105. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  106. AllocaInsertPt->eraseFromParent();
  107. AllocaInsertPt = 0;
  108. // Verify that the function is well formed.
  109. assert(!verifyFunction(*CurFn) && "Generated method is not well formed.");
  110. }
  111. void CodeGenFunction::GenerateCode(const FunctionDecl *FD) {
  112. LLVMIntTy = ConvertType(getContext().IntTy);
  113. LLVMPointerWidth = static_cast<unsigned>(
  114. getContext().getTypeSize(getContext().getPointerType(getContext().VoidTy)));
  115. CurFuncDecl = FD;
  116. FnRetTy = CurFuncDecl->getType()->getAsFunctionType()->getResultType();
  117. CurFn = cast<llvm::Function>(CGM.GetAddrOfFunctionDecl(FD, true));
  118. assert(CurFn->isDeclaration() && "Function already has body?");
  119. // TODO: Set up linkage and many other things. Note, this is a simple
  120. // approximation of what we really want.
  121. if (FD->getAttr<DLLImportAttr>())
  122. CurFn->setLinkage(llvm::Function::DLLImportLinkage);
  123. else if (FD->getAttr<DLLExportAttr>())
  124. CurFn->setLinkage(llvm::Function::DLLExportLinkage);
  125. else if (FD->getAttr<WeakAttr>() || FD->isInline())
  126. CurFn->setLinkage(llvm::Function::WeakLinkage);
  127. else if (FD->getStorageClass() == FunctionDecl::Static)
  128. CurFn->setLinkage(llvm::Function::InternalLinkage);
  129. if (FD->getAttr<FastCallAttr>())
  130. CurFn->setCallingConv(llvm::CallingConv::Fast);
  131. if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
  132. CurFn->setVisibility(attr->getVisibility());
  133. // FIXME: else handle -fvisibility
  134. unsigned FuncAttrs = 0;
  135. if (FD->getAttr<NoThrowAttr>())
  136. FuncAttrs |= llvm::ParamAttr::NoUnwind;
  137. if (FD->getAttr<NoReturnAttr>())
  138. FuncAttrs |= llvm::ParamAttr::NoReturn;
  139. if (FuncAttrs) {
  140. llvm::ParamAttrsWithIndex PAWI =
  141. llvm::ParamAttrsWithIndex::get(0, FuncAttrs);
  142. CurFn->setParamAttrs(llvm::PAListPtr::get(&PAWI, 1));
  143. }
  144. llvm::BasicBlock *EntryBB = new llvm::BasicBlock("entry", CurFn);
  145. // Create a marker to make it easy to insert allocas into the entryblock
  146. // later. Don't create this with the builder, because we don't want it
  147. // folded.
  148. llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
  149. AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
  150. EntryBB);
  151. Builder.SetInsertPoint(EntryBB);
  152. // Emit allocs for param decls. Give the LLVM Argument nodes names.
  153. llvm::Function::arg_iterator AI = CurFn->arg_begin();
  154. // Name the struct return argument.
  155. if (hasAggregateLLVMType(FD->getResultType())) {
  156. AI->setName("agg.result");
  157. ++AI;
  158. }
  159. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i, ++AI) {
  160. assert(AI != CurFn->arg_end() && "Argument mismatch!");
  161. EmitParmDecl(*FD->getParamDecl(i), AI);
  162. }
  163. // Emit the function body.
  164. EmitStmt(FD->getBody());
  165. // Emit a return for code that falls off the end. If insert point
  166. // is a dummy block with no predecessors then remove the block itself.
  167. llvm::BasicBlock *BB = Builder.GetInsertBlock();
  168. if (isDummyBlock(BB))
  169. BB->eraseFromParent();
  170. else {
  171. // FIXME: if this is C++ main, this should return 0.
  172. if (CurFn->getReturnType() == llvm::Type::VoidTy)
  173. Builder.CreateRetVoid();
  174. else
  175. Builder.CreateRet(llvm::UndefValue::get(CurFn->getReturnType()));
  176. }
  177. assert(BreakContinueStack.empty() &&
  178. "mismatched push/pop in break/continue stack!");
  179. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  180. AllocaInsertPt->eraseFromParent();
  181. AllocaInsertPt = 0;
  182. // Verify that the function is well formed.
  183. assert(!verifyFunction(*CurFn) && "Generated function is not well formed.");
  184. }
  185. /// isDummyBlock - Return true if BB is an empty basic block
  186. /// with no predecessors.
  187. bool CodeGenFunction::isDummyBlock(const llvm::BasicBlock *BB) {
  188. if (BB->empty() && pred_begin(BB) == pred_end(BB))
  189. return true;
  190. return false;
  191. }
  192. /// StartBlock - Start new block named N. If insert block is a dummy block
  193. /// then reuse it.
  194. void CodeGenFunction::StartBlock(const char *N) {
  195. llvm::BasicBlock *BB = Builder.GetInsertBlock();
  196. if (!isDummyBlock(BB))
  197. EmitBlock(new llvm::BasicBlock(N));
  198. else
  199. BB->setName(N);
  200. }
  201. /// getCGRecordLayout - Return record layout info.
  202. const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
  203. QualType Ty) {
  204. const RecordType *RTy = Ty->getAsRecordType();
  205. assert (RTy && "Unexpected type. RecordType expected here.");
  206. return CGT.getCGRecordLayout(RTy->getDecl());
  207. }
  208. /// WarnUnsupported - Print out a warning that codegen doesn't support the
  209. /// specified stmt yet.
  210. void CodeGenFunction::WarnUnsupported(const Stmt *S, const char *Type) {
  211. CGM.WarnUnsupported(S, Type);
  212. }