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