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