blob: 190da77b2b7f5b926973bc000ab54239f26d5b70 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source 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"
Chris Lattner9d4e6202007-12-02 01:43:38 +000017#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "clang/AST/AST.h"
19#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
22#include "llvm/Analysis/Verifier.h"
Devang Patel97299362007-09-28 21:49:18 +000023#include "llvm/Support/CFG.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024using namespace clang;
25using namespace CodeGen;
26
27CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Devang Patel347ca322007-10-08 20:57:48 +000028 : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
29 CaseRangeBlock(NULL) {}
Chris Lattner4b009652007-07-25 00:24:17 +000030
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 = new llvm::BasicBlock(S->getName());
42}
43
44
45const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
46 return CGM.getTypes().ConvertType(T);
47}
48
49bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssoncebb8d62007-10-12 23:56:29 +000050 return !T->isRealType() && !T->isPointerType() && !T->isReferenceType() &&
51 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +000052}
53
54
55void CodeGenFunction::GenerateCode(const FunctionDecl *FD) {
56 LLVMIntTy = ConvertType(getContext().IntTy);
Chris Lattnera96e0d82007-09-04 02:34:27 +000057 LLVMPointerWidth = static_cast<unsigned>(
Chris Lattner4b009652007-07-25 00:24:17 +000058 getContext().getTypeSize(getContext().getPointerType(getContext().VoidTy),
Chris Lattnera96e0d82007-09-04 02:34:27 +000059 SourceLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000060
Chris Lattner4b009652007-07-25 00:24:17 +000061 CurFuncDecl = FD;
Chris Lattner0e4755d2007-12-02 06:27:33 +000062 llvm::Constant *CurFnC = CGM.GetAddrOfGlobalDecl(FD);
63 if (!(CurFn = dyn_cast<llvm::Function>(CurFnC))) {
64 // If CurFnC is not a constant, it must be a bitcast of another function.
65 llvm::ConstantExpr *CurFnCE = cast<llvm::ConstantExpr>(CurFnC);
66 assert(CurFnCE->getOpcode() == llvm::Instruction::BitCast &&
67 "Unexpected name collision");
68 llvm::Function *OtherFunc = cast<llvm::Function>(CurFnCE->getOperand(0));
69
70 // This happens if there is a prototype for a function (e.g. "int f()") and
71 // then a definition of a different type (e.g. "int f(int x)"). Start by
72 // making a new function of the correct type, RAUW, then steal the name.
73 const llvm::PointerType *PTy = cast<llvm::PointerType>(CurFnC->getType());
74 const llvm::FunctionType *FTy =
75 cast<llvm::FunctionType>(PTy->getElementType());
76 CurFn = new llvm::Function(FTy, llvm::Function::ExternalLinkage, "",
77 &CGM.getModule());
78 CurFn->takeName(OtherFunc);
79
80 // Replace uses of OtherFunc with the Function we will endow with a body.
81 llvm::Constant *NewPtrForOldDecl =
82 llvm::ConstantExpr::getBitCast(CurFn, OtherFunc->getType());
83 OtherFunc->replaceAllUsesWith(NewPtrForOldDecl);
84
85 // Make sure the GlobalDecl map for FD is up-to-date.
86 CGM.ChangeGlobalDeclMap(FD, CurFn);
87
88 // FIXME: Update the globaldeclmap for the previous decl of this name. We
89 // really want a way to walk all of these, but we don't have it yet. This
90 // is incredibly slow!
91 CGM.ReplaceMapValuesWith(OtherFunc, NewPtrForOldDecl);
92
93 // Ok, delete the old function now, which is dead.
94 assert(OtherFunc->isDeclaration() && "Shouldn't replace non-declaration");
95 OtherFunc->eraseFromParent();
96 }
Chris Lattner4b009652007-07-25 00:24:17 +000097
Chris Lattner4b009652007-07-25 00:24:17 +000098 assert(CurFn->isDeclaration() && "Function already has body?");
99
Chris Lattner23d9e712007-11-27 06:46:51 +0000100 // TODO: Set up linkage and many other things. Note, this is a simple
101 // approximation of what we really want.
102 if (FD->getStorageClass() == FunctionDecl::Static)
103 CurFn->setLinkage(llvm::Function::InternalLinkage);
104 else if (FD->isInline())
105 CurFn->setLinkage(llvm::Function::WeakLinkage);
106
Chris Lattner4b009652007-07-25 00:24:17 +0000107 llvm::BasicBlock *EntryBB = new llvm::BasicBlock("entry", CurFn);
108
109 Builder.SetInsertPoint(EntryBB);
110
111 // Create a marker to make it easy to insert allocas into the entryblock
112 // later.
113 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
114 AllocaInsertPt = Builder.CreateBitCast(Undef,llvm::Type::Int32Ty, "allocapt");
115
116 // Emit allocs for param decls. Give the LLVM Argument nodes names.
117 llvm::Function::arg_iterator AI = CurFn->arg_begin();
118
119 // Name the struct return argument.
120 if (hasAggregateLLVMType(FD->getResultType())) {
121 AI->setName("agg.result");
122 ++AI;
123 }
124
125 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i, ++AI) {
126 assert(AI != CurFn->arg_end() && "Argument mismatch!");
127 EmitParmDecl(*FD->getParamDecl(i), AI);
128 }
129
130 // Emit the function body.
131 EmitStmt(FD->getBody());
132
Devang Patel97299362007-09-28 21:49:18 +0000133 // Emit a return for code that falls off the end. If insert point
134 // is a dummy block with no predecessors then remove the block itself.
135 llvm::BasicBlock *BB = Builder.GetInsertBlock();
136 if (isDummyBlock(BB))
137 BB->eraseFromParent();
138 else {
139 // FIXME: if this is C++ main, this should return 0.
140 if (CurFn->getReturnType() == llvm::Type::VoidTy)
141 Builder.CreateRetVoid();
142 else
143 Builder.CreateRet(llvm::UndefValue::get(CurFn->getReturnType()));
144 }
Chris Lattner4b009652007-07-25 00:24:17 +0000145 assert(BreakContinueStack.empty() &&
146 "mismatched push/pop in break/continue stack!");
147
148 // Verify that the function is well formed.
149 assert(!verifyFunction(*CurFn));
150}
151
Devang Patel97299362007-09-28 21:49:18 +0000152/// isDummyBlock - Return true if BB is an empty basic block
153/// with no predecessors.
154bool CodeGenFunction::isDummyBlock(const llvm::BasicBlock *BB) {
155 if (BB->empty() && pred_begin(BB) == pred_end(BB))
156 return true;
157 return false;
158}
159
Devang Patele58e0802007-10-04 23:45:31 +0000160/// StartBlock - Start new block named N. If insert block is a dummy block
161/// then reuse it.
162void CodeGenFunction::StartBlock(const char *N) {
163 llvm::BasicBlock *BB = Builder.GetInsertBlock();
164 if (!isDummyBlock(BB))
165 EmitBlock(new llvm::BasicBlock(N));
166 else
167 BB->setName(N);
168}
169
Devang Patel7a78e432007-11-01 19:11:01 +0000170/// getCGRecordLayout - Return record layout info.
171const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
172 QualType RTy) {
Devang Patelaebd83f2007-10-23 02:10:49 +0000173 assert (isa<RecordType>(RTy)
174 && "Unexpected type. RecordType expected here.");
175
176 const llvm::Type *Ty = ConvertType(RTy);
177 assert (Ty && "Unable to find llvm::Type");
178
Devang Patel7a78e432007-11-01 19:11:01 +0000179 return CGT.getCGRecordLayout(Ty);
Devang Patelaebd83f2007-10-23 02:10:49 +0000180}
Chris Lattner9d4e6202007-12-02 01:43:38 +0000181
182/// WarnUnsupported - Print out a warning that codegen doesn't support the
183/// specified stmt yet.
Chris Lattnere8f49632007-12-02 01:49:16 +0000184void CodeGenFunction::WarnUnsupported(const Stmt *S, const char *Type) {
Chris Lattner9d4e6202007-12-02 01:43:38 +0000185 unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Warning,
Chris Lattnere8f49632007-12-02 01:49:16 +0000186 "cannot codegen this %0 yet");
Chris Lattner9d4e6202007-12-02 01:43:38 +0000187 SourceRange Range = S->getSourceRange();
Chris Lattnere8f49632007-12-02 01:49:16 +0000188 std::string Msg = Type;
189 CGM.getDiags().Report(S->getLocStart(), DiagID, &Msg, 1, &Range, 1);
Chris Lattner9d4e6202007-12-02 01:43:38 +0000190}
191