CodeGenFunction.h revision 1e7fe751466ea82665fd21e9162fd7cc9c5f412d
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  class CallSite;
41}
42
43namespace clang {
44  class APValue;
45  class ASTContext;
46  class CXXDestructorDecl;
47  class CXXTryStmt;
48  class Decl;
49  class EnumConstantDecl;
50  class FunctionDecl;
51  class FunctionProtoType;
52  class LabelStmt;
53  class ObjCContainerDecl;
54  class ObjCInterfaceDecl;
55  class ObjCIvarDecl;
56  class ObjCMethodDecl;
57  class ObjCImplementationDecl;
58  class ObjCPropertyImplDecl;
59  class TargetInfo;
60  class TargetCodeGenInfo;
61  class VarDecl;
62  class ObjCForCollectionStmt;
63  class ObjCAtTryStmt;
64  class ObjCAtThrowStmt;
65  class ObjCAtSynchronizedStmt;
66
67namespace CodeGen {
68  class CodeGenTypes;
69  class CGDebugInfo;
70  class CGFunctionInfo;
71  class CGRecordLayout;
72  class CGBlockInfo;
73  class CGCXXABI;
74
75/// A branch fixup.  These are required when emitting a goto to a
76/// label which hasn't been emitted yet.  The goto is optimistically
77/// emitted as a branch to the basic block for the label, and (if it
78/// occurs in a scope with non-trivial cleanups) a fixup is added to
79/// the innermost cleanup.  When a (normal) cleanup is popped, any
80/// unresolved fixups in that scope are threaded through the cleanup.
81struct BranchFixup {
82  /// The block containing the terminator which needs to be modified
83  /// into a switch if this fixup is resolved into the current scope.
84  /// If null, LatestBranch points directly to the destination.
85  llvm::BasicBlock *OptimisticBranchBlock;
86
87  /// The ultimate destination of the branch.
88  ///
89  /// This can be set to null to indicate that this fixup was
90  /// successfully resolved.
91  llvm::BasicBlock *Destination;
92
93  /// The destination index value.
94  unsigned DestinationIndex;
95
96  /// The initial branch of the fixup.
97  llvm::BranchInst *InitialBranch;
98};
99
100enum CleanupKind {
101  EHCleanup = 0x1,
102  NormalCleanup = 0x2,
103  NormalAndEHCleanup = EHCleanup | NormalCleanup,
104
105  InactiveCleanup = 0x4,
106  InactiveEHCleanup = EHCleanup | InactiveCleanup,
107  InactiveNormalCleanup = NormalCleanup | InactiveCleanup,
108  InactiveNormalAndEHCleanup = NormalAndEHCleanup | InactiveCleanup
109};
110
111/// A stack of scopes which respond to exceptions, including cleanups
112/// and catch blocks.
113class EHScopeStack {
114public:
115  /// A saved depth on the scope stack.  This is necessary because
116  /// pushing scopes onto the stack invalidates iterators.
117  class stable_iterator {
118    friend class EHScopeStack;
119
120    /// Offset from StartOfData to EndOfBuffer.
121    ptrdiff_t Size;
122
123    stable_iterator(ptrdiff_t Size) : Size(Size) {}
124
125  public:
126    static stable_iterator invalid() { return stable_iterator(-1); }
127    stable_iterator() : Size(-1) {}
128
129    bool isValid() const { return Size >= 0; }
130
131    /// Returns true if this scope encloses I.
132    /// Returns false if I is invalid.
133    /// This scope must be valid.
134    bool encloses(stable_iterator I) const { return Size <= I.Size; }
135
136    /// Returns true if this scope strictly encloses I: that is,
137    /// if it encloses I and is not I.
138    /// Returns false is I is invalid.
139    /// This scope must be valid.
140    bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; }
141
142    friend bool operator==(stable_iterator A, stable_iterator B) {
143      return A.Size == B.Size;
144    }
145    friend bool operator!=(stable_iterator A, stable_iterator B) {
146      return A.Size != B.Size;
147    }
148  };
149
150  /// Information for lazily generating a cleanup.  Subclasses must be
151  /// POD-like: cleanups will not be destructed, and they will be
152  /// allocated on the cleanup stack and freely copied and moved
153  /// around.
154  ///
155  /// Cleanup implementations should generally be declared in an
156  /// anonymous namespace.
157  class Cleanup {
158  public:
159    // Anchor the construction vtable.  We use the destructor because
160    // gcc gives an obnoxious warning if there are virtual methods
161    // with an accessible non-virtual destructor.  Unfortunately,
162    // declaring this destructor makes it non-trivial, but there
163    // doesn't seem to be any other way around this warning.
164    //
165    // This destructor will never be called.
166    virtual ~Cleanup();
167
168    /// Emit the cleanup.  For normal cleanups, this is run in the
169    /// same EH context as when the cleanup was pushed, i.e. the
170    /// immediately-enclosing context of the cleanup scope.  For
171    /// EH cleanups, this is run in a terminate context.
172    ///
173    // \param IsForEHCleanup true if this is for an EH cleanup, false
174    ///  if for a normal cleanup.
175    virtual void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) = 0;
176  };
177
178private:
179  // The implementation for this class is in CGException.h and
180  // CGException.cpp; the definition is here because it's used as a
181  // member of CodeGenFunction.
182
183  /// The start of the scope-stack buffer, i.e. the allocated pointer
184  /// for the buffer.  All of these pointers are either simultaneously
185  /// null or simultaneously valid.
186  char *StartOfBuffer;
187
188  /// The end of the buffer.
189  char *EndOfBuffer;
190
191  /// The first valid entry in the buffer.
192  char *StartOfData;
193
194  /// The innermost normal cleanup on the stack.
195  stable_iterator InnermostNormalCleanup;
196
197  /// The innermost EH cleanup on the stack.
198  stable_iterator InnermostEHCleanup;
199
200  /// The number of catches on the stack.
201  unsigned CatchDepth;
202
203  /// The current EH destination index.  Reset to FirstCatchIndex
204  /// whenever the last EH cleanup is popped.
205  unsigned NextEHDestIndex;
206  enum { FirstEHDestIndex = 1 };
207
208  /// The current set of branch fixups.  A branch fixup is a jump to
209  /// an as-yet unemitted label, i.e. a label for which we don't yet
210  /// know the EH stack depth.  Whenever we pop a cleanup, we have
211  /// to thread all the current branch fixups through it.
212  ///
213  /// Fixups are recorded as the Use of the respective branch or
214  /// switch statement.  The use points to the final destination.
215  /// When popping out of a cleanup, these uses are threaded through
216  /// the cleanup and adjusted to point to the new cleanup.
217  ///
218  /// Note that branches are allowed to jump into protected scopes
219  /// in certain situations;  e.g. the following code is legal:
220  ///     struct A { ~A(); }; // trivial ctor, non-trivial dtor
221  ///     goto foo;
222  ///     A a;
223  ///    foo:
224  ///     bar();
225  llvm::SmallVector<BranchFixup, 8> BranchFixups;
226
227  char *allocate(size_t Size);
228
229  void *pushCleanup(CleanupKind K, size_t DataSize);
230
231public:
232  EHScopeStack() : StartOfBuffer(0), EndOfBuffer(0), StartOfData(0),
233                   InnermostNormalCleanup(stable_end()),
234                   InnermostEHCleanup(stable_end()),
235                   CatchDepth(0), NextEHDestIndex(FirstEHDestIndex) {}
236  ~EHScopeStack() { delete[] StartOfBuffer; }
237
238  // Variadic templates would make this not terrible.
239
240  /// Push a lazily-created cleanup on the stack.
241  template <class T>
242  void pushCleanup(CleanupKind Kind) {
243    void *Buffer = pushCleanup(Kind, sizeof(T));
244    Cleanup *Obj = new(Buffer) T();
245    (void) Obj;
246  }
247
248  /// Push a lazily-created cleanup on the stack.
249  template <class T, class A0>
250  void pushCleanup(CleanupKind Kind, A0 a0) {
251    void *Buffer = pushCleanup(Kind, sizeof(T));
252    Cleanup *Obj = new(Buffer) T(a0);
253    (void) Obj;
254  }
255
256  /// Push a lazily-created cleanup on the stack.
257  template <class T, class A0, class A1>
258  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) {
259    void *Buffer = pushCleanup(Kind, sizeof(T));
260    Cleanup *Obj = new(Buffer) T(a0, a1);
261    (void) Obj;
262  }
263
264  /// Push a lazily-created cleanup on the stack.
265  template <class T, class A0, class A1, class A2>
266  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) {
267    void *Buffer = pushCleanup(Kind, sizeof(T));
268    Cleanup *Obj = new(Buffer) T(a0, a1, a2);
269    (void) Obj;
270  }
271
272  /// Push a lazily-created cleanup on the stack.
273  template <class T, class A0, class A1, class A2, class A3>
274  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) {
275    void *Buffer = pushCleanup(Kind, sizeof(T));
276    Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3);
277    (void) Obj;
278  }
279
280  /// Push a lazily-created cleanup on the stack.
281  template <class T, class A0, class A1, class A2, class A3, class A4>
282  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
283    void *Buffer = pushCleanup(Kind, sizeof(T));
284    Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4);
285    (void) Obj;
286  }
287
288  /// Pops a cleanup scope off the stack.  This should only be called
289  /// by CodeGenFunction::PopCleanupBlock.
290  void popCleanup();
291
292  /// Push a set of catch handlers on the stack.  The catch is
293  /// uninitialized and will need to have the given number of handlers
294  /// set on it.
295  class EHCatchScope *pushCatch(unsigned NumHandlers);
296
297  /// Pops a catch scope off the stack.
298  void popCatch();
299
300  /// Push an exceptions filter on the stack.
301  class EHFilterScope *pushFilter(unsigned NumFilters);
302
303  /// Pops an exceptions filter off the stack.
304  void popFilter();
305
306  /// Push a terminate handler on the stack.
307  void pushTerminate();
308
309  /// Pops a terminate handler off the stack.
310  void popTerminate();
311
312  /// Determines whether the exception-scopes stack is empty.
313  bool empty() const { return StartOfData == EndOfBuffer; }
314
315  bool requiresLandingPad() const {
316    return (CatchDepth || hasEHCleanups());
317  }
318
319  /// Determines whether there are any normal cleanups on the stack.
320  bool hasNormalCleanups() const {
321    return InnermostNormalCleanup != stable_end();
322  }
323
324  /// Returns the innermost normal cleanup on the stack, or
325  /// stable_end() if there are no normal cleanups.
326  stable_iterator getInnermostNormalCleanup() const {
327    return InnermostNormalCleanup;
328  }
329  stable_iterator getInnermostActiveNormalCleanup() const; // CGException.h
330
331  /// Determines whether there are any EH cleanups on the stack.
332  bool hasEHCleanups() const {
333    return InnermostEHCleanup != stable_end();
334  }
335
336  /// Returns the innermost EH cleanup on the stack, or stable_end()
337  /// if there are no EH cleanups.
338  stable_iterator getInnermostEHCleanup() const {
339    return InnermostEHCleanup;
340  }
341  stable_iterator getInnermostActiveEHCleanup() const; // CGException.h
342
343  /// An unstable reference to a scope-stack depth.  Invalidated by
344  /// pushes but not pops.
345  class iterator;
346
347  /// Returns an iterator pointing to the innermost EH scope.
348  iterator begin() const;
349
350  /// Returns an iterator pointing to the outermost EH scope.
351  iterator end() const;
352
353  /// Create a stable reference to the top of the EH stack.  The
354  /// returned reference is valid until that scope is popped off the
355  /// stack.
356  stable_iterator stable_begin() const {
357    return stable_iterator(EndOfBuffer - StartOfData);
358  }
359
360  /// Create a stable reference to the bottom of the EH stack.
361  static stable_iterator stable_end() {
362    return stable_iterator(0);
363  }
364
365  /// Translates an iterator into a stable_iterator.
366  stable_iterator stabilize(iterator it) const;
367
368  /// Finds the nearest cleanup enclosing the given iterator.
369  /// Returns stable_iterator::invalid() if there are no such cleanups.
370  stable_iterator getEnclosingEHCleanup(iterator it) const;
371
372  /// Turn a stable reference to a scope depth into a unstable pointer
373  /// to the EH stack.
374  iterator find(stable_iterator save) const;
375
376  /// Removes the cleanup pointed to by the given stable_iterator.
377  void removeCleanup(stable_iterator save);
378
379  /// Add a branch fixup to the current cleanup scope.
380  BranchFixup &addBranchFixup() {
381    assert(hasNormalCleanups() && "adding fixup in scope without cleanups");
382    BranchFixups.push_back(BranchFixup());
383    return BranchFixups.back();
384  }
385
386  unsigned getNumBranchFixups() const { return BranchFixups.size(); }
387  BranchFixup &getBranchFixup(unsigned I) {
388    assert(I < getNumBranchFixups());
389    return BranchFixups[I];
390  }
391
392  /// Pops lazily-removed fixups from the end of the list.  This
393  /// should only be called by procedures which have just popped a
394  /// cleanup or resolved one or more fixups.
395  void popNullFixups();
396
397  /// Clears the branch-fixups list.  This should only be called by
398  /// CodeGenFunction::ResolveAllBranchFixups.
399  void clearFixups() { BranchFixups.clear(); }
400
401  /// Gets the next EH destination index.
402  unsigned getNextEHDestIndex() { return NextEHDestIndex++; }
403};
404
405/// CodeGenFunction - This class organizes the per-function state that is used
406/// while generating LLVM code.
407class CodeGenFunction : public BlockFunction {
408  CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT
409  void operator=(const CodeGenFunction&);  // DO NOT IMPLEMENT
410
411  friend class CGCXXABI;
412public:
413  /// A jump destination is an abstract label, branching to which may
414  /// require a jump out through normal cleanups.
415  struct JumpDest {
416    JumpDest() : Block(0), ScopeDepth(), Index(0) {}
417    JumpDest(llvm::BasicBlock *Block,
418             EHScopeStack::stable_iterator Depth,
419             unsigned Index)
420      : Block(Block), ScopeDepth(Depth), Index(Index) {}
421
422    bool isValid() const { return Block != 0; }
423    llvm::BasicBlock *getBlock() const { return Block; }
424    EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
425    unsigned getDestIndex() const { return Index; }
426
427  private:
428    llvm::BasicBlock *Block;
429    EHScopeStack::stable_iterator ScopeDepth;
430    unsigned Index;
431  };
432
433  /// An unwind destination is an abstract label, branching to which
434  /// may require a jump out through EH cleanups.
435  struct UnwindDest {
436    UnwindDest() : Block(0), ScopeDepth(), Index(0) {}
437    UnwindDest(llvm::BasicBlock *Block,
438               EHScopeStack::stable_iterator Depth,
439               unsigned Index)
440      : Block(Block), ScopeDepth(Depth), Index(Index) {}
441
442    bool isValid() const { return Block != 0; }
443    llvm::BasicBlock *getBlock() const { return Block; }
444    EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
445    unsigned getDestIndex() const { return Index; }
446
447  private:
448    llvm::BasicBlock *Block;
449    EHScopeStack::stable_iterator ScopeDepth;
450    unsigned Index;
451  };
452
453  CodeGenModule &CGM;  // Per-module state.
454  const TargetInfo &Target;
455
456  typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
457  CGBuilderTy Builder;
458
459  /// CurFuncDecl - Holds the Decl for the current function or ObjC method.
460  /// This excludes BlockDecls.
461  const Decl *CurFuncDecl;
462  /// CurCodeDecl - This is the inner-most code context, which includes blocks.
463  const Decl *CurCodeDecl;
464  const CGFunctionInfo *CurFnInfo;
465  QualType FnRetTy;
466  llvm::Function *CurFn;
467
468  /// CurGD - The GlobalDecl for the current function being compiled.
469  GlobalDecl CurGD;
470
471  /// ReturnBlock - Unified return block.
472  JumpDest ReturnBlock;
473
474  /// ReturnValue - The temporary alloca to hold the return value. This is null
475  /// iff the function has no return value.
476  llvm::Value *ReturnValue;
477
478  /// RethrowBlock - Unified rethrow block.
479  UnwindDest RethrowBlock;
480
481  /// AllocaInsertPoint - This is an instruction in the entry block before which
482  /// we prefer to insert allocas.
483  llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
484
485  // intptr_t, i32, i64
486  const llvm::IntegerType *IntPtrTy, *Int32Ty, *Int64Ty;
487  uint32_t LLVMPointerWidth;
488
489  bool Exceptions;
490  bool CatchUndefined;
491
492  /// \brief A mapping from NRVO variables to the flags used to indicate
493  /// when the NRVO has been applied to this variable.
494  llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
495
496  EHScopeStack EHStack;
497
498  /// i32s containing the indexes of the cleanup destinations.
499  llvm::AllocaInst *NormalCleanupDest;
500  llvm::AllocaInst *EHCleanupDest;
501
502  unsigned NextCleanupDestIndex;
503
504  /// The exception slot.  All landing pads write the current
505  /// exception pointer into this alloca.
506  llvm::Value *ExceptionSlot;
507
508  /// Emits a landing pad for the current EH stack.
509  llvm::BasicBlock *EmitLandingPad();
510
511  llvm::BasicBlock *getInvokeDestImpl();
512
513public:
514  /// ObjCEHValueStack - Stack of Objective-C exception values, used for
515  /// rethrows.
516  llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack;
517
518  // A struct holding information about a finally block's IR
519  // generation.  For now, doesn't actually hold anything.
520  struct FinallyInfo {
521  };
522
523  FinallyInfo EnterFinallyBlock(const Stmt *Stmt,
524                                llvm::Constant *BeginCatchFn,
525                                llvm::Constant *EndCatchFn,
526                                llvm::Constant *RethrowFn);
527  void ExitFinallyBlock(FinallyInfo &FinallyInfo);
528
529  /// PushDestructorCleanup - Push a cleanup to call the
530  /// complete-object destructor of an object of the given type at the
531  /// given address.  Does nothing if T is not a C++ class type with a
532  /// non-trivial destructor.
533  void PushDestructorCleanup(QualType T, llvm::Value *Addr);
534
535  /// PushDestructorCleanup - Push a cleanup to call the
536  /// complete-object variant of the given destructor on the object at
537  /// the given address.
538  void PushDestructorCleanup(const CXXDestructorDecl *Dtor,
539                             llvm::Value *Addr);
540
541  /// PopCleanupBlock - Will pop the cleanup entry on the stack and
542  /// process all branch fixups.
543  void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
544
545  void ActivateCleanup(EHScopeStack::stable_iterator Cleanup);
546
547  /// \brief Enters a new scope for capturing cleanups, all of which
548  /// will be executed once the scope is exited.
549  class RunCleanupsScope {
550    CodeGenFunction& CGF;
551    EHScopeStack::stable_iterator CleanupStackDepth;
552    bool OldDidCallStackSave;
553    bool PerformCleanup;
554
555    RunCleanupsScope(const RunCleanupsScope &); // DO NOT IMPLEMENT
556    RunCleanupsScope &operator=(const RunCleanupsScope &); // DO NOT IMPLEMENT
557
558  public:
559    /// \brief Enter a new cleanup scope.
560    explicit RunCleanupsScope(CodeGenFunction &CGF)
561      : CGF(CGF), PerformCleanup(true)
562    {
563      CleanupStackDepth = CGF.EHStack.stable_begin();
564      OldDidCallStackSave = CGF.DidCallStackSave;
565    }
566
567    /// \brief Exit this cleanup scope, emitting any accumulated
568    /// cleanups.
569    ~RunCleanupsScope() {
570      if (PerformCleanup) {
571        CGF.DidCallStackSave = OldDidCallStackSave;
572        CGF.PopCleanupBlocks(CleanupStackDepth);
573      }
574    }
575
576    /// \brief Determine whether this scope requires any cleanups.
577    bool requiresCleanups() const {
578      return CGF.EHStack.stable_begin() != CleanupStackDepth;
579    }
580
581    /// \brief Force the emission of cleanups now, instead of waiting
582    /// until this object is destroyed.
583    void ForceCleanup() {
584      assert(PerformCleanup && "Already forced cleanup");
585      CGF.DidCallStackSave = OldDidCallStackSave;
586      CGF.PopCleanupBlocks(CleanupStackDepth);
587      PerformCleanup = false;
588    }
589  };
590
591
592  /// PopCleanupBlocks - Takes the old cleanup stack size and emits
593  /// the cleanup blocks that have been added.
594  void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
595
596  void ResolveAllBranchFixups(llvm::SwitchInst *Switch);
597  void ResolveBranchFixups(llvm::BasicBlock *Target);
598
599  /// The given basic block lies in the current EH scope, but may be a
600  /// target of a potentially scope-crossing jump; get a stable handle
601  /// to which we can perform this jump later.
602  JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
603    return JumpDest(Target,
604                    EHStack.getInnermostNormalCleanup(),
605                    NextCleanupDestIndex++);
606  }
607
608  /// The given basic block lies in the current EH scope, but may be a
609  /// target of a potentially scope-crossing jump; get a stable handle
610  /// to which we can perform this jump later.
611  JumpDest getJumpDestInCurrentScope(const char *Name = 0) {
612    return getJumpDestInCurrentScope(createBasicBlock(Name));
613  }
614
615  /// EmitBranchThroughCleanup - Emit a branch from the current insert
616  /// block through the normal cleanup handling code (if any) and then
617  /// on to \arg Dest.
618  void EmitBranchThroughCleanup(JumpDest Dest);
619
620  /// EmitBranchThroughEHCleanup - Emit a branch from the current
621  /// insert block through the EH cleanup handling code (if any) and
622  /// then on to \arg Dest.
623  void EmitBranchThroughEHCleanup(UnwindDest Dest);
624
625  /// getRethrowDest - Returns the unified outermost-scope rethrow
626  /// destination.
627  UnwindDest getRethrowDest();
628
629  /// BeginConditionalBranch - Should be called before a conditional part of an
630  /// expression is emitted. For example, before the RHS of the expression below
631  /// is emitted:
632  ///
633  /// b && f(T());
634  ///
635  /// This is used to make sure that any temporaries created in the conditional
636  /// branch are only destroyed if the branch is taken.
637  void BeginConditionalBranch() {
638    ++ConditionalBranchLevel;
639  }
640
641  /// EndConditionalBranch - Should be called after a conditional part of an
642  /// expression has been emitted.
643  void EndConditionalBranch() {
644    assert(ConditionalBranchLevel != 0 &&
645           "Conditional branch mismatch!");
646
647    --ConditionalBranchLevel;
648  }
649
650private:
651  CGDebugInfo *DebugInfo;
652
653  /// IndirectBranch - The first time an indirect goto is seen we create a block
654  /// with an indirect branch.  Every time we see the address of a label taken,
655  /// we add the label to the indirect goto.  Every subsequent indirect goto is
656  /// codegen'd as a jump to the IndirectBranch's basic block.
657  llvm::IndirectBrInst *IndirectBranch;
658
659  /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
660  /// decls.
661  llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
662
663  /// LabelMap - This keeps track of the LLVM basic block for each C label.
664  llvm::DenseMap<const LabelStmt*, JumpDest> LabelMap;
665
666  // BreakContinueStack - This keeps track of where break and continue
667  // statements should jump to.
668  struct BreakContinue {
669    BreakContinue(JumpDest Break, JumpDest Continue)
670      : BreakBlock(Break), ContinueBlock(Continue) {}
671
672    JumpDest BreakBlock;
673    JumpDest ContinueBlock;
674  };
675  llvm::SmallVector<BreakContinue, 8> BreakContinueStack;
676
677  /// SwitchInsn - This is nearest current switch instruction. It is null if if
678  /// current context is not in a switch.
679  llvm::SwitchInst *SwitchInsn;
680
681  /// CaseRangeBlock - This block holds if condition check for last case
682  /// statement range in current switch instruction.
683  llvm::BasicBlock *CaseRangeBlock;
684
685  // VLASizeMap - This keeps track of the associated size for each VLA type.
686  // We track this by the size expression rather than the type itself because
687  // in certain situations, like a const qualifier applied to an VLA typedef,
688  // multiple VLA types can share the same size expression.
689  // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
690  // enter/leave scopes.
691  llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
692
693  /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
694  /// calling llvm.stacksave for multiple VLAs in the same scope.
695  bool DidCallStackSave;
696
697  /// A block containing a single 'unreachable' instruction.  Created
698  /// lazily by getUnreachableBlock().
699  llvm::BasicBlock *UnreachableBlock;
700
701  /// CXXThisDecl - When generating code for a C++ member function,
702  /// this will hold the implicit 'this' declaration.
703  ImplicitParamDecl *CXXThisDecl;
704  llvm::Value *CXXThisValue;
705
706  /// CXXVTTDecl - When generating code for a base object constructor or
707  /// base object destructor with virtual bases, this will hold the implicit
708  /// VTT parameter.
709  ImplicitParamDecl *CXXVTTDecl;
710  llvm::Value *CXXVTTValue;
711
712  /// ConditionalBranchLevel - Contains the nesting level of the current
713  /// conditional branch. This is used so that we know if a temporary should be
714  /// destroyed conditionally.
715  unsigned ConditionalBranchLevel;
716
717
718  /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
719  /// type as well as the field number that contains the actual data.
720  llvm::DenseMap<const ValueDecl *, std::pair<const llvm::Type *,
721                                              unsigned> > ByRefValueInfo;
722
723  /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
724  /// number that holds the value.
725  unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
726
727  llvm::BasicBlock *TerminateLandingPad;
728  llvm::BasicBlock *TerminateHandler;
729  llvm::BasicBlock *TrapBB;
730
731public:
732  CodeGenFunction(CodeGenModule &cgm);
733
734  CodeGenTypes &getTypes() const { return CGM.getTypes(); }
735  ASTContext &getContext() const;
736  CGDebugInfo *getDebugInfo() { return DebugInfo; }
737
738  /// Returns a pointer to the function's exception object slot, which
739  /// is assigned in every landing pad.
740  llvm::Value *getExceptionSlot();
741
742  llvm::Value *getNormalCleanupDestSlot();
743  llvm::Value *getEHCleanupDestSlot();
744
745  llvm::BasicBlock *getUnreachableBlock() {
746    if (!UnreachableBlock) {
747      UnreachableBlock = createBasicBlock("unreachable");
748      new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
749    }
750    return UnreachableBlock;
751  }
752
753  llvm::BasicBlock *getInvokeDest() {
754    if (!EHStack.requiresLandingPad()) return 0;
755    return getInvokeDestImpl();
756  }
757
758  llvm::LLVMContext &getLLVMContext() { return VMContext; }
759
760  //===--------------------------------------------------------------------===//
761  //                                  Objective-C
762  //===--------------------------------------------------------------------===//
763
764  void GenerateObjCMethod(const ObjCMethodDecl *OMD);
765
766  void StartObjCMethod(const ObjCMethodDecl *MD,
767                       const ObjCContainerDecl *CD);
768
769  /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
770  void GenerateObjCGetter(ObjCImplementationDecl *IMP,
771                          const ObjCPropertyImplDecl *PID);
772  void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
773                                  ObjCMethodDecl *MD, bool ctor);
774
775  /// GenerateObjCSetter - Synthesize an Objective-C property setter function
776  /// for the given property.
777  void GenerateObjCSetter(ObjCImplementationDecl *IMP,
778                          const ObjCPropertyImplDecl *PID);
779  bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
780  bool IvarTypeWithAggrGCObjects(QualType Ty);
781
782  //===--------------------------------------------------------------------===//
783  //                                  Block Bits
784  //===--------------------------------------------------------------------===//
785
786  llvm::Value *BuildBlockLiteralTmp(const BlockExpr *);
787  llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
788                                           const CGBlockInfo &Info,
789                                           const llvm::StructType *,
790                                           llvm::Constant *BlockVarLayout,
791                                           std::vector<HelperInfo> *);
792
793  llvm::Function *GenerateBlockFunction(GlobalDecl GD,
794                                        const BlockExpr *BExpr,
795                                        CGBlockInfo &Info,
796                                        const Decl *OuterFuncDecl,
797                                        llvm::Constant *& BlockVarLayout,
798                                  llvm::DenseMap<const Decl*, llvm::Value*> ldm);
799
800  llvm::Value *LoadBlockStruct();
801
802  void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
803  void AllocateBlockDecl(const BlockDeclRefExpr *E);
804  llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
805    return GetAddrOfBlockDecl(E->getDecl(), E->isByRef());
806  }
807  llvm::Value *GetAddrOfBlockDecl(const ValueDecl *D, bool ByRef);
808  const llvm::Type *BuildByRefType(const ValueDecl *D);
809
810  void GenerateCode(GlobalDecl GD, llvm::Function *Fn);
811  void StartFunction(GlobalDecl GD, QualType RetTy,
812                     llvm::Function *Fn,
813                     const FunctionArgList &Args,
814                     SourceLocation StartLoc);
815
816  void EmitConstructorBody(FunctionArgList &Args);
817  void EmitDestructorBody(FunctionArgList &Args);
818  void EmitFunctionBody(FunctionArgList &Args);
819
820  /// EmitReturnBlock - Emit the unified return block, trying to avoid its
821  /// emission when possible.
822  void EmitReturnBlock();
823
824  /// FinishFunction - Complete IR generation of the current function. It is
825  /// legal to call this function even if there is no current insertion point.
826  void FinishFunction(SourceLocation EndLoc=SourceLocation());
827
828  /// GenerateThunk - Generate a thunk for the given method.
829  void GenerateThunk(llvm::Function *Fn, GlobalDecl GD, const ThunkInfo &Thunk);
830
831  void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
832                        FunctionArgList &Args);
833
834  /// InitializeVTablePointer - Initialize the vtable pointer of the given
835  /// subobject.
836  ///
837  void InitializeVTablePointer(BaseSubobject Base,
838                               const CXXRecordDecl *NearestVBase,
839                               uint64_t OffsetFromNearestVBase,
840                               llvm::Constant *VTable,
841                               const CXXRecordDecl *VTableClass);
842
843  typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
844  void InitializeVTablePointers(BaseSubobject Base,
845                                const CXXRecordDecl *NearestVBase,
846                                uint64_t OffsetFromNearestVBase,
847                                bool BaseIsNonVirtualPrimaryBase,
848                                llvm::Constant *VTable,
849                                const CXXRecordDecl *VTableClass,
850                                VisitedVirtualBasesSetTy& VBases);
851
852  void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
853
854
855  /// EnterDtorCleanups - Enter the cleanups necessary to complete the
856  /// given phase of destruction for a destructor.  The end result
857  /// should call destructors on members and base classes in reverse
858  /// order of their construction.
859  void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
860
861  /// ShouldInstrumentFunction - Return true if the current function should be
862  /// instrumented with __cyg_profile_func_* calls
863  bool ShouldInstrumentFunction();
864
865  /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
866  /// instrumentation function with the current function and the call site, if
867  /// function instrumentation is enabled.
868  void EmitFunctionInstrumentation(const char *Fn);
869
870  /// EmitFunctionProlog - Emit the target specific LLVM code to load the
871  /// arguments for the given function. This is also responsible for naming the
872  /// LLVM function arguments.
873  void EmitFunctionProlog(const CGFunctionInfo &FI,
874                          llvm::Function *Fn,
875                          const FunctionArgList &Args);
876
877  /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
878  /// given temporary.
879  void EmitFunctionEpilog(const CGFunctionInfo &FI);
880
881  /// EmitStartEHSpec - Emit the start of the exception spec.
882  void EmitStartEHSpec(const Decl *D);
883
884  /// EmitEndEHSpec - Emit the end of the exception spec.
885  void EmitEndEHSpec(const Decl *D);
886
887  /// getTerminateLandingPad - Return a landing pad that just calls terminate.
888  llvm::BasicBlock *getTerminateLandingPad();
889
890  /// getTerminateHandler - Return a handler (not a landing pad, just
891  /// a catch handler) that just calls terminate.  This is used when
892  /// a terminate scope encloses a try.
893  llvm::BasicBlock *getTerminateHandler();
894
895  const llvm::Type *ConvertTypeForMem(QualType T);
896  const llvm::Type *ConvertType(QualType T);
897  const llvm::Type *ConvertType(const TypeDecl *T) {
898    return ConvertType(getContext().getTypeDeclType(T));
899  }
900
901  /// LoadObjCSelf - Load the value of self. This function is only valid while
902  /// generating code for an Objective-C method.
903  llvm::Value *LoadObjCSelf();
904
905  /// TypeOfSelfObject - Return type of object that this self represents.
906  QualType TypeOfSelfObject();
907
908  /// hasAggregateLLVMType - Return true if the specified AST type will map into
909  /// an aggregate LLVM type or is void.
910  static bool hasAggregateLLVMType(QualType T);
911
912  /// createBasicBlock - Create an LLVM basic block.
913  llvm::BasicBlock *createBasicBlock(const char *Name="",
914                                     llvm::Function *Parent=0,
915                                     llvm::BasicBlock *InsertBefore=0) {
916#ifdef NDEBUG
917    return llvm::BasicBlock::Create(VMContext, "", Parent, InsertBefore);
918#else
919    return llvm::BasicBlock::Create(VMContext, Name, Parent, InsertBefore);
920#endif
921  }
922
923  /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
924  /// label maps to.
925  JumpDest getJumpDestForLabel(const LabelStmt *S);
926
927  /// SimplifyForwardingBlocks - If the given basic block is only a branch to
928  /// another basic block, simplify it. This assumes that no other code could
929  /// potentially reference the basic block.
930  void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
931
932  /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
933  /// adding a fall-through branch from the current insert block if
934  /// necessary. It is legal to call this function even if there is no current
935  /// insertion point.
936  ///
937  /// IsFinished - If true, indicates that the caller has finished emitting
938  /// branches to the given block and does not expect to emit code into it. This
939  /// means the block can be ignored if it is unreachable.
940  void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
941
942  /// EmitBranch - Emit a branch to the specified basic block from the current
943  /// insert block, taking care to avoid creation of branches from dummy
944  /// blocks. It is legal to call this function even if there is no current
945  /// insertion point.
946  ///
947  /// This function clears the current insertion point. The caller should follow
948  /// calls to this function with calls to Emit*Block prior to generation new
949  /// code.
950  void EmitBranch(llvm::BasicBlock *Block);
951
952  /// HaveInsertPoint - True if an insertion point is defined. If not, this
953  /// indicates that the current code being emitted is unreachable.
954  bool HaveInsertPoint() const {
955    return Builder.GetInsertBlock() != 0;
956  }
957
958  /// EnsureInsertPoint - Ensure that an insertion point is defined so that
959  /// emitted IR has a place to go. Note that by definition, if this function
960  /// creates a block then that block is unreachable; callers may do better to
961  /// detect when no insertion point is defined and simply skip IR generation.
962  void EnsureInsertPoint() {
963    if (!HaveInsertPoint())
964      EmitBlock(createBasicBlock());
965  }
966
967  /// ErrorUnsupported - Print out an error that codegen doesn't support the
968  /// specified stmt yet.
969  void ErrorUnsupported(const Stmt *S, const char *Type,
970                        bool OmitOnError=false);
971
972  //===--------------------------------------------------------------------===//
973  //                                  Helpers
974  //===--------------------------------------------------------------------===//
975
976  LValue MakeAddrLValue(llvm::Value *V, QualType T, unsigned Alignment = 0) {
977    return LValue::MakeAddr(V, T, Alignment, getContext());
978  }
979
980  /// CreateTempAlloca - This creates a alloca and inserts it into the entry
981  /// block. The caller is responsible for setting an appropriate alignment on
982  /// the alloca.
983  llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
984                                     const llvm::Twine &Name = "tmp");
985
986  /// InitTempAlloca - Provide an initial value for the given alloca.
987  void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
988
989  /// CreateIRTemp - Create a temporary IR object of the given type, with
990  /// appropriate alignment. This routine should only be used when an temporary
991  /// value needs to be stored into an alloca (for example, to avoid explicit
992  /// PHI construction), but the type is the IR type, not the type appropriate
993  /// for storing in memory.
994  llvm::AllocaInst *CreateIRTemp(QualType T, const llvm::Twine &Name = "tmp");
995
996  /// CreateMemTemp - Create a temporary memory object of the given type, with
997  /// appropriate alignment.
998  llvm::AllocaInst *CreateMemTemp(QualType T, const llvm::Twine &Name = "tmp");
999
1000  /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1001  /// expression and compare the result against zero, returning an Int1Ty value.
1002  llvm::Value *EvaluateExprAsBool(const Expr *E);
1003
1004  /// EmitAnyExpr - Emit code to compute the specified expression which can have
1005  /// any type.  The result is returned as an RValue struct.  If this is an
1006  /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1007  /// the result should be returned.
1008  ///
1009  /// \param IgnoreResult - True if the resulting value isn't used.
1010  RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0,
1011                     bool IsAggLocVolatile = false, bool IgnoreResult = false,
1012                     bool IsInitializer = false);
1013
1014  // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1015  // or the value of the expression, depending on how va_list is defined.
1016  llvm::Value *EmitVAListRef(const Expr *E);
1017
1018  /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
1019  /// always be accessible even if no aggregate location is provided.
1020  RValue EmitAnyExprToTemp(const Expr *E, bool IsAggLocVolatile = false,
1021                           bool IsInitializer = false);
1022
1023  /// EmitsAnyExprToMem - Emits the code necessary to evaluate an
1024  /// arbitrary expression into the given memory location.
1025  void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
1026                        bool IsLocationVolatile = false,
1027                        bool IsInitializer = false);
1028
1029  /// EmitAggregateCopy - Emit an aggrate copy.
1030  ///
1031  /// \param isVolatile - True iff either the source or the destination is
1032  /// volatile.
1033  void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1034                         QualType EltTy, bool isVolatile=false);
1035
1036  /// StartBlock - Start new block named N. If insert block is a dummy block
1037  /// then reuse it.
1038  void StartBlock(const char *N);
1039
1040  /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
1041  llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD) {
1042    return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
1043  }
1044
1045  /// GetAddrOfLocalVar - Return the address of a local variable.
1046  llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) {
1047    llvm::Value *Res = LocalDeclMap[VD];
1048    assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
1049    return Res;
1050  }
1051
1052  /// getAccessedFieldNo - Given an encoded value and a result number, return
1053  /// the input field number being accessed.
1054  static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
1055
1056  llvm::BlockAddress *GetAddrOfLabel(const LabelStmt *L);
1057  llvm::BasicBlock *GetIndirectGotoBlock();
1058
1059  /// EmitNullInitialization - Generate code to set a value of the given type to
1060  /// null, If the type contains data member pointers, they will be initialized
1061  /// to -1 in accordance with the Itanium C++ ABI.
1062  void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
1063
1064  // EmitVAArg - Generate code to get an argument from the passed in pointer
1065  // and update it accordingly. The return value is a pointer to the argument.
1066  // FIXME: We should be able to get rid of this method and use the va_arg
1067  // instruction in LLVM instead once it works well enough.
1068  llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
1069
1070  /// EmitVLASize - Generate code for any VLA size expressions that might occur
1071  /// in a variably modified type. If Ty is a VLA, will return the value that
1072  /// corresponds to the size in bytes of the VLA type. Will return 0 otherwise.
1073  ///
1074  /// This function can be called with a null (unreachable) insert point.
1075  llvm::Value *EmitVLASize(QualType Ty);
1076
1077  // GetVLASize - Returns an LLVM value that corresponds to the size in bytes
1078  // of a variable length array type.
1079  llvm::Value *GetVLASize(const VariableArrayType *);
1080
1081  /// LoadCXXThis - Load the value of 'this'. This function is only valid while
1082  /// generating code for an C++ member function.
1083  llvm::Value *LoadCXXThis() {
1084    assert(CXXThisValue && "no 'this' value for this function");
1085    return CXXThisValue;
1086  }
1087
1088  /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
1089  /// virtual bases.
1090  llvm::Value *LoadCXXVTT() {
1091    assert(CXXVTTValue && "no VTT value for this function");
1092    return CXXVTTValue;
1093  }
1094
1095  /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
1096  /// complete class to the given direct base.
1097  llvm::Value *
1098  GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
1099                                        const CXXRecordDecl *Derived,
1100                                        const CXXRecordDecl *Base,
1101                                        bool BaseIsVirtual);
1102
1103  /// GetAddressOfBaseClass - This function will add the necessary delta to the
1104  /// load of 'this' and returns address of the base class.
1105  llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
1106                                     const CXXRecordDecl *Derived,
1107                                     CastExpr::path_const_iterator PathBegin,
1108                                     CastExpr::path_const_iterator PathEnd,
1109                                     bool NullCheckValue);
1110
1111  llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
1112                                        const CXXRecordDecl *Derived,
1113                                        CastExpr::path_const_iterator PathBegin,
1114                                        CastExpr::path_const_iterator PathEnd,
1115                                        bool NullCheckValue);
1116
1117  llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
1118                                         const CXXRecordDecl *ClassDecl,
1119                                         const CXXRecordDecl *BaseClassDecl);
1120
1121  void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1122                                      CXXCtorType CtorType,
1123                                      const FunctionArgList &Args);
1124  void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
1125                              bool ForVirtualBase, llvm::Value *This,
1126                              CallExpr::const_arg_iterator ArgBeg,
1127                              CallExpr::const_arg_iterator ArgEnd);
1128
1129  void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1130                                  const ConstantArrayType *ArrayTy,
1131                                  llvm::Value *ArrayPtr,
1132                                  CallExpr::const_arg_iterator ArgBeg,
1133                                  CallExpr::const_arg_iterator ArgEnd,
1134                                  bool ZeroInitialization = false);
1135
1136  void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1137                                  llvm::Value *NumElements,
1138                                  llvm::Value *ArrayPtr,
1139                                  CallExpr::const_arg_iterator ArgBeg,
1140                                  CallExpr::const_arg_iterator ArgEnd,
1141                                  bool ZeroInitialization = false);
1142
1143  void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1144                                 const ArrayType *Array,
1145                                 llvm::Value *This);
1146
1147  void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1148                                 llvm::Value *NumElements,
1149                                 llvm::Value *This);
1150
1151  llvm::Function *GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
1152                                                  const ArrayType *Array,
1153                                                  llvm::Value *This);
1154
1155  void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
1156                             bool ForVirtualBase, llvm::Value *This);
1157
1158  void EmitNewArrayInitializer(const CXXNewExpr *E, llvm::Value *NewPtr,
1159                               llvm::Value *NumElements);
1160
1161  void EmitCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr);
1162
1163  llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
1164  void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
1165
1166  void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
1167                      QualType DeleteTy);
1168
1169  llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
1170  llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
1171
1172  void EmitCheck(llvm::Value *, unsigned Size);
1173
1174  llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1175                                       bool isInc, bool isPre);
1176  ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
1177                                         bool isInc, bool isPre);
1178  //===--------------------------------------------------------------------===//
1179  //                            Declaration Emission
1180  //===--------------------------------------------------------------------===//
1181
1182  /// EmitDecl - Emit a declaration.
1183  ///
1184  /// This function can be called with a null (unreachable) insert point.
1185  void EmitDecl(const Decl &D);
1186
1187  /// EmitBlockVarDecl - Emit a block variable declaration.
1188  ///
1189  /// This function can be called with a null (unreachable) insert point.
1190  void EmitBlockVarDecl(const VarDecl &D);
1191
1192  typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
1193                             llvm::Value *Address);
1194
1195  /// EmitLocalBlockVarDecl - Emit a local block variable declaration.
1196  ///
1197  /// This function can be called with a null (unreachable) insert point.
1198  void EmitLocalBlockVarDecl(const VarDecl &D, SpecialInitFn *SpecialInit = 0);
1199
1200  void EmitStaticBlockVarDecl(const VarDecl &D,
1201                              llvm::GlobalValue::LinkageTypes Linkage);
1202
1203  /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
1204  void EmitParmDecl(const VarDecl &D, llvm::Value *Arg);
1205
1206  //===--------------------------------------------------------------------===//
1207  //                             Statement Emission
1208  //===--------------------------------------------------------------------===//
1209
1210  /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
1211  void EmitStopPoint(const Stmt *S);
1212
1213  /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
1214  /// this function even if there is no current insertion point.
1215  ///
1216  /// This function may clear the current insertion point; callers should use
1217  /// EnsureInsertPoint if they wish to subsequently generate code without first
1218  /// calling EmitBlock, EmitBranch, or EmitStmt.
1219  void EmitStmt(const Stmt *S);
1220
1221  /// EmitSimpleStmt - Try to emit a "simple" statement which does not
1222  /// necessarily require an insertion point or debug information; typically
1223  /// because the statement amounts to a jump or a container of other
1224  /// statements.
1225  ///
1226  /// \return True if the statement was handled.
1227  bool EmitSimpleStmt(const Stmt *S);
1228
1229  RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
1230                          llvm::Value *AggLoc = 0, bool isAggVol = false);
1231
1232  /// EmitLabel - Emit the block for the given label. It is legal to call this
1233  /// function even if there is no current insertion point.
1234  void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt.
1235
1236  void EmitLabelStmt(const LabelStmt &S);
1237  void EmitGotoStmt(const GotoStmt &S);
1238  void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
1239  void EmitIfStmt(const IfStmt &S);
1240  void EmitWhileStmt(const WhileStmt &S);
1241  void EmitDoStmt(const DoStmt &S);
1242  void EmitForStmt(const ForStmt &S);
1243  void EmitReturnStmt(const ReturnStmt &S);
1244  void EmitDeclStmt(const DeclStmt &S);
1245  void EmitBreakStmt(const BreakStmt &S);
1246  void EmitContinueStmt(const ContinueStmt &S);
1247  void EmitSwitchStmt(const SwitchStmt &S);
1248  void EmitDefaultStmt(const DefaultStmt &S);
1249  void EmitCaseStmt(const CaseStmt &S);
1250  void EmitCaseStmtRange(const CaseStmt &S);
1251  void EmitAsmStmt(const AsmStmt &S);
1252
1253  void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
1254  void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
1255  void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
1256  void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
1257
1258  llvm::Constant *getUnwindResumeOrRethrowFn();
1259  void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
1260  void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
1261
1262  void EmitCXXTryStmt(const CXXTryStmt &S);
1263
1264  //===--------------------------------------------------------------------===//
1265  //                         LValue Expression Emission
1266  //===--------------------------------------------------------------------===//
1267
1268  /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
1269  RValue GetUndefRValue(QualType Ty);
1270
1271  /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
1272  /// and issue an ErrorUnsupported style diagnostic (using the
1273  /// provided Name).
1274  RValue EmitUnsupportedRValue(const Expr *E,
1275                               const char *Name);
1276
1277  /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
1278  /// an ErrorUnsupported style diagnostic (using the provided Name).
1279  LValue EmitUnsupportedLValue(const Expr *E,
1280                               const char *Name);
1281
1282  /// EmitLValue - Emit code to compute a designator that specifies the location
1283  /// of the expression.
1284  ///
1285  /// This can return one of two things: a simple address or a bitfield
1286  /// reference.  In either case, the LLVM Value* in the LValue structure is
1287  /// guaranteed to be an LLVM pointer type.
1288  ///
1289  /// If this returns a bitfield reference, nothing about the pointee type of
1290  /// the LLVM value is known: For example, it may not be a pointer to an
1291  /// integer.
1292  ///
1293  /// If this returns a normal address, and if the lvalue's C type is fixed
1294  /// size, this method guarantees that the returned pointer type will point to
1295  /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
1296  /// variable length type, this is not possible.
1297  ///
1298  LValue EmitLValue(const Expr *E);
1299
1300  /// EmitCheckedLValue - Same as EmitLValue but additionally we generate
1301  /// checking code to guard against undefined behavior.  This is only
1302  /// suitable when we know that the address will be used to access the
1303  /// object.
1304  LValue EmitCheckedLValue(const Expr *E);
1305
1306  /// EmitLoadOfScalar - Load a scalar value from an address, taking
1307  /// care to appropriately convert from the memory representation to
1308  /// the LLVM value representation.
1309  llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
1310                                unsigned Alignment, QualType Ty);
1311
1312  /// EmitStoreOfScalar - Store a scalar value to an address, taking
1313  /// care to appropriately convert from the memory representation to
1314  /// the LLVM value representation.
1315  void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
1316                         bool Volatile, unsigned Alignment, QualType Ty);
1317
1318  /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
1319  /// this method emits the address of the lvalue, then loads the result as an
1320  /// rvalue, returning the rvalue.
1321  RValue EmitLoadOfLValue(LValue V, QualType LVType);
1322  RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
1323  RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
1324  RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType);
1325  RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType);
1326
1327
1328  /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1329  /// lvalue, where both are guaranteed to the have the same type, and that type
1330  /// is 'Ty'.
1331  void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
1332  void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
1333                                                QualType Ty);
1334  void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty);
1335  void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty);
1336
1337  /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
1338  /// EmitStoreThroughLValue.
1339  ///
1340  /// \param Result [out] - If non-null, this will be set to a Value* for the
1341  /// bit-field contents after the store, appropriate for use as the result of
1342  /// an assignment to the bit-field.
1343  void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty,
1344                                      llvm::Value **Result=0);
1345
1346  // Note: only availabe for agg return types
1347  LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
1348  LValue EmitCompoundAssignOperatorLValue(const CompoundAssignOperator *E);
1349  // Note: only available for agg return types
1350  LValue EmitCallExprLValue(const CallExpr *E);
1351  // Note: only available for agg return types
1352  LValue EmitVAArgExprLValue(const VAArgExpr *E);
1353  LValue EmitDeclRefLValue(const DeclRefExpr *E);
1354  LValue EmitStringLiteralLValue(const StringLiteral *E);
1355  LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
1356  LValue EmitPredefinedLValue(const PredefinedExpr *E);
1357  LValue EmitUnaryOpLValue(const UnaryOperator *E);
1358  LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
1359  LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
1360  LValue EmitMemberExpr(const MemberExpr *E);
1361  LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
1362  LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
1363  LValue EmitConditionalOperatorLValue(const ConditionalOperator *E);
1364  LValue EmitCastLValue(const CastExpr *E);
1365  LValue EmitNullInitializationLValue(const CXXScalarValueInitExpr *E);
1366
1367  llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
1368                              const ObjCIvarDecl *Ivar);
1369  LValue EmitLValueForAnonRecordField(llvm::Value* Base,
1370                                      const FieldDecl* Field,
1371                                      unsigned CVRQualifiers);
1372  LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field,
1373                            unsigned CVRQualifiers);
1374
1375  /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
1376  /// if the Field is a reference, this will return the address of the reference
1377  /// and not the address of the value stored in the reference.
1378  LValue EmitLValueForFieldInitialization(llvm::Value* Base,
1379                                          const FieldDecl* Field,
1380                                          unsigned CVRQualifiers);
1381
1382  LValue EmitLValueForIvar(QualType ObjectTy,
1383                           llvm::Value* Base, const ObjCIvarDecl *Ivar,
1384                           unsigned CVRQualifiers);
1385
1386  LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field,
1387                                unsigned CVRQualifiers);
1388
1389  LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
1390
1391  LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
1392  LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
1393  LValue EmitCXXExprWithTemporariesLValue(const CXXExprWithTemporaries *E);
1394  LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
1395
1396  LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
1397  LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
1398  LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
1399  LValue EmitObjCKVCRefLValue(const ObjCImplicitSetterGetterRefExpr *E);
1400  LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E);
1401  LValue EmitStmtExprLValue(const StmtExpr *E);
1402  LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
1403  LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
1404  void   EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::ConstantInt *Init);
1405  //===--------------------------------------------------------------------===//
1406  //                         Scalar Expression Emission
1407  //===--------------------------------------------------------------------===//
1408
1409  /// EmitCall - Generate a call of the given function, expecting the given
1410  /// result type, and using the given argument list which specifies both the
1411  /// LLVM arguments and the types they were derived from.
1412  ///
1413  /// \param TargetDecl - If given, the decl of the function in a direct call;
1414  /// used to set attributes on the call (noreturn, etc.).
1415  RValue EmitCall(const CGFunctionInfo &FnInfo,
1416                  llvm::Value *Callee,
1417                  ReturnValueSlot ReturnValue,
1418                  const CallArgList &Args,
1419                  const Decl *TargetDecl = 0,
1420                  llvm::Instruction **callOrInvoke = 0);
1421
1422  RValue EmitCall(QualType FnType, llvm::Value *Callee,
1423                  ReturnValueSlot ReturnValue,
1424                  CallExpr::const_arg_iterator ArgBeg,
1425                  CallExpr::const_arg_iterator ArgEnd,
1426                  const Decl *TargetDecl = 0);
1427  RValue EmitCallExpr(const CallExpr *E,
1428                      ReturnValueSlot ReturnValue = ReturnValueSlot());
1429
1430  llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
1431                                  llvm::Value * const *ArgBegin,
1432                                  llvm::Value * const *ArgEnd,
1433                                  const llvm::Twine &Name = "");
1434
1435  llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1436                                const llvm::Type *Ty);
1437  llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1438                                llvm::Value *&This, const llvm::Type *Ty);
1439
1440  RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
1441                           llvm::Value *Callee,
1442                           ReturnValueSlot ReturnValue,
1443                           llvm::Value *This,
1444                           llvm::Value *VTT,
1445                           CallExpr::const_arg_iterator ArgBeg,
1446                           CallExpr::const_arg_iterator ArgEnd);
1447  RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
1448                               ReturnValueSlot ReturnValue);
1449  RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
1450                                      ReturnValueSlot ReturnValue);
1451
1452  RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
1453                                       const CXXMethodDecl *MD,
1454                                       ReturnValueSlot ReturnValue);
1455
1456
1457  RValue EmitBuiltinExpr(const FunctionDecl *FD,
1458                         unsigned BuiltinID, const CallExpr *E);
1459
1460  RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
1461
1462  /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
1463  /// is unhandled by the current target.
1464  llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1465
1466  llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1467  llvm::Value *EmitNeonCall(llvm::Function *F,
1468                            llvm::SmallVectorImpl<llvm::Value*> &O,
1469                            const char *name, bool splat = false,
1470                            unsigned shift = 0, bool rightshift = false);
1471  llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx,
1472                             bool widen = false);
1473  llvm::Value *EmitNeonShiftVector(llvm::Value *V, const llvm::Type *Ty,
1474                                   bool negateForRightShift);
1475
1476  llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1477  llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1478
1479  llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
1480  llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
1481  llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
1482  RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
1483                             ReturnValueSlot Return = ReturnValueSlot());
1484  RValue EmitObjCPropertyGet(const Expr *E,
1485                             ReturnValueSlot Return = ReturnValueSlot());
1486  RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S,
1487                                  ReturnValueSlot Return = ReturnValueSlot());
1488  void EmitObjCPropertySet(const Expr *E, RValue Src);
1489  void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src);
1490
1491
1492  /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
1493  /// expression. Will emit a temporary variable if E is not an LValue.
1494  RValue EmitReferenceBindingToExpr(const Expr* E,
1495                                    const NamedDecl *InitializedDecl);
1496
1497  //===--------------------------------------------------------------------===//
1498  //                           Expression Emission
1499  //===--------------------------------------------------------------------===//
1500
1501  // Expressions are broken into three classes: scalar, complex, aggregate.
1502
1503  /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
1504  /// scalar type, returning the result.
1505  llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
1506
1507  /// EmitScalarConversion - Emit a conversion from the specified type to the
1508  /// specified destination type, both of which are LLVM scalar types.
1509  llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
1510                                    QualType DstTy);
1511
1512  /// EmitComplexToScalarConversion - Emit a conversion from the specified
1513  /// complex type to the specified destination type, where the destination type
1514  /// is an LLVM scalar type.
1515  llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
1516                                             QualType DstTy);
1517
1518
1519  /// EmitAggExpr - Emit the computation of the specified expression of
1520  /// aggregate type.  The result is computed into DestPtr.  Note that if
1521  /// DestPtr is null, the value of the aggregate expression is not needed.
1522  void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest,
1523                   bool IgnoreResult = false, bool IsInitializer = false,
1524                   bool RequiresGCollection = false);
1525
1526  /// EmitAggExprToLValue - Emit the computation of the specified expression of
1527  /// aggregate type into a temporary LValue.
1528  LValue EmitAggExprToLValue(const Expr *E);
1529
1530  /// EmitGCMemmoveCollectable - Emit special API for structs with object
1531  /// pointers.
1532  void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1533                                QualType Ty);
1534
1535  /// EmitComplexExpr - Emit the computation of the specified expression of
1536  /// complex type, returning the result.
1537  ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false,
1538                                bool IgnoreImag = false,
1539                                bool IgnoreRealAssign = false,
1540                                bool IgnoreImagAssign = false);
1541
1542  /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
1543  /// of complex type, storing into the specified Value*.
1544  void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
1545                               bool DestIsVolatile);
1546
1547  /// StoreComplexToAddr - Store a complex number into the specified address.
1548  void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
1549                          bool DestIsVolatile);
1550  /// LoadComplexFromAddr - Load a complex number from the specified address.
1551  ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
1552
1553  /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global for a
1554  /// static block var decl.
1555  llvm::GlobalVariable *CreateStaticBlockVarDecl(const VarDecl &D,
1556                                                 const char *Separator,
1557                                       llvm::GlobalValue::LinkageTypes Linkage);
1558
1559  /// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the
1560  /// global variable that has already been created for it.  If the initializer
1561  /// has a different type than GV does, this may free GV and return a different
1562  /// one.  Otherwise it just returns GV.
1563  llvm::GlobalVariable *
1564  AddInitializerToGlobalBlockVarDecl(const VarDecl &D,
1565                                     llvm::GlobalVariable *GV);
1566
1567
1568  /// EmitStaticCXXBlockVarDeclInit - Create the initializer for a C++ runtime
1569  /// initialized static block var decl.
1570  void EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
1571                                     llvm::GlobalVariable *GV);
1572
1573  /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
1574  /// variable with global storage.
1575  void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr);
1576
1577  /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr
1578  /// with the C++ runtime so that its destructor will be called at exit.
1579  void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
1580                                     llvm::Constant *DeclPtr);
1581
1582  /// GenerateCXXGlobalInitFunc - Generates code for initializing global
1583  /// variables.
1584  void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
1585                                 llvm::Constant **Decls,
1586                                 unsigned NumDecls);
1587
1588  /// GenerateCXXGlobalDtorFunc - Generates code for destroying global
1589  /// variables.
1590  void GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
1591                                 const std::vector<std::pair<llvm::WeakVH,
1592                                   llvm::Constant*> > &DtorsAndObjects);
1593
1594  void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D);
1595
1596  void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E);
1597
1598  RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E,
1599                                    llvm::Value *AggLoc = 0,
1600                                    bool IsAggLocVolatile = false,
1601                                    bool IsInitializer = false);
1602
1603  void EmitCXXThrowExpr(const CXXThrowExpr *E);
1604
1605  //===--------------------------------------------------------------------===//
1606  //                             Internal Helpers
1607  //===--------------------------------------------------------------------===//
1608
1609  /// ContainsLabel - Return true if the statement contains a label in it.  If
1610  /// this statement is not executed normally, it not containing a label means
1611  /// that we can just remove the code.
1612  static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
1613
1614  /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1615  /// to a constant, or if it does but contains a label, return 0.  If it
1616  /// constant folds to 'true' and does not contain a label, return 1, if it
1617  /// constant folds to 'false' and does not contain a label, return -1.
1618  int ConstantFoldsToSimpleInteger(const Expr *Cond);
1619
1620  /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
1621  /// if statement) to the specified blocks.  Based on the condition, this might
1622  /// try to simplify the codegen of the conditional based on the branch.
1623  void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
1624                            llvm::BasicBlock *FalseBlock);
1625
1626  /// getTrapBB - Create a basic block that will call the trap intrinsic.  We'll
1627  /// generate a branch around the created basic block as necessary.
1628  llvm::BasicBlock *getTrapBB();
1629
1630  /// EmitCallArg - Emit a single call argument.
1631  RValue EmitCallArg(const Expr *E, QualType ArgType);
1632
1633  /// EmitDelegateCallArg - We are performing a delegate call; that
1634  /// is, the current function is delegating to another one.  Produce
1635  /// a r-value suitable for passing the given parameter.
1636  RValue EmitDelegateCallArg(const VarDecl *Param);
1637
1638private:
1639  void EmitReturnOfRValue(RValue RV, QualType Ty);
1640
1641  /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
1642  /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
1643  ///
1644  /// \param AI - The first function argument of the expansion.
1645  /// \return The argument following the last expanded function
1646  /// argument.
1647  llvm::Function::arg_iterator
1648  ExpandTypeFromArgs(QualType Ty, LValue Dst,
1649                     llvm::Function::arg_iterator AI);
1650
1651  /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
1652  /// Ty, into individual arguments on the provided vector \arg Args. See
1653  /// ABIArgInfo::Expand.
1654  void ExpandTypeToArgs(QualType Ty, RValue Src,
1655                        llvm::SmallVector<llvm::Value*, 16> &Args);
1656
1657  llvm::Value* EmitAsmInput(const AsmStmt &S,
1658                            const TargetInfo::ConstraintInfo &Info,
1659                            const Expr *InputExpr, std::string &ConstraintStr);
1660
1661  llvm::Value* EmitAsmInputLValue(const AsmStmt &S,
1662                                  const TargetInfo::ConstraintInfo &Info,
1663                                  LValue InputValue, QualType InputType,
1664                                  std::string &ConstraintStr);
1665
1666  /// EmitCallArgs - Emit call arguments for a function.
1667  /// The CallArgTypeInfo parameter is used for iterating over the known
1668  /// argument types of the function being called.
1669  template<typename T>
1670  void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
1671                    CallExpr::const_arg_iterator ArgBeg,
1672                    CallExpr::const_arg_iterator ArgEnd) {
1673      CallExpr::const_arg_iterator Arg = ArgBeg;
1674
1675    // First, use the argument types that the type info knows about
1676    if (CallArgTypeInfo) {
1677      for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
1678           E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
1679        assert(Arg != ArgEnd && "Running over edge of argument list!");
1680        QualType ArgType = *I;
1681
1682        assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
1683               getTypePtr() ==
1684               getContext().getCanonicalType(Arg->getType()).getTypePtr() &&
1685               "type mismatch in call argument!");
1686
1687        Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1688                                      ArgType));
1689      }
1690
1691      // Either we've emitted all the call args, or we have a call to a
1692      // variadic function.
1693      assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
1694             "Extra arguments in non-variadic function!");
1695
1696    }
1697
1698    // If we still have any arguments, emit them using the type of the argument.
1699    for (; Arg != ArgEnd; ++Arg) {
1700      QualType ArgType = Arg->getType();
1701      Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1702                                    ArgType));
1703    }
1704  }
1705
1706  const TargetCodeGenInfo &getTargetHooks() const {
1707    return CGM.getTargetCodeGenInfo();
1708  }
1709
1710  void EmitDeclMetadata();
1711};
1712
1713/// CGBlockInfo - Information to generate a block literal.
1714class CGBlockInfo {
1715public:
1716  /// Name - The name of the block, kindof.
1717  const char *Name;
1718
1719  /// DeclRefs - Variables from parent scopes that have been
1720  /// imported into this block.
1721  llvm::SmallVector<const BlockDeclRefExpr *, 8> DeclRefs;
1722
1723  /// InnerBlocks - This block and the blocks it encloses.
1724  llvm::SmallPtrSet<const DeclContext *, 4> InnerBlocks;
1725
1726  /// CXXThisRef - Non-null if 'this' was required somewhere, in
1727  /// which case this is that expression.
1728  const CXXThisExpr *CXXThisRef;
1729
1730  /// NeedsObjCSelf - True if something in this block has an implicit
1731  /// reference to 'self'.
1732  bool NeedsObjCSelf;
1733
1734  /// These are initialized by GenerateBlockFunction.
1735  bool BlockHasCopyDispose;
1736  CharUnits BlockSize;
1737  CharUnits BlockAlign;
1738  llvm::SmallVector<const Expr*, 8> BlockLayout;
1739
1740  CGBlockInfo(const char *Name);
1741};
1742
1743}  // end namespace CodeGen
1744}  // end namespace clang
1745
1746#endif
1747