CodeGenFunction.cpp revision f5bd45c8e6fa7519cdc17ec3ff4917e279c6a041
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/Support/CFG.h"
21using namespace clang;
22using namespace CodeGen;
23
24CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
25  : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
26    CaseRangeBlock(NULL) {
27    LLVMIntTy = ConvertType(getContext().IntTy);
28    LLVMPointerWidth = Target.getPointerWidth(0);
29}
30
31ASTContext &CodeGenFunction::getContext() const {
32  return CGM.getContext();
33}
34
35
36llvm::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 = createBasicBlock(S->getName());
42}
43
44llvm::Constant *
45CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
46  return cast<llvm::Constant>(LocalDeclMap[BVD]);
47}
48
49llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD)
50{
51  return LocalDeclMap[VD];
52}
53
54const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
55  return CGM.getTypes().ConvertType(T);
56}
57
58bool CodeGenFunction::isObjCPointerType(QualType T) {
59  // All Objective-C types are pointers.
60  return T->isObjCInterfaceType() ||
61    T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
62}
63
64bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
65  return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
66    !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
67}
68
69void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
70  // Finish emission of indirect switches.
71  EmitIndirectSwitches();
72
73  assert(BreakContinueStack.empty() &&
74         "mismatched push/pop in break/continue stack!");
75
76  // Emit function epilog (to return). This has the nice side effect
77  // of also automatically handling code that falls off the end.
78  EmitBlock(ReturnBlock);
79
80  // Emit debug descriptor for function end.
81  if (CGDebugInfo *DI = CGM.getDebugInfo()) {
82    DI->setLocation(EndLoc);
83    DI->EmitRegionEnd(CurFn, Builder);
84  }
85
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
93void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
94                                    llvm::Function *Fn,
95                                    const FunctionArgList &Args,
96                                    SourceLocation StartLoc) {
97  CurFuncDecl = D;
98  FnRetTy = RetTy;
99  CurFn = Fn;
100  assert(CurFn->isDeclaration() && "Function already has body?");
101
102  llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
103
104  // Create a marker to make it easy to insert allocas into the entryblock
105  // later.  Don't create this with the builder, because we don't want it
106  // folded.
107  llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
108  AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
109                                         EntryBB);
110
111  ReturnBlock = createBasicBlock("return");
112  ReturnValue = 0;
113  if (!RetTy->isVoidType())
114    ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
115
116  Builder.SetInsertPoint(EntryBB);
117
118  // Emit subprogram debug descriptor.
119  // FIXME: The cast here is a huge hack.
120  if (CGDebugInfo *DI = CGM.getDebugInfo()) {
121    DI->setLocation(StartLoc);
122    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
123      DI->EmitFunctionStart(FD->getName(), RetTy, CurFn, Builder);
124    } else {
125      // Just use LLVM function name.
126      DI->EmitFunctionStart(Fn->getName().c_str(),
127                            RetTy, CurFn, Builder);
128    }
129  }
130
131  EmitFunctionProlog(CurFn, FnRetTy, Args);
132}
133
134void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
135                                   llvm::Function *Fn) {
136  FunctionArgList Args;
137  if (FD->getNumParams()) {
138    const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
139    assert(FProto && "Function def must have prototype!");
140
141    for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
142      Args.push_back(std::make_pair(FD->getParamDecl(i),
143                                    FProto->getArgType(i)));
144  }
145
146  StartFunction(FD, FD->getResultType(), Fn, Args,
147                cast<CompoundStmt>(FD->getBody())->getLBracLoc());
148
149  EmitStmt(FD->getBody());
150
151  const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
152  if (S) {
153    FinishFunction(S->getRBracLoc());
154  } else {
155    FinishFunction();
156  }
157}
158
159/// isDummyBlock - Return true if BB is an empty basic block
160/// with no predecessors.
161bool CodeGenFunction::isDummyBlock(const llvm::BasicBlock *BB) {
162  if (BB->empty() && pred_begin(BB) == pred_end(BB) && !BB->hasName())
163    return true;
164  return false;
165}
166
167/// ContainsLabel - Return true if the statement contains a label in it.  If
168/// this statement is not executed normally, it not containing a label means
169/// that we can just remove the code.
170bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
171  // Null statement, not a label!
172  if (S == 0) return false;
173
174  // If this is a label, we have to emit the code, consider something like:
175  // if (0) {  ...  foo:  bar(); }  goto foo;
176  if (isa<LabelStmt>(S))
177    return true;
178
179  // If this is a case/default statement, and we haven't seen a switch, we have
180  // to emit the code.
181  if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
182    return true;
183
184  // If this is a switch statement, we want to ignore cases below it.
185  if (isa<SwitchStmt>(S))
186    IgnoreCaseStmts = true;
187
188  // Scan subexpressions for verboten labels.
189  for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
190       I != E; ++I)
191    if (ContainsLabel(*I, IgnoreCaseStmts))
192      return true;
193
194  return false;
195}
196
197/// getCGRecordLayout - Return record layout info.
198const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
199                                                         QualType Ty) {
200  const RecordType *RTy = Ty->getAsRecordType();
201  assert (RTy && "Unexpected type. RecordType expected here.");
202
203  return CGT.getCGRecordLayout(RTy->getDecl());
204}
205
206/// ErrorUnsupported - Print out an error that codegen doesn't support the
207/// specified stmt yet.
208void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
209                                       bool OmitOnError) {
210  CGM.ErrorUnsupported(S, Type, OmitOnError);
211}
212
213unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
214  // Use LabelIDs.size() as the new ID if one hasn't been assigned.
215  return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
216}
217
218void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
219{
220  const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
221  if (DestPtr->getType() != BP)
222    DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
223
224  // Get size and alignment info for this aggregate.
225  std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
226
227  // FIXME: Handle variable sized types.
228  const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
229
230  Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
231                      llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
232                      // TypeInfo.first describes size in bits.
233                      llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
234                      llvm::ConstantInt::get(llvm::Type::Int32Ty,
235                                             TypeInfo.second/8));
236}
237
238void CodeGenFunction::EmitIndirectSwitches() {
239  llvm::BasicBlock *Default;
240
241  if (IndirectSwitches.empty())
242    return;
243
244  if (!LabelIDs.empty()) {
245    Default = getBasicBlockForLabel(LabelIDs.begin()->first);
246  } else {
247    // No possible targets for indirect goto, just emit an infinite
248    // loop.
249    Default = createBasicBlock("indirectgoto.loop", CurFn);
250    llvm::BranchInst::Create(Default, Default);
251  }
252
253  for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
254         e = IndirectSwitches.end(); i != e; ++i) {
255    llvm::SwitchInst *I = *i;
256
257    I->setSuccessor(0, Default);
258    for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
259           LE = LabelIDs.end(); LI != LE; ++LI) {
260      I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
261                                        LI->second),
262                 getBasicBlockForLabel(LI->first));
263    }
264  }
265}
266
267llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty)
268{
269  // FIXME: This entire method is hardcoded for 32-bit X86.
270
271  const char *TargetPrefix = getContext().Target.getTargetPrefix();
272
273  if (strcmp(TargetPrefix, "x86") != 0 ||
274      getContext().Target.getPointerWidth(0) != 32)
275    return 0;
276
277  const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
278  const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
279
280  llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
281                                                       "ap");
282  llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
283  llvm::Value *AddrTyped =
284    Builder.CreateBitCast(Addr,
285                          llvm::PointerType::getUnqual(ConvertType(Ty)));
286
287  uint64_t SizeInBytes = getContext().getTypeSize(Ty) / 8;
288  const unsigned ArgumentSizeInBytes = 4;
289  if (SizeInBytes < ArgumentSizeInBytes)
290    SizeInBytes = ArgumentSizeInBytes;
291
292  llvm::Value *NextAddr =
293    Builder.CreateGEP(Addr,
294                      llvm::ConstantInt::get(llvm::Type::Int32Ty, SizeInBytes),
295                      "ap.next");
296  Builder.CreateStore(NextAddr, VAListAddrAsBPP);
297
298  return AddrTyped;
299}
300
301