CodeGenFunction.h revision 2621fd1d6d3c5eadcae246859f62738645df7540
1//===--- CodeGenFunction.h - Per-Function state for LLVM CodeGen ----------===//
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 <vector>
22
23namespace llvm {
24  class Module;
25}
26
27namespace clang {
28  class ASTContext;
29  class Decl;
30  class FunctionDecl;
31  class ObjCMethodDecl;
32  class TargetInfo;
33  class FunctionTypeProto;
34
35  class Stmt;
36  class CompoundStmt;
37  class LabelStmt;
38  class GotoStmt;
39  class IfStmt;
40  class WhileStmt;
41  class DoStmt;
42  class ForStmt;
43  class ReturnStmt;
44  class DeclStmt;
45  class CaseStmt;
46  class DefaultStmt;
47  class SwitchStmt;
48  class AsmStmt;
49
50  class Expr;
51  class DeclRefExpr;
52  class StringLiteral;
53  class IntegerLiteral;
54  class FloatingLiteral;
55  class CharacterLiteral;
56  class TypesCompatibleExpr;
57
58  class ImplicitCastExpr;
59  class CastExpr;
60  class CallExpr;
61  class UnaryOperator;
62  class BinaryOperator;
63  class CompoundAssignOperator;
64  class ArraySubscriptExpr;
65  class ExtVectorElementExpr;
66  class ConditionalOperator;
67  class ChooseExpr;
68  class PreDefinedExpr;
69  class ObjCStringLiteral;
70  class ObjCIvarRefExpr;
71  class MemberExpr;
72
73  class VarDecl;
74  class EnumConstantDecl;
75  class ParmVarDecl;
76  class FieldDecl;
77namespace CodeGen {
78  class CodeGenModule;
79  class CodeGenTypes;
80  class CGRecordLayout;
81
82/// RValue - This trivial value class is used to represent the result of an
83/// expression that is evaluated.  It can be one of three things: either a
84/// simple LLVM SSA value, a pair of SSA values for complex numbers, or the
85/// address of an aggregate value in memory.
86class RValue {
87  llvm::Value *V1, *V2;
88  // TODO: Encode this into the low bit of pointer for more efficient
89  // return-by-value.
90  enum { Scalar, Complex, Aggregate } Flavor;
91
92  // FIXME: Aggregate rvalues need to retain information about whether they are
93  // volatile or not.
94public:
95
96  bool isScalar() const { return Flavor == Scalar; }
97  bool isComplex() const { return Flavor == Complex; }
98  bool isAggregate() const { return Flavor == Aggregate; }
99
100  /// getScalar() - Return the Value* of this scalar value.
101  llvm::Value *getScalarVal() const {
102    assert(isScalar() && "Not a scalar!");
103    return V1;
104  }
105
106  /// getComplexVal - Return the real/imag components of this complex value.
107  ///
108  std::pair<llvm::Value *, llvm::Value *> getComplexVal() const {
109    return std::pair<llvm::Value *, llvm::Value *>(V1, V2);
110  }
111
112  /// getAggregateAddr() - Return the Value* of the address of the aggregate.
113  llvm::Value *getAggregateAddr() const {
114    assert(isAggregate() && "Not an aggregate!");
115    return V1;
116  }
117
118  static RValue get(llvm::Value *V) {
119    RValue ER;
120    ER.V1 = V;
121    ER.Flavor = Scalar;
122    return ER;
123  }
124  static RValue getComplex(llvm::Value *V1, llvm::Value *V2) {
125    RValue ER;
126    ER.V1 = V1;
127    ER.V2 = V2;
128    ER.Flavor = Complex;
129    return ER;
130  }
131  static RValue getComplex(const std::pair<llvm::Value *, llvm::Value *> &C) {
132    RValue ER;
133    ER.V1 = C.first;
134    ER.V2 = C.second;
135    ER.Flavor = Complex;
136    return ER;
137  }
138  static RValue getAggregate(llvm::Value *V) {
139    RValue ER;
140    ER.V1 = V;
141    ER.Flavor = Aggregate;
142    return ER;
143  }
144};
145
146
147/// LValue - This represents an lvalue references.  Because C/C++ allow
148/// bitfields, this is not a simple LLVM pointer, it may be a pointer plus a
149/// bitrange.
150class LValue {
151  // FIXME: Volatility.  Restrict?
152  // alignment?
153
154  enum {
155    Simple,       // This is a normal l-value, use getAddress().
156    VectorElt,    // This is a vector element l-value (V[i]), use getVector*
157    BitField,     // This is a bitfield l-value, use getBitfield*.
158    ExtVectorElt  // This is an extended vector subset, use getExtVectorComp
159  } LVType;
160
161  llvm::Value *V;
162
163  union {
164    llvm::Value *VectorIdx;   // Index into a vector subscript: V[i]
165    unsigned VectorElts;      // Encoded ExtVector element subset: V.xyx
166    struct {
167      unsigned short StartBit;
168      unsigned short Size;
169      bool IsSigned;
170    } BitfieldData;           // BitField start bit and size
171  };
172public:
173  bool isSimple() const { return LVType == Simple; }
174  bool isVectorElt() const { return LVType == VectorElt; }
175  bool isBitfield() const { return LVType == BitField; }
176  bool isExtVectorElt() const { return LVType == ExtVectorElt; }
177
178  // simple lvalue
179  llvm::Value *getAddress() const { assert(isSimple()); return V; }
180  // vector elt lvalue
181  llvm::Value *getVectorAddr() const { assert(isVectorElt()); return V; }
182  llvm::Value *getVectorIdx() const { assert(isVectorElt()); return VectorIdx; }
183  // extended vector elements.
184  llvm::Value *getExtVectorAddr() const { assert(isExtVectorElt()); return V; }
185  unsigned getExtVectorElts() const {
186    assert(isExtVectorElt());
187    return VectorElts;
188  }
189  // bitfield lvalue
190  llvm::Value *getBitfieldAddr() const { assert(isBitfield()); return V; }
191  unsigned short getBitfieldStartBit() const {
192    assert(isBitfield());
193    return BitfieldData.StartBit;
194  }
195  unsigned short getBitfieldSize() const {
196    assert(isBitfield());
197    return BitfieldData.Size;
198  }
199  bool isBitfieldSigned() const {
200    assert(isBitfield());
201    return BitfieldData.IsSigned;
202  }
203
204  static LValue MakeAddr(llvm::Value *V) {
205    LValue R;
206    R.LVType = Simple;
207    R.V = V;
208    return R;
209  }
210
211  static LValue MakeVectorElt(llvm::Value *Vec, llvm::Value *Idx) {
212    LValue R;
213    R.LVType = VectorElt;
214    R.V = Vec;
215    R.VectorIdx = Idx;
216    return R;
217  }
218
219  static LValue MakeExtVectorElt(llvm::Value *Vec, unsigned Elements) {
220    LValue R;
221    R.LVType = ExtVectorElt;
222    R.V = Vec;
223    R.VectorElts = Elements;
224    return R;
225  }
226
227  static LValue MakeBitfield(llvm::Value *V, unsigned short StartBit,
228                             unsigned short Size, bool IsSigned) {
229    LValue R;
230    R.LVType = BitField;
231    R.V = V;
232    R.BitfieldData.StartBit = StartBit;
233    R.BitfieldData.Size = Size;
234    R.BitfieldData.IsSigned = IsSigned;
235    return R;
236  }
237};
238
239/// CodeGenFunction - This class organizes the per-function state that is used
240/// while generating LLVM code.
241class CodeGenFunction {
242public:
243  CodeGenModule &CGM;  // Per-module state.
244  TargetInfo &Target;
245
246  typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
247  llvm::IRBuilder Builder;
248
249  // Holds the Decl for the current function or method
250  const Decl *CurFuncDecl;
251  QualType FnRetTy;
252  llvm::Function *CurFn;
253
254  /// AllocaInsertPoint - This is an instruction in the entry block before which
255  /// we prefer to insert allocas.
256  llvm::Instruction *AllocaInsertPt;
257
258  const llvm::Type *LLVMIntTy;
259  uint32_t LLVMPointerWidth;
260
261private:
262  /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
263  /// decls.
264  llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
265
266  /// LabelMap - This keeps track of the LLVM basic block for each C label.
267  llvm::DenseMap<const LabelStmt*, llvm::BasicBlock*> LabelMap;
268
269  // BreakContinueStack - This keeps track of where break and continue
270  // statements should jump to.
271  struct BreakContinue {
272    BreakContinue(llvm::BasicBlock *bb, llvm::BasicBlock *cb)
273      : BreakBlock(bb), ContinueBlock(cb) {}
274
275    llvm::BasicBlock *BreakBlock;
276    llvm::BasicBlock *ContinueBlock;
277  };
278  llvm::SmallVector<BreakContinue, 8> BreakContinueStack;
279
280  /// SwitchInsn - This is nearest current switch instruction. It is null if
281  /// if current context is not in a switch.
282  llvm::SwitchInst *SwitchInsn;
283
284  /// CaseRangeBlock - This block holds if condition check for last case
285  /// statement range in current switch instruction.
286  llvm::BasicBlock *CaseRangeBlock;
287
288public:
289  CodeGenFunction(CodeGenModule &cgm);
290
291  ASTContext &getContext() const;
292
293  void GenerateObjCMethod(const ObjCMethodDecl *OMD);
294  void GenerateCode(const FunctionDecl *FD);
295
296  const llvm::Type *ConvertType(QualType T);
297
298  llvm::Value *LoadObjCSelf();
299
300  /// hasAggregateLLVMType - Return true if the specified AST type will map into
301  /// an aggregate LLVM type or is void.
302  static bool hasAggregateLLVMType(QualType T);
303
304  /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
305  /// label maps to.
306  llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S);
307
308
309  void EmitBlock(llvm::BasicBlock *BB);
310
311  /// WarnUnsupported - Print out a warning that codegen doesn't support the
312  /// specified stmt yet.
313  void WarnUnsupported(const Stmt *S, const char *Type);
314
315  //===--------------------------------------------------------------------===//
316  //                                  Helpers
317  //===--------------------------------------------------------------------===//
318
319  /// CreateTempAlloca - This creates a alloca and inserts it into the entry
320  /// block.
321  llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
322                                     const char *Name = "tmp");
323
324  /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
325  /// expression and compare the result against zero, returning an Int1Ty value.
326  llvm::Value *EvaluateExprAsBool(const Expr *E);
327
328  /// EmitAnyExpr - Emit code to compute the specified expression which can have
329  /// any type.  The result is returned as an RValue struct.  If this is an
330  /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
331  /// the result should be returned.
332  RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0,
333                     bool isAggLocVolatile = false);
334
335  /// isDummyBlock - Return true if BB is an empty basic block
336  /// with no predecessors.
337  static bool isDummyBlock(const llvm::BasicBlock *BB);
338
339  /// StartBlock - Start new block named N. If insert block is a dummy block
340  /// then reuse it.
341  void StartBlock(const char *N);
342
343  /// getCGRecordLayout - Return record layout info.
344  const CGRecordLayout *getCGRecordLayout(CodeGenTypes &CGT, QualType RTy);
345
346  /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
347  llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD);
348  //===--------------------------------------------------------------------===//
349  //                            Declaration Emission
350  //===--------------------------------------------------------------------===//
351
352  void EmitDecl(const Decl &D);
353  void EmitEnumConstantDecl(const EnumConstantDecl &D);
354  void EmitBlockVarDecl(const VarDecl &D);
355  void EmitLocalBlockVarDecl(const VarDecl &D);
356  void EmitStaticBlockVarDecl(const VarDecl &D);
357  void EmitParmDecl(const ParmVarDecl &D, llvm::Value *Arg);
358
359  //===--------------------------------------------------------------------===//
360  //                             Statement Emission
361  //===--------------------------------------------------------------------===//
362
363  void EmitStmt(const Stmt *S);
364  RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
365                          llvm::Value *AggLoc = 0, bool isAggVol = false);
366  void EmitLabelStmt(const LabelStmt &S);
367  void EmitGotoStmt(const GotoStmt &S);
368  void EmitIfStmt(const IfStmt &S);
369  void EmitWhileStmt(const WhileStmt &S);
370  void EmitDoStmt(const DoStmt &S);
371  void EmitForStmt(const ForStmt &S);
372  void EmitReturnStmt(const ReturnStmt &S);
373  void EmitDeclStmt(const DeclStmt &S);
374  void EmitBreakStmt();
375  void EmitContinueStmt();
376  void EmitSwitchStmt(const SwitchStmt &S);
377  void EmitDefaultStmt(const DefaultStmt &S);
378  void EmitCaseStmt(const CaseStmt &S);
379  void EmitCaseStmtRange(const CaseStmt &S);
380  void EmitAsmStmt(const AsmStmt &S);
381
382  //===--------------------------------------------------------------------===//
383  //                         LValue Expression Emission
384  //===--------------------------------------------------------------------===//
385
386  /// EmitLValue - Emit code to compute a designator that specifies the location
387  /// of the expression.
388  ///
389  /// This can return one of two things: a simple address or a bitfield
390  /// reference.  In either case, the LLVM Value* in the LValue structure is
391  /// guaranteed to be an LLVM pointer type.
392  ///
393  /// If this returns a bitfield reference, nothing about the pointee type of
394  /// the LLVM value is known: For example, it may not be a pointer to an
395  /// integer.
396  ///
397  /// If this returns a normal address, and if the lvalue's C type is fixed
398  /// size, this method guarantees that the returned pointer type will point to
399  /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
400  /// variable length type, this is not possible.
401  ///
402  LValue EmitLValue(const Expr *E);
403
404  /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
405  /// this method emits the address of the lvalue, then loads the result as an
406  /// rvalue, returning the rvalue.
407  RValue EmitLoadOfLValue(LValue V, QualType LVType);
408  RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
409  RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
410
411
412  /// EmitStoreThroughLValue - Store the specified rvalue into the specified
413  /// lvalue, where both are guaranteed to the have the same type, and that type
414  /// is 'Ty'.
415  void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
416  void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
417                                                QualType Ty);
418  void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty);
419
420  // Note: only availabe for agg return types
421  LValue EmitCallExprLValue(const CallExpr *E);
422
423  LValue EmitDeclRefLValue(const DeclRefExpr *E);
424  LValue EmitStringLiteralLValue(const StringLiteral *E);
425  LValue EmitPreDefinedLValue(const PreDefinedExpr *E);
426  LValue EmitUnaryOpLValue(const UnaryOperator *E);
427  LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
428  LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
429  LValue EmitMemberExpr(const MemberExpr *E);
430
431  LValue EmitLValueForField(llvm::Value* Base, FieldDecl* Field,
432                            bool isUnion);
433
434  LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
435  //===--------------------------------------------------------------------===//
436  //                         Scalar Expression Emission
437  //===--------------------------------------------------------------------===//
438
439  RValue EmitCallExpr(const CallExpr *E);
440  RValue EmitCallExpr(Expr *FnExpr, Expr *const *Args, unsigned NumArgs);
441  RValue EmitCallExpr(llvm::Value *Callee, QualType FnType,
442                      Expr *const *Args, unsigned NumArgs);
443  RValue EmitBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
444
445  llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
446  llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
447
448  llvm::Value *EmitShuffleVector(llvm::Value* V1, llvm::Value *V2, ...);
449  llvm::Value *EmitVector(llvm::Value * const *Vals, unsigned NumVals,
450                          bool isSplat = false);
451
452  llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
453
454  //===--------------------------------------------------------------------===//
455  //                           Expression Emission
456  //===--------------------------------------------------------------------===//
457
458  // Expressions are broken into three classes: scalar, complex, aggregate.
459
460  /// EmitScalarExpr - Emit the computation of the specified expression of
461  /// LLVM scalar type, returning the result.
462  llvm::Value *EmitScalarExpr(const Expr *E);
463
464  /// EmitScalarConversion - Emit a conversion from the specified type to the
465  /// specified destination type, both of which are LLVM scalar types.
466  llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
467                                    QualType DstTy);
468
469  /// EmitComplexToScalarConversion - Emit a conversion from the specified
470  /// complex type to the specified destination type, where the destination
471  /// type is an LLVM scalar type.
472  llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
473                                             QualType DstTy);
474
475
476  /// EmitAggExpr - Emit the computation of the specified expression of
477  /// aggregate type.  The result is computed into DestPtr.  Note that if
478  /// DestPtr is null, the value of the aggregate expression is not needed.
479  void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest);
480
481  /// EmitComplexExpr - Emit the computation of the specified expression of
482  /// complex type, returning the result.
483  ComplexPairTy EmitComplexExpr(const Expr *E);
484
485  /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
486  /// of complex type, storing into the specified Value*.
487  void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
488                               bool DestIsVolatile);
489  /// LoadComplexFromAddr - Load a complex number from the specified address.
490  ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
491
492  /// GenerateStaticBlockVarDecl - return the the static
493  /// declaration of local variable.
494  llvm::GlobalValue *GenerateStaticBlockVarDecl(const VarDecl &D,
495                                                bool NoInit,
496                                                const char *Separator);
497};
498}  // end namespace CodeGen
499}  // end namespace clang
500
501#endif
502