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