CodeGenFunction.h revision 9c3fc703b29a31d40bcf5027dbb4784dd393804e
1//===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
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 is the internal per-function state used for llvm translation.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef CLANG_CODEGEN_CODEGENFUNCTION_H
15#define CLANG_CODEGEN_CODEGENFUNCTION_H
16
17#include "clang/AST/Type.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/Support/IRBuilder.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprObjC.h"
23
24#include <vector>
25#include <map>
26
27#include "CGValue.h"
28
29namespace llvm {
30  class BasicBlock;
31  class Module;
32}
33
34namespace clang {
35  class ASTContext;
36  class Decl;
37  class EnumConstantDecl;
38  class FunctionDecl;
39  class FunctionTypeProto;
40  class LabelStmt;
41  class ObjCMethodDecl;
42  class ObjCPropertyImplDecl;
43  class TargetInfo;
44  class VarDecl;
45
46namespace CodeGen {
47  class CodeGenModule;
48  class CodeGenTypes;
49  class CGRecordLayout;
50
51/// CodeGenFunction - This class organizes the per-function state that is used
52/// while generating LLVM code.
53class CodeGenFunction {
54public:
55  CodeGenModule &CGM;  // Per-module state.
56  TargetInfo &Target;
57
58  typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
59  llvm::IRBuilder<> Builder;
60
61  // Holds the Decl for the current function or method
62  const Decl *CurFuncDecl;
63  QualType FnRetTy;
64  llvm::Function *CurFn;
65
66  /// AllocaInsertPoint - This is an instruction in the entry block before which
67  /// we prefer to insert allocas.
68  llvm::Instruction *AllocaInsertPt;
69
70  const llvm::Type *LLVMIntTy;
71  uint32_t LLVMPointerWidth;
72
73private:
74  /// LabelIDs - Track arbitrary ids assigned to labels for use in
75  /// implementing the GCC address-of-label extension and indirect
76  /// goto. IDs are assigned to labels inside getIDForAddrOfLabel().
77  std::map<const LabelStmt*, unsigned> LabelIDs;
78
79  /// IndirectSwitches - Record the list of switches for indirect
80  /// gotos. Emission of the actual switching code needs to be delayed
81  /// until all AddrLabelExprs have been seen.
82  std::vector<llvm::SwitchInst*> IndirectSwitches;
83
84  /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
85  /// decls.
86  llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
87
88  /// LabelMap - This keeps track of the LLVM basic block for each C label.
89  llvm::DenseMap<const LabelStmt*, llvm::BasicBlock*> LabelMap;
90
91  // BreakContinueStack - This keeps track of where break and continue
92  // statements should jump to.
93  struct BreakContinue {
94    BreakContinue(llvm::BasicBlock *bb, llvm::BasicBlock *cb)
95      : BreakBlock(bb), ContinueBlock(cb) {}
96
97    llvm::BasicBlock *BreakBlock;
98    llvm::BasicBlock *ContinueBlock;
99  };
100  llvm::SmallVector<BreakContinue, 8> BreakContinueStack;
101
102  /// SwitchInsn - This is nearest current switch instruction. It is null if
103  /// if current context is not in a switch.
104  llvm::SwitchInst *SwitchInsn;
105
106  /// CaseRangeBlock - This block holds if condition check for last case
107  /// statement range in current switch instruction.
108  llvm::BasicBlock *CaseRangeBlock;
109
110public:
111  CodeGenFunction(CodeGenModule &cgm);
112
113  ASTContext &getContext() const;
114
115  void GenerateObjCMethod(const ObjCMethodDecl *OMD);
116
117  void StartObjCMethod(const ObjCMethodDecl *MD);
118
119  /// GenerateObjCGetter - Synthesize an Objective-C property getter
120  /// function.
121  void GenerateObjCGetter(const ObjCPropertyImplDecl *PID);
122
123  /// GenerateObjCSetter - Synthesize an Objective-C property setter
124  /// function for the given property.
125  void GenerateObjCSetter(const ObjCPropertyImplDecl *PID);
126
127  void GenerateCode(const FunctionDecl *FD,
128                    llvm::Function *Fn);
129  void FinishFunction(SourceLocation EndLoc=SourceLocation());
130
131  const llvm::Type *ConvertType(QualType T);
132
133  /// LoadObjCSelf - Load the value of self. This function is only
134  /// valid while generating code for an Objective-C method.
135  llvm::Value *LoadObjCSelf();
136
137  /// isObjCPointerType - Return true if the specificed AST type will map onto
138  /// some Objective-C pointer type.
139  static bool isObjCPointerType(QualType T);
140
141  /// hasAggregateLLVMType - Return true if the specified AST type will map into
142  /// an aggregate LLVM type or is void.
143  static bool hasAggregateLLVMType(QualType T);
144
145  /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
146  /// label maps to.
147  llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S);
148
149
150  void EmitBlock(llvm::BasicBlock *BB);
151
152  /// ErrorUnsupported - Print out an error that codegen doesn't support the
153  /// specified stmt yet.
154  void ErrorUnsupported(const Stmt *S, const char *Type);
155
156  //===--------------------------------------------------------------------===//
157  //                                  Helpers
158  //===--------------------------------------------------------------------===//
159
160  /// CreateTempAlloca - This creates a alloca and inserts it into the entry
161  /// block.
162  llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
163                                     const char *Name = "tmp");
164
165  /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
166  /// expression and compare the result against zero, returning an Int1Ty value.
167  llvm::Value *EvaluateExprAsBool(const Expr *E);
168
169  /// EmitAnyExpr - Emit code to compute the specified expression which can have
170  /// any type.  The result is returned as an RValue struct.  If this is an
171  /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
172  /// the result should be returned.
173  RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0,
174                     bool isAggLocVolatile = false);
175
176  /// isDummyBlock - Return true if BB is an empty basic block
177  /// with no predecessors.
178  static bool isDummyBlock(const llvm::BasicBlock *BB);
179
180  /// StartBlock - Start new block named N. If insert block is a dummy block
181  /// then reuse it.
182  void StartBlock(const char *N);
183
184  /// getCGRecordLayout - Return record layout info.
185  const CGRecordLayout *getCGRecordLayout(CodeGenTypes &CGT, QualType RTy);
186
187  /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
188  llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD);
189
190  /// getAccessedFieldNo - Given an encoded value and a result number, return
191  /// the input field number being accessed.
192  static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
193
194  unsigned GetIDForAddrOfLabel(const LabelStmt *L);
195
196  //===--------------------------------------------------------------------===//
197  //                            Declaration Emission
198  //===--------------------------------------------------------------------===//
199
200  void EmitDecl(const Decl &D);
201  void EmitEnumConstantDecl(const EnumConstantDecl &D);
202  void EmitBlockVarDecl(const VarDecl &D);
203  void EmitLocalBlockVarDecl(const VarDecl &D);
204  void EmitStaticBlockVarDecl(const VarDecl &D);
205
206  /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
207  void EmitParmDecl(const VarDecl &D, llvm::Value *Arg);
208
209  //===--------------------------------------------------------------------===//
210  //                             Statement Emission
211  //===--------------------------------------------------------------------===//
212
213  void EmitStmt(const Stmt *S);
214  RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
215                          llvm::Value *AggLoc = 0, bool isAggVol = false);
216  void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt.
217  void EmitLabelStmt(const LabelStmt &S);
218  void EmitGotoStmt(const GotoStmt &S);
219  void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
220  void EmitIfStmt(const IfStmt &S);
221  void EmitWhileStmt(const WhileStmt &S);
222  void EmitDoStmt(const DoStmt &S);
223  void EmitForStmt(const ForStmt &S);
224  void EmitReturnStmt(const ReturnStmt &S);
225  void EmitDeclStmt(const DeclStmt &S);
226  void EmitBreakStmt();
227  void EmitContinueStmt();
228  void EmitSwitchStmt(const SwitchStmt &S);
229  void EmitDefaultStmt(const DefaultStmt &S);
230  void EmitCaseStmt(const CaseStmt &S);
231  void EmitCaseStmtRange(const CaseStmt &S);
232  void EmitAsmStmt(const AsmStmt &S);
233
234  //===--------------------------------------------------------------------===//
235  //                         LValue Expression Emission
236  //===--------------------------------------------------------------------===//
237
238  /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E
239  /// and issue an ErrorUnsupported style diagnostic (using the
240  /// provided Name).
241  LValue EmitUnsupportedLValue(const Expr *E,
242                               const char *Name);
243
244  /// EmitLValue - Emit code to compute a designator that specifies the location
245  /// of the expression.
246  ///
247  /// This can return one of two things: a simple address or a bitfield
248  /// reference.  In either case, the LLVM Value* in the LValue structure is
249  /// guaranteed to be an LLVM pointer type.
250  ///
251  /// If this returns a bitfield reference, nothing about the pointee type of
252  /// the LLVM value is known: For example, it may not be a pointer to an
253  /// integer.
254  ///
255  /// If this returns a normal address, and if the lvalue's C type is fixed
256  /// size, this method guarantees that the returned pointer type will point to
257  /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
258  /// variable length type, this is not possible.
259  ///
260  LValue EmitLValue(const Expr *E);
261
262  /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
263  /// this method emits the address of the lvalue, then loads the result as an
264  /// rvalue, returning the rvalue.
265  RValue EmitLoadOfLValue(LValue V, QualType LVType);
266  RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
267  RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
268
269
270  /// EmitStoreThroughLValue - Store the specified rvalue into the specified
271  /// lvalue, where both are guaranteed to the have the same type, and that type
272  /// is 'Ty'.
273  void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
274  void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
275                                                QualType Ty);
276  void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty);
277
278  // Note: only availabe for agg return types
279  LValue EmitCallExprLValue(const CallExpr *E);
280
281  LValue EmitDeclRefLValue(const DeclRefExpr *E);
282  LValue EmitStringLiteralLValue(const StringLiteral *E);
283  LValue EmitPredefinedLValue(const PredefinedExpr *E);
284  LValue EmitUnaryOpLValue(const UnaryOperator *E);
285  LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
286  LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
287  LValue EmitMemberExpr(const MemberExpr *E);
288  LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
289
290  LValue EmitLValueForField(llvm::Value* Base, FieldDecl* Field,
291                            bool isUnion, unsigned CVRQualifiers);
292
293  LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
294  LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
295
296  //===--------------------------------------------------------------------===//
297  //                         Scalar Expression Emission
298  //===--------------------------------------------------------------------===//
299
300  RValue EmitCallExpr(const CallExpr *E);
301
302  RValue EmitCallExpr(Expr *FnExpr, CallExpr::const_arg_iterator ArgBeg,
303                      CallExpr::const_arg_iterator ArgEnd);
304
305  RValue EmitCallExpr(llvm::Value *Callee, QualType FnType,
306                      CallExpr::const_arg_iterator ArgBeg,
307                      CallExpr::const_arg_iterator ArgEnd);
308
309  RValue EmitCallExprExt(llvm::Value *Callee,
310                         QualType ResultType,
311                         CallExpr::const_arg_iterator ArgBeg,
312                         CallExpr::const_arg_iterator ArgEnd,
313                         llvm::Value **ExtraArgs,
314                         unsigned NumExtraArgs);
315
316  RValue EmitBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
317
318  llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
319  llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
320
321  llvm::Value *EmitShuffleVector(llvm::Value* V1, llvm::Value *V2, ...);
322  llvm::Value *EmitVector(llvm::Value * const *Vals, unsigned NumVals,
323                          bool isSplat = false);
324
325  llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
326  llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
327  llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
328  RValue EmitObjCMessageExpr(const ObjCMessageExpr *E);
329  RValue EmitObjCPropertyGet(const ObjCPropertyRefExpr *E);
330
331
332  //===--------------------------------------------------------------------===//
333  //                           Expression Emission
334  //===--------------------------------------------------------------------===//
335
336  // Expressions are broken into three classes: scalar, complex, aggregate.
337
338  /// EmitScalarExpr - Emit the computation of the specified expression of
339  /// LLVM scalar type, returning the result.
340  llvm::Value *EmitScalarExpr(const Expr *E);
341
342  /// EmitScalarConversion - Emit a conversion from the specified type to the
343  /// specified destination type, both of which are LLVM scalar types.
344  llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
345                                    QualType DstTy);
346
347  /// EmitComplexToScalarConversion - Emit a conversion from the specified
348  /// complex type to the specified destination type, where the destination
349  /// type is an LLVM scalar type.
350  llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
351                                             QualType DstTy);
352
353
354  /// EmitAggExpr - Emit the computation of the specified expression of
355  /// aggregate type.  The result is computed into DestPtr.  Note that if
356  /// DestPtr is null, the value of the aggregate expression is not needed.
357  void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest);
358
359  /// EmitComplexExpr - Emit the computation of the specified expression of
360  /// complex type, returning the result.
361  ComplexPairTy EmitComplexExpr(const Expr *E);
362
363  /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
364  /// of complex type, storing into the specified Value*.
365  void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
366                               bool DestIsVolatile);
367  /// LoadComplexFromAddr - Load a complex number from the specified address.
368  ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
369
370  /// GenerateStaticBlockVarDecl - return the the static
371  /// declaration of local variable.
372  llvm::GlobalValue *GenerateStaticBlockVarDecl(const VarDecl &D,
373                                                bool NoInit,
374                                                const char *Separator);
375
376  // GenerateStaticBlockVarDecl - return the static declaration of
377  // a local variable. Performs initialization of the variable if necessary.
378  llvm::GlobalValue *GenerateStaticCXXBlockVarDecl(const VarDecl &D);
379
380  //===--------------------------------------------------------------------===//
381  //                             Internal Helpers
382  //===--------------------------------------------------------------------===//
383
384private:
385  /// EmitIndirectSwitches - Emit code for all of the switch
386  /// instructions in IndirectSwitches.
387  void EmitIndirectSwitches();
388};
389}  // end namespace CodeGen
390}  // end namespace clang
391
392#endif
393