CodeGenFunction.h revision dd5c98f709837e5dd3da08d44d1ce407975df2cf
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 "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/Basic/TargetInfo.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/Support/ValueHandle.h"
25#include "CodeGenModule.h"
26#include "CGBlocks.h"
27#include "CGBuilder.h"
28#include "CGCall.h"
29#include "CGCXX.h"
30#include "CGValue.h"
31
32namespace llvm {
33  class BasicBlock;
34  class LLVMContext;
35  class MDNode;
36  class Module;
37  class SwitchInst;
38  class Twine;
39  class Value;
40}
41
42namespace clang {
43  class ASTContext;
44  class CXXDestructorDecl;
45  class CXXTryStmt;
46  class Decl;
47  class EnumConstantDecl;
48  class FunctionDecl;
49  class FunctionProtoType;
50  class LabelStmt;
51  class ObjCContainerDecl;
52  class ObjCInterfaceDecl;
53  class ObjCIvarDecl;
54  class ObjCMethodDecl;
55  class ObjCImplementationDecl;
56  class ObjCPropertyImplDecl;
57  class TargetInfo;
58  class TargetCodeGenInfo;
59  class VarDecl;
60  class ObjCForCollectionStmt;
61  class ObjCAtTryStmt;
62  class ObjCAtThrowStmt;
63  class ObjCAtSynchronizedStmt;
64
65namespace CodeGen {
66  class CodeGenTypes;
67  class CGDebugInfo;
68  class CGFunctionInfo;
69  class CGRecordLayout;
70
71/// CodeGenFunction - This class organizes the per-function state that is used
72/// while generating LLVM code.
73class CodeGenFunction : public BlockFunction {
74  CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT
75  void operator=(const CodeGenFunction&);  // DO NOT IMPLEMENT
76public:
77  CodeGenModule &CGM;  // Per-module state.
78  const TargetInfo &Target;
79
80  typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
81  CGBuilderTy Builder;
82
83  /// CurFuncDecl - Holds the Decl for the current function or ObjC method.
84  /// This excludes BlockDecls.
85  const Decl *CurFuncDecl;
86  /// CurCodeDecl - This is the inner-most code context, which includes blocks.
87  const Decl *CurCodeDecl;
88  const CGFunctionInfo *CurFnInfo;
89  QualType FnRetTy;
90  llvm::Function *CurFn;
91
92  /// CurGD - The GlobalDecl for the current function being compiled.
93  GlobalDecl CurGD;
94
95  /// ReturnBlock - Unified return block.
96  llvm::BasicBlock *ReturnBlock;
97  /// ReturnValue - The temporary alloca to hold the return value. This is null
98  /// iff the function has no return value.
99  llvm::Value *ReturnValue;
100
101  /// AllocaInsertPoint - This is an instruction in the entry block before which
102  /// we prefer to insert allocas.
103  llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
104
105  const llvm::Type *LLVMIntTy;
106  uint32_t LLVMPointerWidth;
107
108  bool Exceptions;
109  bool CatchUndefined;
110public:
111  /// ObjCEHValueStack - Stack of Objective-C exception values, used for
112  /// rethrows.
113  llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack;
114
115  /// PushCleanupBlock - Push a new cleanup entry on the stack and set the
116  /// passed in block as the cleanup block.
117  void PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
118                        llvm::BasicBlock *CleanupExitBlock,
119                        llvm::BasicBlock *PreviousInvokeDest,
120                        bool EHOnly = false);
121  void PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock) {
122    PushCleanupBlock(CleanupEntryBlock, 0, getInvokeDest(), false);
123  }
124
125  /// CleanupBlockInfo - A struct representing a popped cleanup block.
126  struct CleanupBlockInfo {
127    /// CleanupEntryBlock - the cleanup entry block
128    llvm::BasicBlock *CleanupBlock;
129
130    /// SwitchBlock - the block (if any) containing the switch instruction used
131    /// for jumping to the final destination.
132    llvm::BasicBlock *SwitchBlock;
133
134    /// EndBlock - the default destination for the switch instruction.
135    llvm::BasicBlock *EndBlock;
136
137    /// EHOnly - True iff this cleanup should only be performed on the
138    /// exceptional edge.
139    bool EHOnly;
140
141    CleanupBlockInfo(llvm::BasicBlock *cb, llvm::BasicBlock *sb,
142                     llvm::BasicBlock *eb, bool ehonly = false)
143      : CleanupBlock(cb), SwitchBlock(sb), EndBlock(eb), EHOnly(ehonly) {}
144  };
145
146  /// EHCleanupBlock - RAII object that will create a cleanup block for the
147  /// exceptional edge and set the insert point to that block.  When destroyed,
148  /// it creates the cleanup edge and sets the insert point to the previous
149  /// block.
150  class EHCleanupBlock {
151    CodeGenFunction& CGF;
152    llvm::BasicBlock *PreviousInsertionBlock;
153    llvm::BasicBlock *CleanupHandler;
154    llvm::BasicBlock *PreviousInvokeDest;
155  public:
156    EHCleanupBlock(CodeGenFunction &cgf)
157      : CGF(cgf),
158        PreviousInsertionBlock(CGF.Builder.GetInsertBlock()),
159        CleanupHandler(CGF.createBasicBlock("ehcleanup", CGF.CurFn)),
160        PreviousInvokeDest(CGF.getInvokeDest()) {
161      llvm::BasicBlock *TerminateHandler = CGF.getTerminateHandler();
162      CGF.Builder.SetInsertPoint(CleanupHandler);
163      CGF.setInvokeDest(TerminateHandler);
164    }
165    ~EHCleanupBlock();
166  };
167
168  /// PopCleanupBlock - Will pop the cleanup entry on the stack, process all
169  /// branch fixups and return a block info struct with the switch block and end
170  /// block.  This will also reset the invoke handler to the previous value
171  /// from when the cleanup block was created.
172  CleanupBlockInfo PopCleanupBlock();
173
174  /// DelayedCleanupBlock - RAII object that will create a cleanup block and set
175  /// the insert point to that block. When destructed, it sets the insert point
176  /// to the previous block and pushes a new cleanup entry on the stack.
177  class DelayedCleanupBlock {
178    CodeGenFunction& CGF;
179    llvm::BasicBlock *CurBB;
180    llvm::BasicBlock *CleanupEntryBB;
181    llvm::BasicBlock *CleanupExitBB;
182    llvm::BasicBlock *CurInvokeDest;
183    bool EHOnly;
184
185  public:
186    DelayedCleanupBlock(CodeGenFunction &cgf, bool ehonly = false)
187      : CGF(cgf), CurBB(CGF.Builder.GetInsertBlock()),
188        CleanupEntryBB(CGF.createBasicBlock("cleanup")),
189        CleanupExitBB(0),
190        CurInvokeDest(CGF.getInvokeDest()),
191        EHOnly(ehonly) {
192      CGF.Builder.SetInsertPoint(CleanupEntryBB);
193    }
194
195    llvm::BasicBlock *getCleanupExitBlock() {
196      if (!CleanupExitBB)
197        CleanupExitBB = CGF.createBasicBlock("cleanup.exit");
198      return CleanupExitBB;
199    }
200
201    ~DelayedCleanupBlock() {
202      CGF.PushCleanupBlock(CleanupEntryBB, CleanupExitBB, CurInvokeDest,
203                           EHOnly);
204      // FIXME: This is silly, move this into the builder.
205      if (CurBB)
206        CGF.Builder.SetInsertPoint(CurBB);
207      else
208        CGF.Builder.ClearInsertionPoint();
209    }
210  };
211
212  /// \brief Enters a new scope for capturing cleanups, all of which will be
213  /// executed once the scope is exited.
214  class CleanupScope {
215    CodeGenFunction& CGF;
216    size_t CleanupStackDepth;
217    bool OldDidCallStackSave;
218    bool PerformCleanup;
219
220    CleanupScope(const CleanupScope &); // DO NOT IMPLEMENT
221    CleanupScope &operator=(const CleanupScope &); // DO NOT IMPLEMENT
222
223  public:
224    /// \brief Enter a new cleanup scope.
225    explicit CleanupScope(CodeGenFunction &CGF)
226      : CGF(CGF), PerformCleanup(true)
227    {
228      CleanupStackDepth = CGF.CleanupEntries.size();
229      OldDidCallStackSave = CGF.DidCallStackSave;
230    }
231
232    /// \brief Exit this cleanup scope, emitting any accumulated
233    /// cleanups.
234    ~CleanupScope() {
235      if (PerformCleanup) {
236        CGF.DidCallStackSave = OldDidCallStackSave;
237        CGF.EmitCleanupBlocks(CleanupStackDepth);
238      }
239    }
240
241    /// \brief Determine whether this scope requires any cleanups.
242    bool requiresCleanups() const {
243      return CGF.CleanupEntries.size() > CleanupStackDepth;
244    }
245
246    /// \brief Force the emission of cleanups now, instead of waiting
247    /// until this object is destroyed.
248    void ForceCleanup() {
249      assert(PerformCleanup && "Already forced cleanup");
250      CGF.DidCallStackSave = OldDidCallStackSave;
251      CGF.EmitCleanupBlocks(CleanupStackDepth);
252      PerformCleanup = false;
253    }
254  };
255
256  /// CXXTemporariesCleanupScope - Enters a new scope for catching live
257  /// temporaries, all of which will be popped once the scope is exited.
258  class CXXTemporariesCleanupScope {
259    CodeGenFunction &CGF;
260    size_t NumLiveTemporaries;
261
262    // DO NOT IMPLEMENT
263    CXXTemporariesCleanupScope(const CXXTemporariesCleanupScope &);
264    CXXTemporariesCleanupScope &operator=(const CXXTemporariesCleanupScope &);
265
266  public:
267    explicit CXXTemporariesCleanupScope(CodeGenFunction &CGF)
268      : CGF(CGF), NumLiveTemporaries(CGF.LiveTemporaries.size()) { }
269
270    ~CXXTemporariesCleanupScope() {
271      while (CGF.LiveTemporaries.size() > NumLiveTemporaries)
272        CGF.PopCXXTemporary();
273    }
274  };
275
276
277  /// EmitCleanupBlocks - Takes the old cleanup stack size and emits the cleanup
278  /// blocks that have been added.
279  void EmitCleanupBlocks(size_t OldCleanupStackSize);
280
281  /// EmitBranchThroughCleanup - Emit a branch from the current insert block
282  /// through the cleanup handling code (if any) and then on to \arg Dest.
283  ///
284  /// FIXME: Maybe this should really be in EmitBranch? Don't we always want
285  /// this behavior for branches?
286  void EmitBranchThroughCleanup(llvm::BasicBlock *Dest);
287
288  /// BeginConditionalBranch - Should be called before a conditional part of an
289  /// expression is emitted. For example, before the RHS of the expression below
290  /// is emitted:
291  ///
292  /// b && f(T());
293  ///
294  /// This is used to make sure that any temporaries created in the conditional
295  /// branch are only destroyed if the branch is taken.
296  void BeginConditionalBranch() {
297    ++ConditionalBranchLevel;
298  }
299
300  /// EndConditionalBranch - Should be called after a conditional part of an
301  /// expression has been emitted.
302  void EndConditionalBranch() {
303    assert(ConditionalBranchLevel != 0 &&
304           "Conditional branch mismatch!");
305
306    --ConditionalBranchLevel;
307  }
308
309private:
310  CGDebugInfo *DebugInfo;
311
312  /// IndirectBranch - The first time an indirect goto is seen we create a block
313  /// with an indirect branch.  Every time we see the address of a label taken,
314  /// we add the label to the indirect goto.  Every subsequent indirect goto is
315  /// codegen'd as a jump to the IndirectBranch's basic block.
316  llvm::IndirectBrInst *IndirectBranch;
317
318  /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
319  /// decls.
320  llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
321
322  /// LabelMap - This keeps track of the LLVM basic block for each C label.
323  llvm::DenseMap<const LabelStmt*, llvm::BasicBlock*> LabelMap;
324
325  // BreakContinueStack - This keeps track of where break and continue
326  // statements should jump to.
327  struct BreakContinue {
328    BreakContinue(llvm::BasicBlock *bb, llvm::BasicBlock *cb)
329      : BreakBlock(bb), ContinueBlock(cb) {}
330
331    llvm::BasicBlock *BreakBlock;
332    llvm::BasicBlock *ContinueBlock;
333  };
334  llvm::SmallVector<BreakContinue, 8> BreakContinueStack;
335
336  /// SwitchInsn - This is nearest current switch instruction. It is null if if
337  /// current context is not in a switch.
338  llvm::SwitchInst *SwitchInsn;
339
340  /// CaseRangeBlock - This block holds if condition check for last case
341  /// statement range in current switch instruction.
342  llvm::BasicBlock *CaseRangeBlock;
343
344  /// InvokeDest - This is the nearest exception target for calls
345  /// which can unwind, when exceptions are being used.
346  llvm::BasicBlock *InvokeDest;
347
348  // VLASizeMap - This keeps track of the associated size for each VLA type.
349  // We track this by the size expression rather than the type itself because
350  // in certain situations, like a const qualifier applied to an VLA typedef,
351  // multiple VLA types can share the same size expression.
352  // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
353  // enter/leave scopes.
354  llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
355
356  /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
357  /// calling llvm.stacksave for multiple VLAs in the same scope.
358  bool DidCallStackSave;
359
360  struct CleanupEntry {
361    /// CleanupEntryBlock - The block of code that does the actual cleanup.
362    llvm::BasicBlock *CleanupEntryBlock;
363
364    /// CleanupExitBlock - The cleanup exit block.
365    llvm::BasicBlock *CleanupExitBlock;
366
367    /// Blocks - Basic blocks that were emitted in the current cleanup scope.
368    std::vector<llvm::BasicBlock *> Blocks;
369
370    /// BranchFixups - Branch instructions to basic blocks that haven't been
371    /// inserted into the current function yet.
372    std::vector<llvm::BranchInst *> BranchFixups;
373
374    /// PreviousInvokeDest - The invoke handler from the start of the cleanup
375    /// region.
376    llvm::BasicBlock *PreviousInvokeDest;
377
378    /// EHOnly - Perform this only on the exceptional edge, not the main edge.
379    bool EHOnly;
380
381    explicit CleanupEntry(llvm::BasicBlock *CleanupEntryBlock,
382                          llvm::BasicBlock *CleanupExitBlock,
383                          llvm::BasicBlock *PreviousInvokeDest,
384                          bool ehonly)
385      : CleanupEntryBlock(CleanupEntryBlock),
386        CleanupExitBlock(CleanupExitBlock),
387        PreviousInvokeDest(PreviousInvokeDest),
388        EHOnly(ehonly) {}
389  };
390
391  /// CleanupEntries - Stack of cleanup entries.
392  llvm::SmallVector<CleanupEntry, 8> CleanupEntries;
393
394  typedef llvm::DenseMap<llvm::BasicBlock*, size_t> BlockScopeMap;
395
396  /// BlockScopes - Map of which "cleanup scope" scope basic blocks have.
397  BlockScopeMap BlockScopes;
398
399  /// CXXThisDecl - When generating code for a C++ member function,
400  /// this will hold the implicit 'this' declaration.
401  ImplicitParamDecl *CXXThisDecl;
402  llvm::Value *CXXThisValue;
403
404  /// CXXVTTDecl - When generating code for a base object constructor or
405  /// base object destructor with virtual bases, this will hold the implicit
406  /// VTT parameter.
407  ImplicitParamDecl *CXXVTTDecl;
408  llvm::Value *CXXVTTValue;
409
410  /// CXXLiveTemporaryInfo - Holds information about a live C++ temporary.
411  struct CXXLiveTemporaryInfo {
412    /// Temporary - The live temporary.
413    const CXXTemporary *Temporary;
414
415    /// ThisPtr - The pointer to the temporary.
416    llvm::Value *ThisPtr;
417
418    /// DtorBlock - The destructor block.
419    llvm::BasicBlock *DtorBlock;
420
421    /// CondPtr - If this is a conditional temporary, this is the pointer to the
422    /// condition variable that states whether the destructor should be called
423    /// or not.
424    llvm::Value *CondPtr;
425
426    CXXLiveTemporaryInfo(const CXXTemporary *temporary,
427                         llvm::Value *thisptr, llvm::BasicBlock *dtorblock,
428                         llvm::Value *condptr)
429      : Temporary(temporary), ThisPtr(thisptr), DtorBlock(dtorblock),
430      CondPtr(condptr) { }
431  };
432
433  llvm::SmallVector<CXXLiveTemporaryInfo, 4> LiveTemporaries;
434
435  /// ConditionalBranchLevel - Contains the nesting level of the current
436  /// conditional branch. This is used so that we know if a temporary should be
437  /// destroyed conditionally.
438  unsigned ConditionalBranchLevel;
439
440
441  /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
442  /// type as well as the field number that contains the actual data.
443  llvm::DenseMap<const ValueDecl *, std::pair<const llvm::Type *,
444                                              unsigned> > ByRefValueInfo;
445
446  /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
447  /// number that holds the value.
448  unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
449
450  llvm::BasicBlock *TerminateHandler;
451  llvm::BasicBlock *TrapBB;
452
453  int UniqueAggrDestructorCount;
454public:
455  CodeGenFunction(CodeGenModule &cgm);
456
457  ASTContext &getContext() const;
458  CGDebugInfo *getDebugInfo() { return DebugInfo; }
459
460  llvm::BasicBlock *getInvokeDest() { return InvokeDest; }
461  void setInvokeDest(llvm::BasicBlock *B) { InvokeDest = B; }
462
463  llvm::LLVMContext &getLLVMContext() { return VMContext; }
464
465  //===--------------------------------------------------------------------===//
466  //                                  Objective-C
467  //===--------------------------------------------------------------------===//
468
469  void GenerateObjCMethod(const ObjCMethodDecl *OMD);
470
471  void StartObjCMethod(const ObjCMethodDecl *MD,
472                       const ObjCContainerDecl *CD);
473
474  /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
475  void GenerateObjCGetter(ObjCImplementationDecl *IMP,
476                          const ObjCPropertyImplDecl *PID);
477  void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
478                                  ObjCMethodDecl *MD, bool ctor);
479
480  /// GenerateObjCSetter - Synthesize an Objective-C property setter function
481  /// for the given property.
482  void GenerateObjCSetter(ObjCImplementationDecl *IMP,
483                          const ObjCPropertyImplDecl *PID);
484  bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
485  bool IvarTypeWithAggrGCObjects(QualType Ty);
486
487  //===--------------------------------------------------------------------===//
488  //                                  Block Bits
489  //===--------------------------------------------------------------------===//
490
491  llvm::Value *BuildBlockLiteralTmp(const BlockExpr *);
492  llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
493                                           bool BlockHasCopyDispose,
494                                           CharUnits Size,
495                                           const llvm::StructType *,
496                                           std::vector<HelperInfo> *);
497
498  llvm::Function *GenerateBlockFunction(const BlockExpr *BExpr,
499                                        const BlockInfo& Info,
500                                        const Decl *OuterFuncDecl,
501                                  llvm::DenseMap<const Decl*, llvm::Value*> ldm,
502                                        CharUnits &Size, CharUnits &Align,
503                      llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
504                                        bool &subBlockHasCopyDispose);
505
506  void BlockForwardSelf();
507  llvm::Value *LoadBlockStruct();
508
509  CharUnits AllocateBlockDecl(const BlockDeclRefExpr *E);
510  llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E);
511  const llvm::Type *BuildByRefType(const ValueDecl *D);
512
513  void GenerateCode(GlobalDecl GD, llvm::Function *Fn);
514  void StartFunction(GlobalDecl GD, QualType RetTy,
515                     llvm::Function *Fn,
516                     const FunctionArgList &Args,
517                     SourceLocation StartLoc);
518
519  void EmitConstructorBody(FunctionArgList &Args);
520  void EmitDestructorBody(FunctionArgList &Args);
521  void EmitFunctionBody(FunctionArgList &Args);
522
523  /// EmitReturnBlock - Emit the unified return block, trying to avoid its
524  /// emission when possible.
525  void EmitReturnBlock();
526
527  /// FinishFunction - Complete IR generation of the current function. It is
528  /// legal to call this function even if there is no current insertion point.
529  void FinishFunction(SourceLocation EndLoc=SourceLocation());
530
531  /// GenerateThunk - Generate a thunk for the given method.
532  void GenerateThunk(llvm::Function *Fn, GlobalDecl GD, const ThunkInfo &Thunk);
533
534  void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type);
535
536  /// InitializeVTablePointer - Initialize the vtable pointer of the given
537  /// subobject.
538  ///
539  void InitializeVTablePointer(BaseSubobject Base,
540                               const CXXRecordDecl *NearestVBase,
541                               llvm::Constant *VTable,
542                               const CXXRecordDecl *VTableClass);
543
544  typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
545  void InitializeVTablePointers(BaseSubobject Base,
546                                const CXXRecordDecl *NearestVBase,
547                                bool BaseIsNonVirtualPrimaryBase,
548                                llvm::Constant *VTable,
549                                const CXXRecordDecl *VTableClass,
550                                VisitedVirtualBasesSetTy& VBases);
551
552  void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
553
554
555  void SynthesizeCXXCopyConstructor(const FunctionArgList &Args);
556  void SynthesizeCXXCopyAssignment(const FunctionArgList &Args);
557
558  /// EmitDtorEpilogue - Emit all code that comes at the end of class's
559  /// destructor. This is to call destructors on members and base classes in
560  /// reverse order of their construction.
561  void EmitDtorEpilogue(const CXXDestructorDecl *Dtor,
562                        CXXDtorType Type);
563
564  /// EmitFunctionProlog - Emit the target specific LLVM code to load the
565  /// arguments for the given function. This is also responsible for naming the
566  /// LLVM function arguments.
567  void EmitFunctionProlog(const CGFunctionInfo &FI,
568                          llvm::Function *Fn,
569                          const FunctionArgList &Args);
570
571  /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
572  /// given temporary.
573  void EmitFunctionEpilog(const CGFunctionInfo &FI, llvm::Value *ReturnValue);
574
575  /// EmitStartEHSpec - Emit the start of the exception spec.
576  void EmitStartEHSpec(const Decl *D);
577
578  /// EmitEndEHSpec - Emit the end of the exception spec.
579  void EmitEndEHSpec(const Decl *D);
580
581  /// getTerminateHandler - Return a handler that just calls terminate.
582  llvm::BasicBlock *getTerminateHandler();
583
584  const llvm::Type *ConvertTypeForMem(QualType T);
585  const llvm::Type *ConvertType(QualType T);
586  const llvm::Type *ConvertType(const TypeDecl *T) {
587    return ConvertType(getContext().getTypeDeclType(T));
588  }
589
590  /// LoadObjCSelf - Load the value of self. This function is only valid while
591  /// generating code for an Objective-C method.
592  llvm::Value *LoadObjCSelf();
593
594  /// TypeOfSelfObject - Return type of object that this self represents.
595  QualType TypeOfSelfObject();
596
597  /// hasAggregateLLVMType - Return true if the specified AST type will map into
598  /// an aggregate LLVM type or is void.
599  static bool hasAggregateLLVMType(QualType T);
600
601  /// createBasicBlock - Create an LLVM basic block.
602  llvm::BasicBlock *createBasicBlock(const char *Name="",
603                                     llvm::Function *Parent=0,
604                                     llvm::BasicBlock *InsertBefore=0) {
605#ifdef NDEBUG
606    return llvm::BasicBlock::Create(VMContext, "", Parent, InsertBefore);
607#else
608    return llvm::BasicBlock::Create(VMContext, Name, Parent, InsertBefore);
609#endif
610  }
611
612  /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
613  /// label maps to.
614  llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S);
615
616  /// SimplifyForwardingBlocks - If the given basic block is only a branch to
617  /// another basic block, simplify it. This assumes that no other code could
618  /// potentially reference the basic block.
619  void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
620
621  /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
622  /// adding a fall-through branch from the current insert block if
623  /// necessary. It is legal to call this function even if there is no current
624  /// insertion point.
625  ///
626  /// IsFinished - If true, indicates that the caller has finished emitting
627  /// branches to the given block and does not expect to emit code into it. This
628  /// means the block can be ignored if it is unreachable.
629  void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
630
631  /// EmitBranch - Emit a branch to the specified basic block from the current
632  /// insert block, taking care to avoid creation of branches from dummy
633  /// blocks. It is legal to call this function even if there is no current
634  /// insertion point.
635  ///
636  /// This function clears the current insertion point. The caller should follow
637  /// calls to this function with calls to Emit*Block prior to generation new
638  /// code.
639  void EmitBranch(llvm::BasicBlock *Block);
640
641  /// HaveInsertPoint - True if an insertion point is defined. If not, this
642  /// indicates that the current code being emitted is unreachable.
643  bool HaveInsertPoint() const {
644    return Builder.GetInsertBlock() != 0;
645  }
646
647  /// EnsureInsertPoint - Ensure that an insertion point is defined so that
648  /// emitted IR has a place to go. Note that by definition, if this function
649  /// creates a block then that block is unreachable; callers may do better to
650  /// detect when no insertion point is defined and simply skip IR generation.
651  void EnsureInsertPoint() {
652    if (!HaveInsertPoint())
653      EmitBlock(createBasicBlock());
654  }
655
656  /// ErrorUnsupported - Print out an error that codegen doesn't support the
657  /// specified stmt yet.
658  void ErrorUnsupported(const Stmt *S, const char *Type,
659                        bool OmitOnError=false);
660
661  //===--------------------------------------------------------------------===//
662  //                                  Helpers
663  //===--------------------------------------------------------------------===//
664
665  Qualifiers MakeQualifiers(QualType T) {
666    Qualifiers Quals = getContext().getCanonicalType(T).getQualifiers();
667    Quals.setObjCGCAttr(getContext().getObjCGCAttrKind(T));
668    return Quals;
669  }
670
671  /// CreateTempAlloca - This creates a alloca and inserts it into the entry
672  /// block. The caller is responsible for setting an appropriate alignment on
673  /// the alloca.
674  llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
675                                     const llvm::Twine &Name = "tmp");
676
677  /// InitTempAlloca - Provide an initial value for the given alloca.
678  void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
679
680  /// CreateIRTemp - Create a temporary IR object of the given type, with
681  /// appropriate alignment. This routine should only be used when an temporary
682  /// value needs to be stored into an alloca (for example, to avoid explicit
683  /// PHI construction), but the type is the IR type, not the type appropriate
684  /// for storing in memory.
685  llvm::Value *CreateIRTemp(QualType T, const llvm::Twine &Name = "tmp");
686
687  /// CreateMemTemp - Create a temporary memory object of the given type, with
688  /// appropriate alignment.
689  llvm::Value *CreateMemTemp(QualType T, const llvm::Twine &Name = "tmp");
690
691  /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
692  /// expression and compare the result against zero, returning an Int1Ty value.
693  llvm::Value *EvaluateExprAsBool(const Expr *E);
694
695  /// EmitAnyExpr - Emit code to compute the specified expression which can have
696  /// any type.  The result is returned as an RValue struct.  If this is an
697  /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
698  /// the result should be returned.
699  ///
700  /// \param IgnoreResult - True if the resulting value isn't used.
701  RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0,
702                     bool IsAggLocVolatile = false, bool IgnoreResult = false,
703                     bool IsInitializer = false);
704
705  // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
706  // or the value of the expression, depending on how va_list is defined.
707  llvm::Value *EmitVAListRef(const Expr *E);
708
709  /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
710  /// always be accessible even if no aggregate location is provided.
711  RValue EmitAnyExprToTemp(const Expr *E, bool IsAggLocVolatile = false,
712                           bool IsInitializer = false);
713
714  /// EmitsAnyExprToMem - Emits the code necessary to evaluate an
715  /// arbitrary expression into the given memory location.
716  void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
717                        bool IsLocationVolatile = false,
718                        bool IsInitializer = false);
719
720  /// EmitAggregateCopy - Emit an aggrate copy.
721  ///
722  /// \param isVolatile - True iff either the source or the destination is
723  /// volatile.
724  void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
725                         QualType EltTy, bool isVolatile=false);
726
727  void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty);
728
729  /// StartBlock - Start new block named N. If insert block is a dummy block
730  /// then reuse it.
731  void StartBlock(const char *N);
732
733  /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
734  llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD);
735
736  /// GetAddrOfLocalVar - Return the address of a local variable.
737  llvm::Value *GetAddrOfLocalVar(const VarDecl *VD);
738
739  /// getAccessedFieldNo - Given an encoded value and a result number, return
740  /// the input field number being accessed.
741  static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
742
743  llvm::BlockAddress *GetAddrOfLabel(const LabelStmt *L);
744  llvm::BasicBlock *GetIndirectGotoBlock();
745
746  /// EmitMemSetToZero - Generate code to memset a value of the given type to 0.
747  void EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty);
748
749  // EmitVAArg - Generate code to get an argument from the passed in pointer
750  // and update it accordingly. The return value is a pointer to the argument.
751  // FIXME: We should be able to get rid of this method and use the va_arg
752  // instruction in LLVM instead once it works well enough.
753  llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
754
755  /// EmitVLASize - Generate code for any VLA size expressions that might occur
756  /// in a variably modified type. If Ty is a VLA, will return the value that
757  /// corresponds to the size in bytes of the VLA type. Will return 0 otherwise.
758  ///
759  /// This function can be called with a null (unreachable) insert point.
760  llvm::Value *EmitVLASize(QualType Ty);
761
762  // GetVLASize - Returns an LLVM value that corresponds to the size in bytes
763  // of a variable length array type.
764  llvm::Value *GetVLASize(const VariableArrayType *);
765
766  /// LoadCXXThis - Load the value of 'this'. This function is only valid while
767  /// generating code for an C++ member function.
768  llvm::Value *LoadCXXThis() {
769    assert(CXXThisValue && "no 'this' value for this function");
770    return CXXThisValue;
771  }
772
773  /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
774  /// virtual bases.
775  llvm::Value *LoadCXXVTT() {
776    assert(CXXVTTValue && "no VTT value for this function");
777    return CXXVTTValue;
778  }
779
780  /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
781  /// complete class to the given direct base.
782  llvm::Value *
783  GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
784                                        const CXXRecordDecl *Derived,
785                                        const CXXRecordDecl *Base,
786                                        bool BaseIsVirtual);
787
788  llvm::Value *OldGetAddressOfBaseClass(llvm::Value *Value,
789                                        const CXXRecordDecl *ClassDecl,
790                                        const CXXRecordDecl *BaseClassDecl);
791
792  /// GetAddressOfBaseClass - This function will add the necessary delta to the
793  /// load of 'this' and returns address of the base class.
794  llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
795                                     const CXXRecordDecl *Derived,
796                                     const CXXBaseSpecifierArray &BasePath,
797                                     bool NullCheckValue);
798
799  llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
800                                        const CXXRecordDecl *Derived,
801                                        const CXXBaseSpecifierArray &BasePath,
802                                        bool NullCheckValue);
803
804  llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
805                                         const CXXRecordDecl *ClassDecl,
806                                         const CXXRecordDecl *BaseClassDecl);
807
808  void EmitClassAggrMemberwiseCopy(llvm::Value *DestValue,
809                                   llvm::Value *SrcValue,
810                                   const ArrayType *Array,
811                                   const CXXRecordDecl *BaseClassDecl,
812                                   QualType Ty);
813
814  void EmitClassAggrCopyAssignment(llvm::Value *DestValue,
815                                   llvm::Value *SrcValue,
816                                   const ArrayType *Array,
817                                   const CXXRecordDecl *BaseClassDecl,
818                                   QualType Ty);
819
820  void EmitClassMemberwiseCopy(llvm::Value *DestValue, llvm::Value *SrcValue,
821                               const CXXRecordDecl *ClassDecl,
822                               const CXXRecordDecl *BaseClassDecl,
823                               QualType Ty);
824
825  void EmitClassCopyAssignment(llvm::Value *DestValue, llvm::Value *SrcValue,
826                               const CXXRecordDecl *ClassDecl);
827
828  void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
829                                      CXXCtorType CtorType,
830                                      const FunctionArgList &Args);
831  void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
832                              llvm::Value *This,
833                              CallExpr::const_arg_iterator ArgBeg,
834                              CallExpr::const_arg_iterator ArgEnd);
835
836  void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
837                                  const ConstantArrayType *ArrayTy,
838                                  llvm::Value *ArrayPtr,
839                                  CallExpr::const_arg_iterator ArgBeg,
840                                  CallExpr::const_arg_iterator ArgEnd);
841
842  void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
843                                  llvm::Value *NumElements,
844                                  llvm::Value *ArrayPtr,
845                                  CallExpr::const_arg_iterator ArgBeg,
846                                  CallExpr::const_arg_iterator ArgEnd);
847
848  void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
849                                 const ArrayType *Array,
850                                 llvm::Value *This);
851
852  void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
853                                 llvm::Value *NumElements,
854                                 llvm::Value *This);
855
856  llvm::Constant *GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
857                                                const ArrayType *Array,
858                                                llvm::Value *This);
859
860  void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
861                             llvm::Value *This);
862
863  void PushCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr);
864  void PopCXXTemporary();
865
866  llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
867  void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
868
869  void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
870                      QualType DeleteTy);
871
872  llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
873  llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
874
875  void EmitCheck(llvm::Value *, unsigned Size);
876
877  llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
878                                       bool isInc, bool isPre);
879  ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
880                                         bool isInc, bool isPre);
881  //===--------------------------------------------------------------------===//
882  //                            Declaration Emission
883  //===--------------------------------------------------------------------===//
884
885  /// EmitDecl - Emit a declaration.
886  ///
887  /// This function can be called with a null (unreachable) insert point.
888  void EmitDecl(const Decl &D);
889
890  /// EmitBlockVarDecl - Emit a block variable declaration.
891  ///
892  /// This function can be called with a null (unreachable) insert point.
893  void EmitBlockVarDecl(const VarDecl &D);
894
895  /// EmitLocalBlockVarDecl - Emit a local block variable declaration.
896  ///
897  /// This function can be called with a null (unreachable) insert point.
898  void EmitLocalBlockVarDecl(const VarDecl &D);
899
900  void EmitStaticBlockVarDecl(const VarDecl &D,
901                              llvm::GlobalValue::LinkageTypes Linkage);
902
903  /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
904  void EmitParmDecl(const VarDecl &D, llvm::Value *Arg);
905
906  //===--------------------------------------------------------------------===//
907  //                             Statement Emission
908  //===--------------------------------------------------------------------===//
909
910  /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
911  void EmitStopPoint(const Stmt *S);
912
913  /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
914  /// this function even if there is no current insertion point.
915  ///
916  /// This function may clear the current insertion point; callers should use
917  /// EnsureInsertPoint if they wish to subsequently generate code without first
918  /// calling EmitBlock, EmitBranch, or EmitStmt.
919  void EmitStmt(const Stmt *S);
920
921  /// EmitSimpleStmt - Try to emit a "simple" statement which does not
922  /// necessarily require an insertion point or debug information; typically
923  /// because the statement amounts to a jump or a container of other
924  /// statements.
925  ///
926  /// \return True if the statement was handled.
927  bool EmitSimpleStmt(const Stmt *S);
928
929  RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
930                          llvm::Value *AggLoc = 0, bool isAggVol = false);
931
932  /// EmitLabel - Emit the block for the given label. It is legal to call this
933  /// function even if there is no current insertion point.
934  void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt.
935
936  void EmitLabelStmt(const LabelStmt &S);
937  void EmitGotoStmt(const GotoStmt &S);
938  void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
939  void EmitIfStmt(const IfStmt &S);
940  void EmitWhileStmt(const WhileStmt &S);
941  void EmitDoStmt(const DoStmt &S);
942  void EmitForStmt(const ForStmt &S);
943  void EmitReturnStmt(const ReturnStmt &S);
944  void EmitDeclStmt(const DeclStmt &S);
945  void EmitBreakStmt(const BreakStmt &S);
946  void EmitContinueStmt(const ContinueStmt &S);
947  void EmitSwitchStmt(const SwitchStmt &S);
948  void EmitDefaultStmt(const DefaultStmt &S);
949  void EmitCaseStmt(const CaseStmt &S);
950  void EmitCaseStmtRange(const CaseStmt &S);
951  void EmitAsmStmt(const AsmStmt &S);
952
953  void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
954  void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
955  void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
956  void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
957
958  struct CXXTryStmtInfo {
959    llvm::BasicBlock *SavedLandingPad;
960    llvm::BasicBlock *HandlerBlock;
961    llvm::BasicBlock *FinallyBlock;
962  };
963  CXXTryStmtInfo EnterCXXTryStmt(const CXXTryStmt &S);
964  void ExitCXXTryStmt(const CXXTryStmt &S, CXXTryStmtInfo Info);
965
966  void EmitCXXTryStmt(const CXXTryStmt &S);
967
968  //===--------------------------------------------------------------------===//
969  //                         LValue Expression Emission
970  //===--------------------------------------------------------------------===//
971
972  /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
973  RValue GetUndefRValue(QualType Ty);
974
975  /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
976  /// and issue an ErrorUnsupported style diagnostic (using the
977  /// provided Name).
978  RValue EmitUnsupportedRValue(const Expr *E,
979                               const char *Name);
980
981  /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
982  /// an ErrorUnsupported style diagnostic (using the provided Name).
983  LValue EmitUnsupportedLValue(const Expr *E,
984                               const char *Name);
985
986  /// EmitLValue - Emit code to compute a designator that specifies the location
987  /// of the expression.
988  ///
989  /// This can return one of two things: a simple address or a bitfield
990  /// reference.  In either case, the LLVM Value* in the LValue structure is
991  /// guaranteed to be an LLVM pointer type.
992  ///
993  /// If this returns a bitfield reference, nothing about the pointee type of
994  /// the LLVM value is known: For example, it may not be a pointer to an
995  /// integer.
996  ///
997  /// If this returns a normal address, and if the lvalue's C type is fixed
998  /// size, this method guarantees that the returned pointer type will point to
999  /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
1000  /// variable length type, this is not possible.
1001  ///
1002  LValue EmitLValue(const Expr *E);
1003
1004  /// EmitCheckedLValue - Same as EmitLValue but additionally we generate
1005  /// checking code to guard against undefined behavior.  This is only
1006  /// suitable when we know that the address will be used to access the
1007  /// object.
1008  LValue EmitCheckedLValue(const Expr *E);
1009
1010  /// EmitLoadOfScalar - Load a scalar value from an address, taking
1011  /// care to appropriately convert from the memory representation to
1012  /// the LLVM value representation.
1013  llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
1014                                QualType Ty);
1015
1016  /// EmitStoreOfScalar - Store a scalar value to an address, taking
1017  /// care to appropriately convert from the memory representation to
1018  /// the LLVM value representation.
1019  void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
1020                         bool Volatile, QualType Ty);
1021
1022  /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
1023  /// this method emits the address of the lvalue, then loads the result as an
1024  /// rvalue, returning the rvalue.
1025  RValue EmitLoadOfLValue(LValue V, QualType LVType);
1026  RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
1027  RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
1028  RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType);
1029  RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType);
1030
1031
1032  /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1033  /// lvalue, where both are guaranteed to the have the same type, and that type
1034  /// is 'Ty'.
1035  void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
1036  void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
1037                                                QualType Ty);
1038  void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty);
1039  void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty);
1040
1041  /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
1042  /// EmitStoreThroughLValue.
1043  ///
1044  /// \param Result [out] - If non-null, this will be set to a Value* for the
1045  /// bit-field contents after the store, appropriate for use as the result of
1046  /// an assignment to the bit-field.
1047  void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty,
1048                                      llvm::Value **Result=0);
1049
1050  // Note: only availabe for agg return types
1051  LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
1052  LValue EmitCompoundAssignOperatorLValue(const CompoundAssignOperator *E);
1053  // Note: only available for agg return types
1054  LValue EmitCallExprLValue(const CallExpr *E);
1055  // Note: only available for agg return types
1056  LValue EmitVAArgExprLValue(const VAArgExpr *E);
1057  LValue EmitDeclRefLValue(const DeclRefExpr *E);
1058  LValue EmitStringLiteralLValue(const StringLiteral *E);
1059  LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
1060  LValue EmitPredefinedFunctionName(unsigned Type);
1061  LValue EmitPredefinedLValue(const PredefinedExpr *E);
1062  LValue EmitUnaryOpLValue(const UnaryOperator *E);
1063  LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
1064  LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
1065  LValue EmitMemberExpr(const MemberExpr *E);
1066  LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
1067  LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
1068  LValue EmitConditionalOperatorLValue(const ConditionalOperator *E);
1069  LValue EmitCastLValue(const CastExpr *E);
1070  LValue EmitNullInitializationLValue(const CXXZeroInitValueExpr *E);
1071
1072  llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
1073                              const ObjCIvarDecl *Ivar);
1074  LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field,
1075                            unsigned CVRQualifiers);
1076
1077  /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
1078  /// if the Field is a reference, this will return the address of the reference
1079  /// and not the address of the value stored in the reference.
1080  LValue EmitLValueForFieldInitialization(llvm::Value* Base,
1081                                          const FieldDecl* Field,
1082                                          unsigned CVRQualifiers);
1083
1084  LValue EmitLValueForIvar(QualType ObjectTy,
1085                           llvm::Value* Base, const ObjCIvarDecl *Ivar,
1086                           unsigned CVRQualifiers);
1087
1088  LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field,
1089                                unsigned CVRQualifiers);
1090
1091  LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
1092
1093  LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
1094  LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
1095  LValue EmitCXXExprWithTemporariesLValue(const CXXExprWithTemporaries *E);
1096  LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
1097
1098  LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
1099  LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
1100  LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
1101  LValue EmitObjCKVCRefLValue(const ObjCImplicitSetterGetterRefExpr *E);
1102  LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E);
1103  LValue EmitStmtExprLValue(const StmtExpr *E);
1104  LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
1105
1106  //===--------------------------------------------------------------------===//
1107  //                         Scalar Expression Emission
1108  //===--------------------------------------------------------------------===//
1109
1110  /// EmitCall - Generate a call of the given function, expecting the given
1111  /// result type, and using the given argument list which specifies both the
1112  /// LLVM arguments and the types they were derived from.
1113  ///
1114  /// \param TargetDecl - If given, the decl of the function in a direct call;
1115  /// used to set attributes on the call (noreturn, etc.).
1116  RValue EmitCall(const CGFunctionInfo &FnInfo,
1117                  llvm::Value *Callee,
1118                  ReturnValueSlot ReturnValue,
1119                  const CallArgList &Args,
1120                  const Decl *TargetDecl = 0,
1121                  unsigned MDKind = 0,
1122                  llvm::MDNode *Metadata = 0);
1123
1124  RValue EmitCall(QualType FnType, llvm::Value *Callee,
1125                  ReturnValueSlot ReturnValue,
1126                  CallExpr::const_arg_iterator ArgBeg,
1127                  CallExpr::const_arg_iterator ArgEnd,
1128                  const Decl *TargetDecl = 0);
1129  RValue EmitCallExpr(const CallExpr *E,
1130                      ReturnValueSlot ReturnValue = ReturnValueSlot());
1131
1132  llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1133                                const llvm::Type *Ty);
1134  llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1135                                llvm::Value *&This, const llvm::Type *Ty);
1136
1137  RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
1138                           llvm::Value *Callee,
1139                           ReturnValueSlot ReturnValue,
1140                           llvm::Value *This,
1141                           llvm::Value *VTT,
1142                           CallExpr::const_arg_iterator ArgBeg,
1143                           CallExpr::const_arg_iterator ArgEnd);
1144  RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
1145                               ReturnValueSlot ReturnValue);
1146  RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
1147                                      ReturnValueSlot ReturnValue);
1148
1149  RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
1150                                       const CXXMethodDecl *MD,
1151                                       ReturnValueSlot ReturnValue);
1152
1153
1154  RValue EmitBuiltinExpr(const FunctionDecl *FD,
1155                         unsigned BuiltinID, const CallExpr *E);
1156
1157  RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
1158
1159  /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
1160  /// is unhandled by the current target.
1161  llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1162
1163  llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1164  llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1165  llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1166
1167  llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
1168  llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
1169  llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
1170  RValue EmitObjCMessageExpr(const ObjCMessageExpr *E);
1171  RValue EmitObjCPropertyGet(const Expr *E);
1172  RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S);
1173  void EmitObjCPropertySet(const Expr *E, RValue Src);
1174  void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src);
1175
1176
1177  /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
1178  /// expression. Will emit a temporary variable if E is not an LValue.
1179  RValue EmitReferenceBindingToExpr(const Expr* E, bool IsInitializer = false);
1180
1181  //===--------------------------------------------------------------------===//
1182  //                           Expression Emission
1183  //===--------------------------------------------------------------------===//
1184
1185  // Expressions are broken into three classes: scalar, complex, aggregate.
1186
1187  /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
1188  /// scalar type, returning the result.
1189  llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
1190
1191  /// EmitScalarConversion - Emit a conversion from the specified type to the
1192  /// specified destination type, both of which are LLVM scalar types.
1193  llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
1194                                    QualType DstTy);
1195
1196  /// EmitComplexToScalarConversion - Emit a conversion from the specified
1197  /// complex type to the specified destination type, where the destination type
1198  /// is an LLVM scalar type.
1199  llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
1200                                             QualType DstTy);
1201
1202
1203  /// EmitAggExpr - Emit the computation of the specified expression of
1204  /// aggregate type.  The result is computed into DestPtr.  Note that if
1205  /// DestPtr is null, the value of the aggregate expression is not needed.
1206  void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest,
1207                   bool IgnoreResult = false, bool IsInitializer = false,
1208                   bool RequiresGCollection = false);
1209
1210  /// EmitAggExprToLValue - Emit the computation of the specified expression of
1211  /// aggregate type into a temporary LValue.
1212  LValue EmitAggExprToLValue(const Expr *E);
1213
1214  /// EmitGCMemmoveCollectable - Emit special API for structs with object
1215  /// pointers.
1216  void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1217                                QualType Ty);
1218
1219  /// EmitComplexExpr - Emit the computation of the specified expression of
1220  /// complex type, returning the result.
1221  ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false,
1222                                bool IgnoreImag = false,
1223                                bool IgnoreRealAssign = false,
1224                                bool IgnoreImagAssign = false);
1225
1226  /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
1227  /// of complex type, storing into the specified Value*.
1228  void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
1229                               bool DestIsVolatile);
1230
1231  /// StoreComplexToAddr - Store a complex number into the specified address.
1232  void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
1233                          bool DestIsVolatile);
1234  /// LoadComplexFromAddr - Load a complex number from the specified address.
1235  ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
1236
1237  /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global for a
1238  /// static block var decl.
1239  llvm::GlobalVariable *CreateStaticBlockVarDecl(const VarDecl &D,
1240                                                 const char *Separator,
1241                                       llvm::GlobalValue::LinkageTypes Linkage);
1242
1243  /// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the
1244  /// global variable that has already been created for it.  If the initializer
1245  /// has a different type than GV does, this may free GV and return a different
1246  /// one.  Otherwise it just returns GV.
1247  llvm::GlobalVariable *
1248  AddInitializerToGlobalBlockVarDecl(const VarDecl &D,
1249                                     llvm::GlobalVariable *GV);
1250
1251
1252  /// EmitStaticCXXBlockVarDeclInit - Create the initializer for a C++ runtime
1253  /// initialized static block var decl.
1254  void EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
1255                                     llvm::GlobalVariable *GV);
1256
1257  /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
1258  /// variable with global storage.
1259  void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr);
1260
1261  /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr
1262  /// with the C++ runtime so that its destructor will be called at exit.
1263  void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
1264                                     llvm::Constant *DeclPtr);
1265
1266  /// GenerateCXXGlobalInitFunc - Generates code for initializing global
1267  /// variables.
1268  void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
1269                                 llvm::Constant **Decls,
1270                                 unsigned NumDecls);
1271
1272  /// GenerateCXXGlobalDtorFunc - Generates code for destroying global
1273  /// variables.
1274  void GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
1275                                 const std::vector<std::pair<llvm::Constant*,
1276                                   llvm::Constant*> > &DtorsAndObjects);
1277
1278  void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D);
1279
1280  void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E);
1281
1282  RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E,
1283                                    llvm::Value *AggLoc = 0,
1284                                    bool IsAggLocVolatile = false,
1285                                    bool IsInitializer = false);
1286
1287  void EmitCXXThrowExpr(const CXXThrowExpr *E);
1288
1289  //===--------------------------------------------------------------------===//
1290  //                             Internal Helpers
1291  //===--------------------------------------------------------------------===//
1292
1293  /// ContainsLabel - Return true if the statement contains a label in it.  If
1294  /// this statement is not executed normally, it not containing a label means
1295  /// that we can just remove the code.
1296  static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
1297
1298  /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1299  /// to a constant, or if it does but contains a label, return 0.  If it
1300  /// constant folds to 'true' and does not contain a label, return 1, if it
1301  /// constant folds to 'false' and does not contain a label, return -1.
1302  int ConstantFoldsToSimpleInteger(const Expr *Cond);
1303
1304  /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
1305  /// if statement) to the specified blocks.  Based on the condition, this might
1306  /// try to simplify the codegen of the conditional based on the branch.
1307  void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
1308                            llvm::BasicBlock *FalseBlock);
1309
1310  /// getTrapBB - Create a basic block that will call the trap intrinsic.  We'll
1311  /// generate a branch around the created basic block as necessary.
1312  llvm::BasicBlock* getTrapBB();
1313
1314  /// EmitCallArg - Emit a single call argument.
1315  RValue EmitCallArg(const Expr *E, QualType ArgType);
1316
1317private:
1318
1319  void EmitReturnOfRValue(RValue RV, QualType Ty);
1320
1321  /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
1322  /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
1323  ///
1324  /// \param AI - The first function argument of the expansion.
1325  /// \return The argument following the last expanded function
1326  /// argument.
1327  llvm::Function::arg_iterator
1328  ExpandTypeFromArgs(QualType Ty, LValue Dst,
1329                     llvm::Function::arg_iterator AI);
1330
1331  /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
1332  /// Ty, into individual arguments on the provided vector \arg Args. See
1333  /// ABIArgInfo::Expand.
1334  void ExpandTypeToArgs(QualType Ty, RValue Src,
1335                        llvm::SmallVector<llvm::Value*, 16> &Args);
1336
1337  llvm::Value* EmitAsmInput(const AsmStmt &S,
1338                            const TargetInfo::ConstraintInfo &Info,
1339                            const Expr *InputExpr, std::string &ConstraintStr);
1340
1341  /// EmitCleanupBlock - emits a single cleanup block.
1342  void EmitCleanupBlock();
1343
1344  /// AddBranchFixup - adds a branch instruction to the list of fixups for the
1345  /// current cleanup scope.
1346  void AddBranchFixup(llvm::BranchInst *BI);
1347
1348  /// EmitCallArgs - Emit call arguments for a function.
1349  /// The CallArgTypeInfo parameter is used for iterating over the known
1350  /// argument types of the function being called.
1351  template<typename T>
1352  void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
1353                    CallExpr::const_arg_iterator ArgBeg,
1354                    CallExpr::const_arg_iterator ArgEnd) {
1355      CallExpr::const_arg_iterator Arg = ArgBeg;
1356
1357    // First, use the argument types that the type info knows about
1358    if (CallArgTypeInfo) {
1359      for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
1360           E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
1361        assert(Arg != ArgEnd && "Running over edge of argument list!");
1362        QualType ArgType = *I;
1363
1364        assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
1365               getTypePtr() ==
1366               getContext().getCanonicalType(Arg->getType()).getTypePtr() &&
1367               "type mismatch in call argument!");
1368
1369        Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1370                                      ArgType));
1371      }
1372
1373      // Either we've emitted all the call args, or we have a call to a
1374      // variadic function.
1375      assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
1376             "Extra arguments in non-variadic function!");
1377
1378    }
1379
1380    // If we still have any arguments, emit them using the type of the argument.
1381    for (; Arg != ArgEnd; ++Arg) {
1382      QualType ArgType = Arg->getType();
1383      Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1384                                    ArgType));
1385    }
1386  }
1387
1388  const TargetCodeGenInfo &getTargetHooks() const {
1389    return CGM.getTargetCodeGenInfo();
1390  }
1391};
1392
1393
1394}  // end namespace CodeGen
1395}  // end namespace clang
1396
1397#endif
1398