CodeGenFunction.h revision 7f28a9c37e67ae16396042ad9c085830969daf29
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 "clang/Basic/TargetInfo.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
24
25#include <vector>
26#include <map>
27
28#include "CGBlocks.h"
29#include "CGBuilder.h"
30#include "CGCall.h"
31#include "CGValue.h"
32
33namespace llvm {
34  class BasicBlock;
35  class Module;
36  class SwitchInst;
37  class Value;
38}
39
40namespace clang {
41  class ASTContext;
42  class Decl;
43  class EnumConstantDecl;
44  class FunctionDecl;
45  class FunctionProtoType;
46  class LabelStmt;
47  class ObjCContainerDecl;
48  class ObjCInterfaceDecl;
49  class ObjCIvarDecl;
50  class ObjCMethodDecl;
51  class ObjCImplementationDecl;
52  class ObjCPropertyImplDecl;
53  class TargetInfo;
54  class VarDecl;
55
56namespace CodeGen {
57  class CodeGenModule;
58  class CodeGenTypes;
59  class CGDebugInfo;
60  class CGFunctionInfo;
61  class CGRecordLayout;
62
63/// CodeGenFunction - This class organizes the per-function state that is used
64/// while generating LLVM code.
65class CodeGenFunction : public BlockFunction {
66  CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT
67  void operator=(const CodeGenFunction&);  // DO NOT IMPLEMENT
68public:
69  CodeGenModule &CGM;  // Per-module state.
70  TargetInfo &Target;
71
72  typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
73  CGBuilderTy Builder;
74
75  // Holds the Decl for the current function or method
76  const Decl *CurFuncDecl;
77  const CGFunctionInfo *CurFnInfo;
78  QualType FnRetTy;
79  llvm::Function *CurFn;
80
81  /// ReturnBlock - Unified return block.
82  llvm::BasicBlock *ReturnBlock;
83  /// ReturnValue - The temporary alloca to hold the return value. This is null
84  /// iff the function has no return value.
85  llvm::Instruction *ReturnValue;
86
87  /// AllocaInsertPoint - This is an instruction in the entry block before which
88  /// we prefer to insert allocas.
89  llvm::Instruction *AllocaInsertPt;
90
91  const llvm::Type *LLVMIntTy;
92  uint32_t LLVMPointerWidth;
93
94public:
95  /// ObjCEHValueStack - Stack of Objective-C exception values, used for
96  /// rethrows.
97  llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack;
98
99  /// PushCleanupBlock - Push a new cleanup entry on the stack and set the
100  /// passed in block as the cleanup block.
101  void PushCleanupBlock(llvm::BasicBlock *CleanupBlock);
102
103  /// CleanupBlockInfo - A struct representing a popped cleanup block.
104  struct CleanupBlockInfo {
105    /// CleanupBlock - the cleanup block
106    llvm::BasicBlock *CleanupBlock;
107
108    /// SwitchBlock - the block (if any) containing the switch instruction used
109    /// for jumping to the final destination.
110    llvm::BasicBlock *SwitchBlock;
111
112    /// EndBlock - the default destination for the switch instruction.
113    llvm::BasicBlock *EndBlock;
114
115    CleanupBlockInfo(llvm::BasicBlock *cb, llvm::BasicBlock *sb,
116                     llvm::BasicBlock *eb)
117      : CleanupBlock(cb), SwitchBlock(sb), EndBlock(eb) {}
118  };
119
120  /// PopCleanupBlock - Will pop the cleanup entry on the stack, process all
121  /// branch fixups and return a block info struct with the switch block and end
122  /// block.
123  CleanupBlockInfo PopCleanupBlock();
124
125  /// CleanupScope - RAII object that will create a cleanup block and set the
126  /// insert point to that block. When destructed, it sets the insert point to
127  /// the previous block and pushes a new cleanup entry on the stack.
128  class CleanupScope {
129    CodeGenFunction& CGF;
130    llvm::BasicBlock *CurBB;
131    llvm::BasicBlock *CleanupBB;
132
133  public:
134    CleanupScope(CodeGenFunction &cgf)
135      : CGF(cgf), CurBB(CGF.Builder.GetInsertBlock()) {
136      CleanupBB = CGF.createBasicBlock("cleanup");
137      CGF.Builder.SetInsertPoint(CleanupBB);
138    }
139
140    ~CleanupScope() {
141      CGF.PushCleanupBlock(CleanupBB);
142      CGF.Builder.SetInsertPoint(CurBB);
143    }
144  };
145
146  /// EmitCleanupBlocks - Takes the old cleanup stack size and emits the cleanup
147  /// blocks that have been added.
148  void EmitCleanupBlocks(size_t OldCleanupStackSize);
149
150  /// EmitBranchThroughCleanup - Emit a branch from the current insert block
151  /// through the cleanup handling code (if any) and then on to \arg Dest.
152  ///
153  /// FIXME: Maybe this should really be in EmitBranch? Don't we always want
154  /// this behavior for branches?
155  void EmitBranchThroughCleanup(llvm::BasicBlock *Dest);
156
157private:
158  CGDebugInfo* DebugInfo;
159
160  /// LabelIDs - Track arbitrary ids assigned to labels for use in implementing
161  /// the GCC address-of-label extension and indirect goto. IDs are assigned to
162  /// labels inside getIDForAddrOfLabel().
163  std::map<const LabelStmt*, unsigned> LabelIDs;
164
165  /// IndirectSwitches - Record the list of switches for indirect
166  /// gotos. Emission of the actual switching code needs to be delayed until all
167  /// AddrLabelExprs have been seen.
168  std::vector<llvm::SwitchInst*> IndirectSwitches;
169
170  /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
171  /// decls.
172  llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
173
174  /// LabelMap - This keeps track of the LLVM basic block for each C label.
175  llvm::DenseMap<const LabelStmt*, llvm::BasicBlock*> LabelMap;
176
177  // BreakContinueStack - This keeps track of where break and continue
178  // statements should jump to.
179  struct BreakContinue {
180    BreakContinue(llvm::BasicBlock *bb, llvm::BasicBlock *cb)
181      : BreakBlock(bb), ContinueBlock(cb) {}
182
183    llvm::BasicBlock *BreakBlock;
184    llvm::BasicBlock *ContinueBlock;
185  };
186  llvm::SmallVector<BreakContinue, 8> BreakContinueStack;
187
188  /// SwitchInsn - This is nearest current switch instruction. It is null if if
189  /// current context is not in a switch.
190  llvm::SwitchInst *SwitchInsn;
191
192  /// CaseRangeBlock - This block holds if condition check for last case
193  /// statement range in current switch instruction.
194  llvm::BasicBlock *CaseRangeBlock;
195
196  /// InvokeDest - This is the nearest exception target for calls
197  /// which can unwind, when exceptions are being used.
198  llvm::BasicBlock *InvokeDest;
199
200  // VLASizeMap - This keeps track of the associated size for each VLA type.
201  // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
202  // enter/leave scopes.
203  llvm::DenseMap<const VariableArrayType*, llvm::Value*> VLASizeMap;
204
205  /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
206  /// calling llvm.stacksave for multiple VLAs in the same scope.
207  bool DidCallStackSave;
208
209  struct CleanupEntry {
210    /// CleanupBlock - The block of code that does the actual cleanup.
211    llvm::BasicBlock *CleanupBlock;
212
213    /// Blocks - Basic blocks that were emitted in the current cleanup scope.
214    std::vector<llvm::BasicBlock *> Blocks;
215
216    /// BranchFixups - Branch instructions to basic blocks that haven't been
217    /// inserted into the current function yet.
218    std::vector<llvm::BranchInst *> BranchFixups;
219
220    explicit CleanupEntry(llvm::BasicBlock *cb)
221      : CleanupBlock(cb) {}
222
223    ~CleanupEntry() {
224      assert(Blocks.empty() && "Did not empty blocks!");
225      assert(BranchFixups.empty() && "Did not empty branch fixups!");
226    }
227  };
228
229  /// CleanupEntries - Stack of cleanup entries.
230  llvm::SmallVector<CleanupEntry, 8> CleanupEntries;
231
232  typedef llvm::DenseMap<llvm::BasicBlock*, size_t> BlockScopeMap;
233
234  /// BlockScopes - Map of which "cleanup scope" scope basic blocks have.
235  BlockScopeMap BlockScopes;
236
237public:
238  CodeGenFunction(CodeGenModule &cgm);
239
240  ASTContext &getContext() const;
241  CGDebugInfo *getDebugInfo() { return DebugInfo; }
242
243  llvm::BasicBlock *getInvokeDest() { return InvokeDest; }
244  void setInvokeDest(llvm::BasicBlock *B) { InvokeDest = B; }
245
246  //===--------------------------------------------------------------------===//
247  //                                  Objective-C
248  //===--------------------------------------------------------------------===//
249
250  void GenerateObjCMethod(const ObjCMethodDecl *OMD);
251
252  void StartObjCMethod(const ObjCMethodDecl *MD,
253                       const ObjCContainerDecl *CD);
254
255  /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
256  void GenerateObjCGetter(ObjCImplementationDecl *IMP,
257                          const ObjCPropertyImplDecl *PID);
258
259  /// GenerateObjCSetter - Synthesize an Objective-C property setter function
260  /// for the given property.
261  void GenerateObjCSetter(ObjCImplementationDecl *IMP,
262                          const ObjCPropertyImplDecl *PID);
263
264  //===--------------------------------------------------------------------===//
265  //                                  Block Bits
266  //===--------------------------------------------------------------------===//
267
268  llvm::Value *BuildBlockLiteralTmp(const BlockExpr *);
269  llvm::Constant *BuildDescriptorBlockDecl(uint64_t Size,
270                                           const llvm::StructType *,
271                                           std::vector<HelperInfo> *);
272
273  llvm::Function *GenerateBlockFunction(const BlockExpr *BExpr,
274                                        const BlockInfo& Info,
275                                  llvm::DenseMap<const Decl*, llvm::Value*> ldm,
276                                        uint64_t &Size, uint64_t &Align,
277                      llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
278                                        bool &subBlockHasCopyDispose);
279
280  llvm::Value *LoadBlockStruct();
281
282  llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E);
283
284  const llvm::Type *BuildByRefType(QualType Ty, uint64_t Align);
285
286  void GenerateCode(const FunctionDecl *FD,
287                    llvm::Function *Fn);
288  void StartFunction(const Decl *D, QualType RetTy,
289                     llvm::Function *Fn,
290                     const FunctionArgList &Args,
291                     SourceLocation StartLoc);
292
293  /// EmitReturnBlock - Emit the unified return block, trying to avoid its
294  /// emission when possible.
295  void EmitReturnBlock();
296
297  /// FinishFunction - Complete IR generation of the current function. It is
298  /// legal to call this function even if there is no current insertion point.
299  void FinishFunction(SourceLocation EndLoc=SourceLocation());
300
301  /// EmitFunctionProlog - Emit the target specific LLVM code to load the
302  /// arguments for the given function. This is also responsible for naming the
303  /// LLVM function arguments.
304  void EmitFunctionProlog(const CGFunctionInfo &FI,
305                          llvm::Function *Fn,
306                          const FunctionArgList &Args);
307
308  /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
309  /// given temporary.
310  void EmitFunctionEpilog(const CGFunctionInfo &FI, llvm::Value *ReturnValue);
311
312  const llvm::Type *ConvertTypeForMem(QualType T);
313  const llvm::Type *ConvertType(QualType T);
314
315  /// LoadObjCSelf - Load the value of self. This function is only valid while
316  /// generating code for an Objective-C method.
317  llvm::Value *LoadObjCSelf();
318
319  /// TypeOfSelfObject - Return type of object that this self represents.
320  QualType TypeOfSelfObject();
321
322  /// hasAggregateLLVMType - Return true if the specified AST type will map into
323  /// an aggregate LLVM type or is void.
324  static bool hasAggregateLLVMType(QualType T);
325
326  /// createBasicBlock - Create an LLVM basic block.
327  llvm::BasicBlock *createBasicBlock(const char *Name="",
328                                     llvm::Function *Parent=0,
329                                     llvm::BasicBlock *InsertBefore=0) {
330#ifdef NDEBUG
331    return llvm::BasicBlock::Create("", Parent, InsertBefore);
332#else
333    return llvm::BasicBlock::Create(Name, Parent, InsertBefore);
334#endif
335  }
336
337  /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
338  /// label maps to.
339  llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S);
340
341  /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
342  /// adding a fall-through branch from the current insert block if
343  /// necessary. It is legal to call this function even if there is no current
344  /// insertion point.
345  ///
346  /// IsFinished - If true, indicates that the caller has finished emitting
347  /// branches to the given block and does not expect to emit code into it. This
348  /// means the block can be ignored if it is unreachable.
349  void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
350
351  /// EmitBranch - Emit a branch to the specified basic block from the current
352  /// insert block, taking care to avoid creation of branches from dummy
353  /// blocks. It is legal to call this function even if there is no current
354  /// insertion point.
355  ///
356  /// This function clears the current insertion point. The caller should follow
357  /// calls to this function with calls to Emit*Block prior to generation new
358  /// code.
359  void EmitBranch(llvm::BasicBlock *Block);
360
361  /// HaveInsertPoint - True if an insertion point is defined. If not, this
362  /// indicates that the current code being emitted is unreachable.
363  bool HaveInsertPoint() const {
364    return Builder.GetInsertBlock() != 0;
365  }
366
367  /// EnsureInsertPoint - Ensure that an insertion point is defined so that
368  /// emitted IR has a place to go. Note that by definition, if this function
369  /// creates a block then that block is unreachable; callers may do better to
370  /// detect when no insertion point is defined and simply skip IR generation.
371  void EnsureInsertPoint() {
372    if (!HaveInsertPoint())
373      EmitBlock(createBasicBlock());
374  }
375
376  /// ErrorUnsupported - Print out an error that codegen doesn't support the
377  /// specified stmt yet.
378  void ErrorUnsupported(const Stmt *S, const char *Type,
379                        bool OmitOnError=false);
380
381  //===--------------------------------------------------------------------===//
382  //                                  Helpers
383  //===--------------------------------------------------------------------===//
384
385  /// CreateTempAlloca - This creates a alloca and inserts it into the entry
386  /// block.
387  llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
388                                     const char *Name = "tmp");
389
390  /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
391  /// expression and compare the result against zero, returning an Int1Ty value.
392  llvm::Value *EvaluateExprAsBool(const Expr *E);
393
394  /// EmitAnyExpr - Emit code to compute the specified expression which can have
395  /// any type.  The result is returned as an RValue struct.  If this is an
396  /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
397  /// the result should be returned.
398  RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0,
399                     bool isAggLocVolatile = false);
400
401  // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
402  // or the value of the expression, depending on how va_list is defined.
403  llvm::Value *EmitVAListRef(const Expr *E);
404
405  /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
406  /// always be accessible even if no aggregate location is provided.
407  RValue EmitAnyExprToTemp(const Expr *E, llvm::Value *AggLoc = 0,
408                           bool isAggLocVolatile = false);
409
410  void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
411                         QualType EltTy);
412
413  void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty);
414
415  /// StartBlock - Start new block named N. If insert block is a dummy block
416  /// then reuse it.
417  void StartBlock(const char *N);
418
419  /// getCGRecordLayout - Return record layout info.
420  const CGRecordLayout *getCGRecordLayout(CodeGenTypes &CGT, QualType RTy);
421
422  /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
423  llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD);
424
425  /// GetAddrOfLocalVar - Return the address of a local variable.
426  llvm::Value *GetAddrOfLocalVar(const VarDecl *VD);
427
428  /// getAccessedFieldNo - Given an encoded value and a result number, return
429  /// the input field number being accessed.
430  static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
431
432  unsigned GetIDForAddrOfLabel(const LabelStmt *L);
433
434  /// EmitMemSetToZero - Generate code to memset a value of the given type to 0.
435  void EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty);
436
437  // EmitVAArg - Generate code to get an argument from the passed in pointer
438  // and update it accordingly. The return value is a pointer to the argument.
439  // FIXME: We should be able to get rid of this method and use the va_arg
440  // instruction in LLVM instead once it works well enough.
441  llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
442
443  // EmitVLASize - Generate code for any VLA size expressions that might occur
444  // in a variably modified type. If Ty is a VLA, will return the value that
445  // corresponds to the size in bytes of the VLA type. Will return 0 otherwise.
446  llvm::Value *EmitVLASize(QualType Ty);
447
448  // GetVLASize - Returns an LLVM value that corresponds to the size in bytes
449  // of a variable length array type.
450  llvm::Value *GetVLASize(const VariableArrayType *);
451
452  //===--------------------------------------------------------------------===//
453  //                            Declaration Emission
454  //===--------------------------------------------------------------------===//
455
456  void EmitDecl(const Decl &D);
457  void EmitBlockVarDecl(const VarDecl &D);
458  void EmitLocalBlockVarDecl(const VarDecl &D);
459  void EmitStaticBlockVarDecl(const VarDecl &D);
460
461  /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
462  void EmitParmDecl(const VarDecl &D, llvm::Value *Arg);
463
464  //===--------------------------------------------------------------------===//
465  //                             Statement Emission
466  //===--------------------------------------------------------------------===//
467
468  /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
469  void EmitStopPoint(const Stmt *S);
470
471  /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
472  /// this function even if there is no current insertion point.
473  ///
474  /// This function may clear the current insertion point; callers should use
475  /// EnsureInsertPoint if they wish to subsequently generate code without first
476  /// calling EmitBlock, EmitBranch, or EmitStmt.
477  void EmitStmt(const Stmt *S);
478
479  /// EmitSimpleStmt - Try to emit a "simple" statement which does not
480  /// necessarily require an insertion point or debug information; typically
481  /// because the statement amounts to a jump or a container of other
482  /// statements.
483  ///
484  /// \return True if the statement was handled.
485  bool EmitSimpleStmt(const Stmt *S);
486
487  RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
488                          llvm::Value *AggLoc = 0, bool isAggVol = false);
489
490  /// EmitLabel - Emit the block for the given label. It is legal to call this
491  /// function even if there is no current insertion point.
492  void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt.
493
494  void EmitLabelStmt(const LabelStmt &S);
495  void EmitGotoStmt(const GotoStmt &S);
496  void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
497  void EmitIfStmt(const IfStmt &S);
498  void EmitWhileStmt(const WhileStmt &S);
499  void EmitDoStmt(const DoStmt &S);
500  void EmitForStmt(const ForStmt &S);
501  void EmitReturnStmt(const ReturnStmt &S);
502  void EmitDeclStmt(const DeclStmt &S);
503  void EmitBreakStmt(const BreakStmt &S);
504  void EmitContinueStmt(const ContinueStmt &S);
505  void EmitSwitchStmt(const SwitchStmt &S);
506  void EmitDefaultStmt(const DefaultStmt &S);
507  void EmitCaseStmt(const CaseStmt &S);
508  void EmitCaseStmtRange(const CaseStmt &S);
509  void EmitAsmStmt(const AsmStmt &S);
510
511  void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
512  void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
513  void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
514  void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
515
516  //===--------------------------------------------------------------------===//
517  //                         LValue Expression Emission
518  //===--------------------------------------------------------------------===//
519
520  /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
521  RValue GetUndefRValue(QualType Ty);
522
523  /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
524  /// and issue an ErrorUnsupported style diagnostic (using the
525  /// provided Name).
526  RValue EmitUnsupportedRValue(const Expr *E,
527                               const char *Name);
528
529  /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
530  /// an ErrorUnsupported style diagnostic (using the provided Name).
531  LValue EmitUnsupportedLValue(const Expr *E,
532                               const char *Name);
533
534  /// EmitLValue - Emit code to compute a designator that specifies the location
535  /// of the expression.
536  ///
537  /// This can return one of two things: a simple address or a bitfield
538  /// reference.  In either case, the LLVM Value* in the LValue structure is
539  /// guaranteed to be an LLVM pointer type.
540  ///
541  /// If this returns a bitfield reference, nothing about the pointee type of
542  /// the LLVM value is known: For example, it may not be a pointer to an
543  /// integer.
544  ///
545  /// If this returns a normal address, and if the lvalue's C type is fixed
546  /// size, this method guarantees that the returned pointer type will point to
547  /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
548  /// variable length type, this is not possible.
549  ///
550  LValue EmitLValue(const Expr *E);
551
552  /// EmitLoadOfScalar - Load a scalar value from an address, taking
553  /// care to appropriately convert from the memory representation to
554  /// the LLVM value representation.
555  llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
556                                QualType Ty);
557
558  /// EmitStoreOfScalar - Store a scalar value to an address, taking
559  /// care to appropriately convert from the memory representation to
560  /// the LLVM value representation.
561  void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
562                         bool Volatile);
563
564  /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
565  /// this method emits the address of the lvalue, then loads the result as an
566  /// rvalue, returning the rvalue.
567  RValue EmitLoadOfLValue(LValue V, QualType LVType);
568  RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
569  RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
570  RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType);
571  RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType);
572
573
574  /// EmitStoreThroughLValue - Store the specified rvalue into the specified
575  /// lvalue, where both are guaranteed to the have the same type, and that type
576  /// is 'Ty'.
577  void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
578  void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
579                                                QualType Ty);
580  void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty);
581  void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty);
582
583  /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
584  /// EmitStoreThroughLValue.
585  ///
586  /// \param Result [out] - If non-null, this will be set to a Value* for the
587  /// bit-field contents after the store, appropriate for use as the result of
588  /// an assignment to the bit-field.
589  void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty,
590                                      llvm::Value **Result=0);
591
592  // Note: only availabe for agg return types
593  LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
594  // Note: only available for agg return types
595  LValue EmitCallExprLValue(const CallExpr *E);
596  // Note: only available for agg return types
597  LValue EmitVAArgExprLValue(const VAArgExpr *E);
598  LValue EmitDeclRefLValue(const DeclRefExpr *E);
599  LValue EmitStringLiteralLValue(const StringLiteral *E);
600  LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
601  LValue EmitPredefinedFunctionName(unsigned Type);
602  LValue EmitPredefinedLValue(const PredefinedExpr *E);
603  LValue EmitUnaryOpLValue(const UnaryOperator *E);
604  LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
605  LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
606  LValue EmitMemberExpr(const MemberExpr *E);
607  LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
608
609  llvm::Value *EmitIvarOffset(ObjCInterfaceDecl *Interface,
610                              const ObjCIvarDecl *Ivar);
611  LValue EmitLValueForField(llvm::Value* Base, FieldDecl* Field,
612                            bool isUnion, unsigned CVRQualifiers);
613  LValue EmitLValueForIvar(QualType ObjectTy,
614                           llvm::Value* Base, const ObjCIvarDecl *Ivar,
615                           const FieldDecl *Field,
616                           unsigned CVRQualifiers);
617
618  LValue EmitLValueForBitfield(llvm::Value* Base, FieldDecl* Field,
619                                unsigned CVRQualifiers);
620
621  LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
622
623  LValue EmitCXXConditionDeclLValue(const CXXConditionDeclExpr *E);
624
625  LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
626  LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
627  LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
628  LValue EmitObjCKVCRefLValue(const ObjCKVCRefExpr *E);
629  LValue EmitObjCSuperExpr(const ObjCSuperExpr *E);
630
631  //===--------------------------------------------------------------------===//
632  //                         Scalar Expression Emission
633  //===--------------------------------------------------------------------===//
634
635  /// EmitCall - Generate a call of the given function, expecting the given
636  /// result type, and using the given argument list which specifies both the
637  /// LLVM arguments and the types they were derived from.
638  ///
639  /// \param TargetDecl - If given, the decl of the function in a
640  /// direct call; used to set attributes on the call (noreturn,
641  /// etc.).
642  RValue EmitCall(const CGFunctionInfo &FnInfo,
643                  llvm::Value *Callee,
644                  const CallArgList &Args,
645                  const Decl *TargetDecl = 0);
646
647  RValue EmitCallExpr(const CallExpr *E);
648
649  RValue EmitCallExpr(llvm::Value *Callee, QualType FnType,
650                      CallExpr::const_arg_iterator ArgBeg,
651                      CallExpr::const_arg_iterator ArgEnd,
652                      const Decl *TargetDecl = 0);
653
654  RValue EmitBuiltinExpr(const FunctionDecl *FD,
655                         unsigned BuiltinID, const CallExpr *E);
656
657  RValue EmitBlockCallExpr(const CallExpr *E);
658
659  /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
660  /// is unhandled by the current target.
661  llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
662
663  llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
664  llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
665
666  llvm::Value *EmitShuffleVector(llvm::Value* V1, llvm::Value *V2, ...);
667  llvm::Value *EmitVector(llvm::Value * const *Vals, unsigned NumVals,
668                          bool isSplat = false);
669
670  llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
671  llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
672  llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
673  RValue EmitObjCMessageExpr(const ObjCMessageExpr *E);
674  RValue EmitObjCPropertyGet(const Expr *E);
675  void EmitObjCPropertySet(const Expr *E, RValue Src);
676
677
678  //===--------------------------------------------------------------------===//
679  //                           Expression Emission
680  //===--------------------------------------------------------------------===//
681
682  // Expressions are broken into three classes: scalar, complex, aggregate.
683
684  /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
685  /// scalar type, returning the result.
686  llvm::Value *EmitScalarExpr(const Expr *E);
687
688  /// EmitScalarConversion - Emit a conversion from the specified type to the
689  /// specified destination type, both of which are LLVM scalar types.
690  llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
691                                    QualType DstTy);
692
693  /// EmitComplexToScalarConversion - Emit a conversion from the specified
694  /// complex type to the specified destination type, where the destination type
695  /// is an LLVM scalar type.
696  llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
697                                             QualType DstTy);
698
699
700  /// EmitAggExpr - Emit the computation of the specified expression of
701  /// aggregate type.  The result is computed into DestPtr.  Note that if
702  /// DestPtr is null, the value of the aggregate expression is not needed.
703  void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest);
704
705  /// EmitComplexExpr - Emit the computation of the specified expression of
706  /// complex type, returning the result.
707  ComplexPairTy EmitComplexExpr(const Expr *E);
708
709  /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
710  /// of complex type, storing into the specified Value*.
711  void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
712                               bool DestIsVolatile);
713
714  /// StoreComplexToAddr - Store a complex number into the specified address.
715  void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
716                          bool DestIsVolatile);
717  /// LoadComplexFromAddr - Load a complex number from the specified address.
718  ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
719
720  /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global
721  /// for a static block var decl.
722  llvm::GlobalVariable * CreateStaticBlockVarDecl(const VarDecl &D,
723                                                  const char *Separator,
724                                                  llvm::GlobalValue::LinkageTypes
725                                                  Linkage);
726
727  /// GenerateStaticCXXBlockVarDecl - Create the initializer for a C++
728  /// runtime initialized static block var decl.
729  void GenerateStaticCXXBlockVarDeclInit(const VarDecl &D,
730                                         llvm::GlobalVariable *GV);
731
732  //===--------------------------------------------------------------------===//
733  //                             Internal Helpers
734  //===--------------------------------------------------------------------===//
735
736  /// ContainsLabel - Return true if the statement contains a label in it.  If
737  /// this statement is not executed normally, it not containing a label means
738  /// that we can just remove the code.
739  static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
740
741  /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
742  /// to a constant, or if it does but contains a label, return 0.  If it
743  /// constant folds to 'true' and does not contain a label, return 1, if it
744  /// constant folds to 'false' and does not contain a label, return -1.
745  int ConstantFoldsToSimpleInteger(const Expr *Cond);
746
747  /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
748  /// if statement) to the specified blocks.  Based on the condition, this might
749  /// try to simplify the codegen of the conditional based on the branch.
750  void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
751                            llvm::BasicBlock *FalseBlock);
752private:
753
754  /// EmitIndirectSwitches - Emit code for all of the switch
755  /// instructions in IndirectSwitches.
756  void EmitIndirectSwitches();
757
758  void EmitReturnOfRValue(RValue RV, QualType Ty);
759
760  /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
761  /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
762  ///
763  /// \param AI - The first function argument of the expansion.
764  /// \return The argument following the last expanded function
765  /// argument.
766  llvm::Function::arg_iterator
767  ExpandTypeFromArgs(QualType Ty, LValue Dst,
768                     llvm::Function::arg_iterator AI);
769
770  /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
771  /// Ty, into individual arguments on the provided vector \arg Args. See
772  /// ABIArgInfo::Expand.
773  void ExpandTypeToArgs(QualType Ty, RValue Src,
774                        llvm::SmallVector<llvm::Value*, 16> &Args);
775
776  llvm::Value* EmitAsmInput(const AsmStmt &S, TargetInfo::ConstraintInfo Info,
777                            const Expr *InputExpr, std::string &ConstraintStr);
778
779  /// EmitCleanupBlock - emits a single cleanup block.
780  void EmitCleanupBlock();
781
782  /// AddBranchFixup - adds a branch instruction to the list of fixups for the
783  /// current cleanup scope.
784  void AddBranchFixup(llvm::BranchInst *BI);
785
786};
787}  // end namespace CodeGen
788}  // end namespace clang
789
790#endif
791