1193326Sed//===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This is the internal per-function state used for llvm translation.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14193326Sed#ifndef CLANG_CODEGEN_CODEGENFUNCTION_H
15193326Sed#define CLANG_CODEGEN_CODEGENFUNCTION_H
16193326Sed
17252723Sdim#include "CGBuilder.h"
18252723Sdim#include "CGDebugInfo.h"
19252723Sdim#include "CGValue.h"
20263509Sdim#include "EHScopeStack.h"
21252723Sdim#include "CodeGenModule.h"
22252723Sdim#include "clang/AST/CharUnits.h"
23193326Sed#include "clang/AST/ExprCXX.h"
24193326Sed#include "clang/AST/ExprObjC.h"
25252723Sdim#include "clang/AST/Type.h"
26218893Sdim#include "clang/Basic/ABI.h"
27263509Sdim#include "clang/Basic/CapturedStmt.h"
28193326Sed#include "clang/Basic/TargetInfo.h"
29252723Sdim#include "clang/Frontend/CodeGenOptions.h"
30224145Sdim#include "llvm/ADT/ArrayRef.h"
31193326Sed#include "llvm/ADT/DenseMap.h"
32193326Sed#include "llvm/ADT/SmallVector.h"
33252723Sdim#include "llvm/Support/Debug.h"
34193326Sed#include "llvm/Support/ValueHandle.h"
35193326Sed
36193326Sednamespace llvm {
37193326Sed  class BasicBlock;
38198092Srdivacky  class LLVMContext;
39207619Srdivacky  class MDNode;
40193326Sed  class Module;
41193326Sed  class SwitchInst;
42198398Srdivacky  class Twine;
43193326Sed  class Value;
44210299Sed  class CallSite;
45193326Sed}
46193326Sed
47193326Sednamespace clang {
48193326Sed  class ASTContext;
49235633Sdim  class BlockDecl;
50193326Sed  class CXXDestructorDecl;
51221345Sdim  class CXXForRangeStmt;
52198092Srdivacky  class CXXTryStmt;
53193326Sed  class Decl;
54218893Sdim  class LabelDecl;
55193326Sed  class EnumConstantDecl;
56193326Sed  class FunctionDecl;
57193326Sed  class FunctionProtoType;
58193326Sed  class LabelStmt;
59193326Sed  class ObjCContainerDecl;
60193326Sed  class ObjCInterfaceDecl;
61193326Sed  class ObjCIvarDecl;
62193326Sed  class ObjCMethodDecl;
63193326Sed  class ObjCImplementationDecl;
64193326Sed  class ObjCPropertyImplDecl;
65193326Sed  class TargetInfo;
66204643Srdivacky  class TargetCodeGenInfo;
67193326Sed  class VarDecl;
68193326Sed  class ObjCForCollectionStmt;
69193326Sed  class ObjCAtTryStmt;
70193326Sed  class ObjCAtThrowStmt;
71193326Sed  class ObjCAtSynchronizedStmt;
72224145Sdim  class ObjCAutoreleasePoolStmt;
73193326Sed
74193326Sednamespace CodeGen {
75193326Sed  class CodeGenTypes;
76193326Sed  class CGFunctionInfo;
77193326Sed  class CGRecordLayout;
78208600Srdivacky  class CGBlockInfo;
79212904Sdim  class CGCXXABI;
80218893Sdim  class BlockFlags;
81218893Sdim  class BlockFieldFlags;
82193326Sed
83252723Sdim/// The kind of evaluation to perform on values of a particular
84252723Sdim/// type.  Basically, is the code in CGExprScalar, CGExprComplex, or
85252723Sdim/// CGExprAgg?
86252723Sdim///
87252723Sdim/// TODO: should vectors maybe be split out into their own thing?
88252723Sdimenum TypeEvaluationKind {
89252723Sdim  TEK_Scalar,
90252723Sdim  TEK_Complex,
91252723Sdim  TEK_Aggregate
92252723Sdim};
93252723Sdim
94193326Sed/// CodeGenFunction - This class organizes the per-function state that is used
95193326Sed/// while generating LLVM code.
96218893Sdimclass CodeGenFunction : public CodeGenTypeCache {
97245431Sdim  CodeGenFunction(const CodeGenFunction &) LLVM_DELETED_FUNCTION;
98245431Sdim  void operator=(const CodeGenFunction &) LLVM_DELETED_FUNCTION;
99212904Sdim
100212904Sdim  friend class CGCXXABI;
101193326Sedpublic:
102212904Sdim  /// A jump destination is an abstract label, branching to which may
103212904Sdim  /// require a jump out through normal cleanups.
104210299Sed  struct JumpDest {
105212904Sdim    JumpDest() : Block(0), ScopeDepth(), Index(0) {}
106212904Sdim    JumpDest(llvm::BasicBlock *Block,
107212904Sdim             EHScopeStack::stable_iterator Depth,
108212904Sdim             unsigned Index)
109212904Sdim      : Block(Block), ScopeDepth(Depth), Index(Index) {}
110212904Sdim
111212904Sdim    bool isValid() const { return Block != 0; }
112212904Sdim    llvm::BasicBlock *getBlock() const { return Block; }
113212904Sdim    EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
114212904Sdim    unsigned getDestIndex() const { return Index; }
115218893Sdim
116252723Sdim    // This should be used cautiously.
117252723Sdim    void setScopeDepth(EHScopeStack::stable_iterator depth) {
118252723Sdim      ScopeDepth = depth;
119252723Sdim    }
120252723Sdim
121212904Sdim  private:
122210299Sed    llvm::BasicBlock *Block;
123210299Sed    EHScopeStack::stable_iterator ScopeDepth;
124212904Sdim    unsigned Index;
125210299Sed  };
126210299Sed
127193326Sed  CodeGenModule &CGM;  // Per-module state.
128199482Srdivacky  const TargetInfo &Target;
129193326Sed
130193326Sed  typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
131193326Sed  CGBuilderTy Builder;
132193326Sed
133252723Sdim  /// CurFuncDecl - Holds the Decl for the current outermost
134252723Sdim  /// non-closure context.
135193326Sed  const Decl *CurFuncDecl;
136193326Sed  /// CurCodeDecl - This is the inner-most code context, which includes blocks.
137193326Sed  const Decl *CurCodeDecl;
138193326Sed  const CGFunctionInfo *CurFnInfo;
139193326Sed  QualType FnRetTy;
140193326Sed  llvm::Function *CurFn;
141193326Sed
142200583Srdivacky  /// CurGD - The GlobalDecl for the current function being compiled.
143200583Srdivacky  GlobalDecl CurGD;
144200583Srdivacky
145224145Sdim  /// PrologueCleanupDepth - The cleanup depth enclosing all the
146224145Sdim  /// cleanups associated with the parameters.
147224145Sdim  EHScopeStack::stable_iterator PrologueCleanupDepth;
148224145Sdim
149193326Sed  /// ReturnBlock - Unified return block.
150210299Sed  JumpDest ReturnBlock;
151210299Sed
152193326Sed  /// ReturnValue - The temporary alloca to hold the return value. This is null
153193326Sed  /// iff the function has no return value.
154200583Srdivacky  llvm::Value *ReturnValue;
155193326Sed
156193326Sed  /// AllocaInsertPoint - This is an instruction in the entry block before which
157193326Sed  /// we prefer to insert allocas.
158193326Sed  llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
159193326Sed
160263509Sdim  /// \brief API for captured statement code generation.
161263509Sdim  class CGCapturedStmtInfo {
162263509Sdim  public:
163263509Sdim    explicit CGCapturedStmtInfo(const CapturedStmt &S,
164263509Sdim                                CapturedRegionKind K = CR_Default)
165263509Sdim      : Kind(K), ThisValue(0), CXXThisFieldDecl(0) {
166263509Sdim
167263509Sdim      RecordDecl::field_iterator Field =
168263509Sdim        S.getCapturedRecordDecl()->field_begin();
169263509Sdim      for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
170263509Sdim                                                E = S.capture_end();
171263509Sdim           I != E; ++I, ++Field) {
172263509Sdim        if (I->capturesThis())
173263509Sdim          CXXThisFieldDecl = *Field;
174263509Sdim        else
175263509Sdim          CaptureFields[I->getCapturedVar()] = *Field;
176263509Sdim      }
177263509Sdim    }
178263509Sdim
179263509Sdim    virtual ~CGCapturedStmtInfo();
180263509Sdim
181263509Sdim    CapturedRegionKind getKind() const { return Kind; }
182263509Sdim
183263509Sdim    void setContextValue(llvm::Value *V) { ThisValue = V; }
184263509Sdim    // \brief Retrieve the value of the context parameter.
185263509Sdim    llvm::Value *getContextValue() const { return ThisValue; }
186263509Sdim
187263509Sdim    /// \brief Lookup the captured field decl for a variable.
188263509Sdim    const FieldDecl *lookup(const VarDecl *VD) const {
189263509Sdim      return CaptureFields.lookup(VD);
190263509Sdim    }
191263509Sdim
192263509Sdim    bool isCXXThisExprCaptured() const { return CXXThisFieldDecl != 0; }
193263509Sdim    FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
194263509Sdim
195263509Sdim    /// \brief Emit the captured statement body.
196263509Sdim    virtual void EmitBody(CodeGenFunction &CGF, Stmt *S) {
197263509Sdim      CGF.EmitStmt(S);
198263509Sdim    }
199263509Sdim
200263509Sdim    /// \brief Get the name of the capture helper.
201263509Sdim    virtual StringRef getHelperName() const { return "__captured_stmt"; }
202263509Sdim
203263509Sdim  private:
204263509Sdim    /// \brief The kind of captured statement being generated.
205263509Sdim    CapturedRegionKind Kind;
206263509Sdim
207263509Sdim    /// \brief Keep the map between VarDecl and FieldDecl.
208263509Sdim    llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
209263509Sdim
210263509Sdim    /// \brief The base address of the captured record, passed in as the first
211263509Sdim    /// argument of the parallel region function.
212263509Sdim    llvm::Value *ThisValue;
213263509Sdim
214263509Sdim    /// \brief Captured 'this' type.
215263509Sdim    FieldDecl *CXXThisFieldDecl;
216263509Sdim  };
217263509Sdim  CGCapturedStmtInfo *CapturedStmtInfo;
218263509Sdim
219245431Sdim  /// BoundsChecking - Emit run-time bounds checks. Higher values mean
220245431Sdim  /// potentially higher performance penalties.
221245431Sdim  unsigned char BoundsChecking;
222193326Sed
223245431Sdim  /// \brief Whether any type-checking sanitizers are enabled. If \c false,
224245431Sdim  /// calls to EmitTypeCheck can be skipped.
225245431Sdim  bool SanitizePerformTypeCheck;
226245431Sdim
227252723Sdim  /// \brief Sanitizer options to use for this function.
228252723Sdim  const SanitizerOptions *SanOpts;
229252723Sdim
230224145Sdim  /// In ARC, whether we should autorelease the return value.
231224145Sdim  bool AutoreleaseResult;
232224145Sdim
233218893Sdim  const CodeGen::CGBlockInfo *BlockInfo;
234218893Sdim  llvm::Value *BlockPointer;
235218893Sdim
236235633Sdim  llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
237235633Sdim  FieldDecl *LambdaThisCaptureField;
238235633Sdim
239208600Srdivacky  /// \brief A mapping from NRVO variables to the flags used to indicate
240208600Srdivacky  /// when the NRVO has been applied to this variable.
241208600Srdivacky  llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
242193326Sed
243210299Sed  EHScopeStack EHStack;
244263509Sdim  llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
245193326Sed
246263509Sdim  /// Header for data within LifetimeExtendedCleanupStack.
247263509Sdim  struct LifetimeExtendedCleanupHeader {
248263509Sdim    /// The size of the following cleanup object.
249263509Sdim    size_t Size : 29;
250263509Sdim    /// The kind of cleanup to push: a value from the CleanupKind enumeration.
251263509Sdim    unsigned Kind : 3;
252263509Sdim
253263509Sdim    size_t getSize() const { return Size; }
254263509Sdim    CleanupKind getKind() const { return static_cast<CleanupKind>(Kind); }
255263509Sdim  };
256263509Sdim
257212904Sdim  /// i32s containing the indexes of the cleanup destinations.
258212904Sdim  llvm::AllocaInst *NormalCleanupDest;
259212904Sdim
260212904Sdim  unsigned NextCleanupDestIndex;
261212904Sdim
262235633Sdim  /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
263235633Sdim  CGBlockInfo *FirstBlockInfo;
264235633Sdim
265226890Sdim  /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
266226890Sdim  llvm::BasicBlock *EHResumeBlock;
267226890Sdim
268226890Sdim  /// The exception slot.  All landing pads write the current exception pointer
269226890Sdim  /// into this alloca.
270210299Sed  llvm::Value *ExceptionSlot;
271193326Sed
272226890Sdim  /// The selector slot.  Under the MandatoryCleanup model, all landing pads
273226890Sdim  /// write the current selector value into this alloca.
274223017Sdim  llvm::AllocaInst *EHSelectorSlot;
275223017Sdim
276210299Sed  /// Emits a landing pad for the current EH stack.
277210299Sed  llvm::BasicBlock *EmitLandingPad();
278193326Sed
279210299Sed  llvm::BasicBlock *getInvokeDestImpl();
280193326Sed
281218893Sdim  template <class T>
282218893Sdim  typename DominatingValue<T>::saved_type saveValueInCond(T value) {
283218893Sdim    return DominatingValue<T>::save(*this, value);
284218893Sdim  }
285218893Sdim
286210299Sedpublic:
287210299Sed  /// ObjCEHValueStack - Stack of Objective-C exception values, used for
288210299Sed  /// rethrows.
289226890Sdim  SmallVector<llvm::Value*, 8> ObjCEHValueStack;
290200583Srdivacky
291224145Sdim  /// A class controlling the emission of a finally block.
292224145Sdim  class FinallyInfo {
293224145Sdim    /// Where the catchall's edge through the cleanup should go.
294224145Sdim    JumpDest RethrowDest;
295224145Sdim
296224145Sdim    /// A function to call to enter the catch.
297224145Sdim    llvm::Constant *BeginCatchFn;
298224145Sdim
299224145Sdim    /// An i1 variable indicating whether or not the @finally is
300224145Sdim    /// running for an exception.
301224145Sdim    llvm::AllocaInst *ForEHVar;
302224145Sdim
303224145Sdim    /// An i8* variable into which the exception pointer to rethrow
304224145Sdim    /// has been saved.
305224145Sdim    llvm::AllocaInst *SavedExnVar;
306224145Sdim
307224145Sdim  public:
308224145Sdim    void enter(CodeGenFunction &CGF, const Stmt *Finally,
309224145Sdim               llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
310224145Sdim               llvm::Constant *rethrowFn);
311224145Sdim    void exit(CodeGenFunction &CGF);
312193326Sed  };
313193326Sed
314218893Sdim  /// pushFullExprCleanup - Push a cleanup to be run at the end of the
315218893Sdim  /// current full-expression.  Safe against the possibility that
316218893Sdim  /// we're currently inside a conditionally-evaluated expression.
317218893Sdim  template <class T, class A0>
318218893Sdim  void pushFullExprCleanup(CleanupKind kind, A0 a0) {
319218893Sdim    // If we're not in a conditional branch, or if none of the
320218893Sdim    // arguments requires saving, then use the unconditional cleanup.
321224145Sdim    if (!isInConditionalBranch())
322224145Sdim      return EHStack.pushCleanup<T>(kind, a0);
323218893Sdim
324218893Sdim    typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
325218893Sdim
326218893Sdim    typedef EHScopeStack::ConditionalCleanup1<T, A0> CleanupType;
327218893Sdim    EHStack.pushCleanup<CleanupType>(kind, a0_saved);
328218893Sdim    initFullExprCleanup();
329218893Sdim  }
330218893Sdim
331218893Sdim  /// pushFullExprCleanup - Push a cleanup to be run at the end of the
332218893Sdim  /// current full-expression.  Safe against the possibility that
333218893Sdim  /// we're currently inside a conditionally-evaluated expression.
334218893Sdim  template <class T, class A0, class A1>
335218893Sdim  void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1) {
336218893Sdim    // If we're not in a conditional branch, or if none of the
337218893Sdim    // arguments requires saving, then use the unconditional cleanup.
338224145Sdim    if (!isInConditionalBranch())
339224145Sdim      return EHStack.pushCleanup<T>(kind, a0, a1);
340218893Sdim
341218893Sdim    typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
342218893Sdim    typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
343218893Sdim
344218893Sdim    typedef EHScopeStack::ConditionalCleanup2<T, A0, A1> CleanupType;
345218893Sdim    EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved);
346218893Sdim    initFullExprCleanup();
347218893Sdim  }
348218893Sdim
349224145Sdim  /// pushFullExprCleanup - Push a cleanup to be run at the end of the
350224145Sdim  /// current full-expression.  Safe against the possibility that
351224145Sdim  /// we're currently inside a conditionally-evaluated expression.
352224145Sdim  template <class T, class A0, class A1, class A2>
353224145Sdim  void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2) {
354224145Sdim    // If we're not in a conditional branch, or if none of the
355224145Sdim    // arguments requires saving, then use the unconditional cleanup.
356224145Sdim    if (!isInConditionalBranch()) {
357224145Sdim      return EHStack.pushCleanup<T>(kind, a0, a1, a2);
358224145Sdim    }
359224145Sdim
360224145Sdim    typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
361224145Sdim    typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
362224145Sdim    typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2);
363224145Sdim
364224145Sdim    typedef EHScopeStack::ConditionalCleanup3<T, A0, A1, A2> CleanupType;
365224145Sdim    EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, a2_saved);
366224145Sdim    initFullExprCleanup();
367224145Sdim  }
368224145Sdim
369224145Sdim  /// pushFullExprCleanup - Push a cleanup to be run at the end of the
370224145Sdim  /// current full-expression.  Safe against the possibility that
371224145Sdim  /// we're currently inside a conditionally-evaluated expression.
372224145Sdim  template <class T, class A0, class A1, class A2, class A3>
373224145Sdim  void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2, A3 a3) {
374224145Sdim    // If we're not in a conditional branch, or if none of the
375224145Sdim    // arguments requires saving, then use the unconditional cleanup.
376224145Sdim    if (!isInConditionalBranch()) {
377224145Sdim      return EHStack.pushCleanup<T>(kind, a0, a1, a2, a3);
378224145Sdim    }
379224145Sdim
380224145Sdim    typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
381224145Sdim    typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
382224145Sdim    typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2);
383224145Sdim    typename DominatingValue<A3>::saved_type a3_saved = saveValueInCond(a3);
384224145Sdim
385224145Sdim    typedef EHScopeStack::ConditionalCleanup4<T, A0, A1, A2, A3> CleanupType;
386224145Sdim    EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved,
387224145Sdim                                     a2_saved, a3_saved);
388224145Sdim    initFullExprCleanup();
389224145Sdim  }
390224145Sdim
391263509Sdim  /// \brief Queue a cleanup to be pushed after finishing the current
392263509Sdim  /// full-expression.
393263509Sdim  template <class T, class A0, class A1, class A2, class A3>
394263509Sdim  void pushCleanupAfterFullExpr(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) {
395263509Sdim    assert(!isInConditionalBranch() && "can't defer conditional cleanup");
396263509Sdim
397263509Sdim    LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind };
398263509Sdim
399263509Sdim    size_t OldSize = LifetimeExtendedCleanupStack.size();
400263509Sdim    LifetimeExtendedCleanupStack.resize(
401263509Sdim        LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size);
402263509Sdim
403263509Sdim    char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
404263509Sdim    new (Buffer) LifetimeExtendedCleanupHeader(Header);
405263509Sdim    new (Buffer + sizeof(Header)) T(a0, a1, a2, a3);
406263509Sdim  }
407263509Sdim
408235633Sdim  /// Set up the last cleaup that was pushed as a conditional
409235633Sdim  /// full-expression cleanup.
410235633Sdim  void initFullExprCleanup();
411235633Sdim
412210299Sed  /// PushDestructorCleanup - Push a cleanup to call the
413210299Sed  /// complete-object destructor of an object of the given type at the
414210299Sed  /// given address.  Does nothing if T is not a C++ class type with a
415210299Sed  /// non-trivial destructor.
416210299Sed  void PushDestructorCleanup(QualType T, llvm::Value *Addr);
417193326Sed
418212904Sdim  /// PushDestructorCleanup - Push a cleanup to call the
419212904Sdim  /// complete-object variant of the given destructor on the object at
420212904Sdim  /// the given address.
421212904Sdim  void PushDestructorCleanup(const CXXDestructorDecl *Dtor,
422212904Sdim                             llvm::Value *Addr);
423212904Sdim
424210299Sed  /// PopCleanupBlock - Will pop the cleanup entry on the stack and
425210299Sed  /// process all branch fixups.
426263509Sdim  void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
427210299Sed
428218893Sdim  /// DeactivateCleanupBlock - Deactivates the given cleanup block.
429218893Sdim  /// The block cannot be reactivated.  Pops it if it's the top of the
430218893Sdim  /// stack.
431235633Sdim  ///
432235633Sdim  /// \param DominatingIP - An instruction which is known to
433235633Sdim  ///   dominate the current IP (if set) and which lies along
434235633Sdim  ///   all paths of execution between the current IP and the
435235633Sdim  ///   the point at which the cleanup comes into scope.
436235633Sdim  void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
437235633Sdim                              llvm::Instruction *DominatingIP);
438193326Sed
439218893Sdim  /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
440218893Sdim  /// Cannot be used to resurrect a deactivated cleanup.
441235633Sdim  ///
442235633Sdim  /// \param DominatingIP - An instruction which is known to
443235633Sdim  ///   dominate the current IP (if set) and which lies along
444235633Sdim  ///   all paths of execution between the current IP and the
445235633Sdim  ///   the point at which the cleanup comes into scope.
446235633Sdim  void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
447235633Sdim                            llvm::Instruction *DominatingIP);
448218893Sdim
449210299Sed  /// \brief Enters a new scope for capturing cleanups, all of which
450210299Sed  /// will be executed once the scope is exited.
451210299Sed  class RunCleanupsScope {
452210299Sed    EHScopeStack::stable_iterator CleanupStackDepth;
453263509Sdim    size_t LifetimeExtendedCleanupStackSize;
454199990Srdivacky    bool OldDidCallStackSave;
455252723Sdim  protected:
456199990Srdivacky    bool PerformCleanup;
457252723Sdim  private:
458199990Srdivacky
459245431Sdim    RunCleanupsScope(const RunCleanupsScope &) LLVM_DELETED_FUNCTION;
460245431Sdim    void operator=(const RunCleanupsScope &) LLVM_DELETED_FUNCTION;
461199990Srdivacky
462235633Sdim  protected:
463235633Sdim    CodeGenFunction& CGF;
464252723Sdim
465199990Srdivacky  public:
466199990Srdivacky    /// \brief Enter a new cleanup scope.
467218893Sdim    explicit RunCleanupsScope(CodeGenFunction &CGF)
468235633Sdim      : PerformCleanup(true), CGF(CGF)
469199990Srdivacky    {
470210299Sed      CleanupStackDepth = CGF.EHStack.stable_begin();
471263509Sdim      LifetimeExtendedCleanupStackSize =
472263509Sdim          CGF.LifetimeExtendedCleanupStack.size();
473199990Srdivacky      OldDidCallStackSave = CGF.DidCallStackSave;
474218893Sdim      CGF.DidCallStackSave = false;
475199990Srdivacky    }
476199990Srdivacky
477199990Srdivacky    /// \brief Exit this cleanup scope, emitting any accumulated
478199990Srdivacky    /// cleanups.
479210299Sed    ~RunCleanupsScope() {
480199990Srdivacky      if (PerformCleanup) {
481199990Srdivacky        CGF.DidCallStackSave = OldDidCallStackSave;
482263509Sdim        CGF.PopCleanupBlocks(CleanupStackDepth,
483263509Sdim                             LifetimeExtendedCleanupStackSize);
484199990Srdivacky      }
485199990Srdivacky    }
486199990Srdivacky
487199990Srdivacky    /// \brief Determine whether this scope requires any cleanups.
488199990Srdivacky    bool requiresCleanups() const {
489210299Sed      return CGF.EHStack.stable_begin() != CleanupStackDepth;
490199990Srdivacky    }
491199990Srdivacky
492199990Srdivacky    /// \brief Force the emission of cleanups now, instead of waiting
493199990Srdivacky    /// until this object is destroyed.
494199990Srdivacky    void ForceCleanup() {
495199990Srdivacky      assert(PerformCleanup && "Already forced cleanup");
496199990Srdivacky      CGF.DidCallStackSave = OldDidCallStackSave;
497263509Sdim      CGF.PopCleanupBlocks(CleanupStackDepth,
498263509Sdim                           LifetimeExtendedCleanupStackSize);
499199990Srdivacky      PerformCleanup = false;
500199990Srdivacky    }
501199990Srdivacky  };
502199990Srdivacky
503235633Sdim  class LexicalScope: protected RunCleanupsScope {
504235633Sdim    SourceRange Range;
505252723Sdim    SmallVector<const LabelDecl*, 4> Labels;
506252723Sdim    LexicalScope *ParentScope;
507206084Srdivacky
508245431Sdim    LexicalScope(const LexicalScope &) LLVM_DELETED_FUNCTION;
509245431Sdim    void operator=(const LexicalScope &) LLVM_DELETED_FUNCTION;
510235633Sdim
511235633Sdim  public:
512235633Sdim    /// \brief Enter a new cleanup scope.
513235633Sdim    explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
514252723Sdim      : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
515252723Sdim      CGF.CurLexicalScope = this;
516235633Sdim      if (CGDebugInfo *DI = CGF.getDebugInfo())
517235633Sdim        DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
518235633Sdim    }
519235633Sdim
520252723Sdim    void addLabel(const LabelDecl *label) {
521252723Sdim      assert(PerformCleanup && "adding label to dead scope?");
522252723Sdim      Labels.push_back(label);
523252723Sdim    }
524252723Sdim
525235633Sdim    /// \brief Exit this cleanup scope, emitting any accumulated
526235633Sdim    /// cleanups.
527235633Sdim    ~LexicalScope() {
528252723Sdim      if (CGDebugInfo *DI = CGF.getDebugInfo())
529252723Sdim        DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
530252723Sdim
531252723Sdim      // If we should perform a cleanup, force them now.  Note that
532252723Sdim      // this ends the cleanup scope before rescoping any labels.
533252723Sdim      if (PerformCleanup) ForceCleanup();
534235633Sdim    }
535235633Sdim
536235633Sdim    /// \brief Force the emission of cleanups now, instead of waiting
537235633Sdim    /// until this object is destroyed.
538235633Sdim    void ForceCleanup() {
539252723Sdim      CGF.CurLexicalScope = ParentScope;
540235633Sdim      RunCleanupsScope::ForceCleanup();
541252723Sdim
542252723Sdim      if (!Labels.empty())
543252723Sdim        rescopeLabels();
544235633Sdim    }
545252723Sdim
546252723Sdim    void rescopeLabels();
547235633Sdim  };
548235633Sdim
549235633Sdim
550263509Sdim  /// \brief Takes the old cleanup stack size and emits the cleanup blocks
551263509Sdim  /// that have been added.
552263509Sdim  void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
553263509Sdim
554263509Sdim  /// \brief Takes the old cleanup stack size and emits the cleanup blocks
555263509Sdim  /// that have been added, then adds all lifetime-extended cleanups from
556263509Sdim  /// the given position to the stack.
557252723Sdim  void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
558263509Sdim                        size_t OldLifetimeExtendedStackSize);
559206084Srdivacky
560212904Sdim  void ResolveBranchFixups(llvm::BasicBlock *Target);
561212904Sdim
562210299Sed  /// The given basic block lies in the current EH scope, but may be a
563210299Sed  /// target of a potentially scope-crossing jump; get a stable handle
564210299Sed  /// to which we can perform this jump later.
565212904Sdim  JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
566212904Sdim    return JumpDest(Target,
567212904Sdim                    EHStack.getInnermostNormalCleanup(),
568212904Sdim                    NextCleanupDestIndex++);
569210299Sed  }
570193326Sed
571210299Sed  /// The given basic block lies in the current EH scope, but may be a
572210299Sed  /// target of a potentially scope-crossing jump; get a stable handle
573210299Sed  /// to which we can perform this jump later.
574226890Sdim  JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
575212904Sdim    return getJumpDestInCurrentScope(createBasicBlock(Name));
576210299Sed  }
577193326Sed
578210299Sed  /// EmitBranchThroughCleanup - Emit a branch from the current insert
579210299Sed  /// block through the normal cleanup handling code (if any) and then
580210299Sed  /// on to \arg Dest.
581210299Sed  void EmitBranchThroughCleanup(JumpDest Dest);
582221345Sdim
583221345Sdim  /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
584221345Sdim  /// specified destination obviously has no cleanups to run.  'false' is always
585221345Sdim  /// a conservatively correct answer for this method.
586221345Sdim  bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
587210299Sed
588226890Sdim  /// popCatchScope - Pops the catch scope at the top of the EHScope
589226890Sdim  /// stack, emitting any required code (other than the catch handlers
590226890Sdim  /// themselves).
591226890Sdim  void popCatchScope();
592210299Sed
593245431Sdim  llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
594226890Sdim  llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
595212904Sdim
596218893Sdim  /// An object to manage conditionally-evaluated expressions.
597218893Sdim  class ConditionalEvaluation {
598218893Sdim    llvm::BasicBlock *StartBB;
599198092Srdivacky
600218893Sdim  public:
601218893Sdim    ConditionalEvaluation(CodeGenFunction &CGF)
602218893Sdim      : StartBB(CGF.Builder.GetInsertBlock()) {}
603198092Srdivacky
604218893Sdim    void begin(CodeGenFunction &CGF) {
605218893Sdim      assert(CGF.OutermostConditional != this);
606218893Sdim      if (!CGF.OutermostConditional)
607218893Sdim        CGF.OutermostConditional = this;
608218893Sdim    }
609218893Sdim
610218893Sdim    void end(CodeGenFunction &CGF) {
611218893Sdim      assert(CGF.OutermostConditional != 0);
612218893Sdim      if (CGF.OutermostConditional == this)
613218893Sdim        CGF.OutermostConditional = 0;
614218893Sdim    }
615218893Sdim
616218893Sdim    /// Returns a block which will be executed prior to each
617218893Sdim    /// evaluation of the conditional code.
618218893Sdim    llvm::BasicBlock *getStartingBlock() const {
619218893Sdim      return StartBB;
620218893Sdim    }
621218893Sdim  };
622218893Sdim
623218893Sdim  /// isInConditionalBranch - Return true if we're currently emitting
624218893Sdim  /// one branch or the other of a conditional expression.
625218893Sdim  bool isInConditionalBranch() const { return OutermostConditional != 0; }
626218893Sdim
627235633Sdim  void setBeforeOutermostConditional(llvm::Value *value, llvm::Value *addr) {
628235633Sdim    assert(isInConditionalBranch());
629235633Sdim    llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
630235633Sdim    new llvm::StoreInst(value, addr, &block->back());
631235633Sdim  }
632235633Sdim
633218893Sdim  /// An RAII object to record that we're evaluating a statement
634218893Sdim  /// expression.
635218893Sdim  class StmtExprEvaluation {
636218893Sdim    CodeGenFunction &CGF;
637218893Sdim
638218893Sdim    /// We have to save the outermost conditional: cleanups in a
639218893Sdim    /// statement expression aren't conditional just because the
640218893Sdim    /// StmtExpr is.
641218893Sdim    ConditionalEvaluation *SavedOutermostConditional;
642218893Sdim
643218893Sdim  public:
644218893Sdim    StmtExprEvaluation(CodeGenFunction &CGF)
645218893Sdim      : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
646218893Sdim      CGF.OutermostConditional = 0;
647218893Sdim    }
648218893Sdim
649218893Sdim    ~StmtExprEvaluation() {
650218893Sdim      CGF.OutermostConditional = SavedOutermostConditional;
651218893Sdim      CGF.EnsureInsertPoint();
652218893Sdim    }
653218893Sdim  };
654218893Sdim
655218893Sdim  /// An object which temporarily prevents a value from being
656218893Sdim  /// destroyed by aggressive peephole optimizations that assume that
657218893Sdim  /// all uses of a value have been realized in the IR.
658218893Sdim  class PeepholeProtection {
659218893Sdim    llvm::Instruction *Inst;
660218893Sdim    friend class CodeGenFunction;
661218893Sdim
662218893Sdim  public:
663218893Sdim    PeepholeProtection() : Inst(0) {}
664235633Sdim  };
665218893Sdim
666235633Sdim  /// A non-RAII class containing all the information about a bound
667235633Sdim  /// opaque value.  OpaqueValueMapping, below, is a RAII wrapper for
668235633Sdim  /// this which makes individual mappings very simple; using this
669235633Sdim  /// class directly is useful when you have a variable number of
670235633Sdim  /// opaque values or don't want the RAII functionality for some
671235633Sdim  /// reason.
672235633Sdim  class OpaqueValueMappingData {
673218893Sdim    const OpaqueValueExpr *OpaqueValue;
674218893Sdim    bool BoundLValue;
675218893Sdim    CodeGenFunction::PeepholeProtection Protection;
676218893Sdim
677235633Sdim    OpaqueValueMappingData(const OpaqueValueExpr *ov,
678235633Sdim                           bool boundLValue)
679235633Sdim      : OpaqueValue(ov), BoundLValue(boundLValue) {}
680218893Sdim  public:
681235633Sdim    OpaqueValueMappingData() : OpaqueValue(0) {}
682235633Sdim
683218893Sdim    static bool shouldBindAsLValue(const Expr *expr) {
684235633Sdim      // gl-values should be bound as l-values for obvious reasons.
685235633Sdim      // Records should be bound as l-values because IR generation
686235633Sdim      // always keeps them in memory.  Expressions of function type
687235633Sdim      // act exactly like l-values but are formally required to be
688235633Sdim      // r-values in C.
689235633Sdim      return expr->isGLValue() ||
690235633Sdim             expr->getType()->isRecordType() ||
691235633Sdim             expr->getType()->isFunctionType();
692218893Sdim    }
693218893Sdim
694235633Sdim    static OpaqueValueMappingData bind(CodeGenFunction &CGF,
695235633Sdim                                       const OpaqueValueExpr *ov,
696235633Sdim                                       const Expr *e) {
697235633Sdim      if (shouldBindAsLValue(ov))
698235633Sdim        return bind(CGF, ov, CGF.EmitLValue(e));
699235633Sdim      return bind(CGF, ov, CGF.EmitAnyExpr(e));
700235633Sdim    }
701235633Sdim
702235633Sdim    static OpaqueValueMappingData bind(CodeGenFunction &CGF,
703235633Sdim                                       const OpaqueValueExpr *ov,
704235633Sdim                                       const LValue &lv) {
705235633Sdim      assert(shouldBindAsLValue(ov));
706235633Sdim      CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
707235633Sdim      return OpaqueValueMappingData(ov, true);
708235633Sdim    }
709235633Sdim
710235633Sdim    static OpaqueValueMappingData bind(CodeGenFunction &CGF,
711235633Sdim                                       const OpaqueValueExpr *ov,
712235633Sdim                                       const RValue &rv) {
713235633Sdim      assert(!shouldBindAsLValue(ov));
714235633Sdim      CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
715235633Sdim
716235633Sdim      OpaqueValueMappingData data(ov, false);
717235633Sdim
718235633Sdim      // Work around an extremely aggressive peephole optimization in
719235633Sdim      // EmitScalarConversion which assumes that all other uses of a
720235633Sdim      // value are extant.
721235633Sdim      data.Protection = CGF.protectFromPeepholes(rv);
722235633Sdim
723235633Sdim      return data;
724235633Sdim    }
725235633Sdim
726235633Sdim    bool isValid() const { return OpaqueValue != 0; }
727235633Sdim    void clear() { OpaqueValue = 0; }
728235633Sdim
729235633Sdim    void unbind(CodeGenFunction &CGF) {
730235633Sdim      assert(OpaqueValue && "no data to unbind!");
731235633Sdim
732235633Sdim      if (BoundLValue) {
733235633Sdim        CGF.OpaqueLValues.erase(OpaqueValue);
734235633Sdim      } else {
735235633Sdim        CGF.OpaqueRValues.erase(OpaqueValue);
736235633Sdim        CGF.unprotectFromPeepholes(Protection);
737235633Sdim      }
738235633Sdim    }
739235633Sdim  };
740235633Sdim
741235633Sdim  /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
742235633Sdim  class OpaqueValueMapping {
743235633Sdim    CodeGenFunction &CGF;
744235633Sdim    OpaqueValueMappingData Data;
745235633Sdim
746235633Sdim  public:
747235633Sdim    static bool shouldBindAsLValue(const Expr *expr) {
748235633Sdim      return OpaqueValueMappingData::shouldBindAsLValue(expr);
749235633Sdim    }
750235633Sdim
751218893Sdim    /// Build the opaque value mapping for the given conditional
752218893Sdim    /// operator if it's the GNU ?: extension.  This is a common
753218893Sdim    /// enough pattern that the convenience operator is really
754218893Sdim    /// helpful.
755218893Sdim    ///
756218893Sdim    OpaqueValueMapping(CodeGenFunction &CGF,
757218893Sdim                       const AbstractConditionalOperator *op) : CGF(CGF) {
758235633Sdim      if (isa<ConditionalOperator>(op))
759235633Sdim        // Leave Data empty.
760218893Sdim        return;
761218893Sdim
762218893Sdim      const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
763235633Sdim      Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
764235633Sdim                                          e->getCommon());
765218893Sdim    }
766218893Sdim
767218893Sdim    OpaqueValueMapping(CodeGenFunction &CGF,
768218893Sdim                       const OpaqueValueExpr *opaqueValue,
769218893Sdim                       LValue lvalue)
770235633Sdim      : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
771218893Sdim    }
772218893Sdim
773218893Sdim    OpaqueValueMapping(CodeGenFunction &CGF,
774218893Sdim                       const OpaqueValueExpr *opaqueValue,
775218893Sdim                       RValue rvalue)
776235633Sdim      : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
777218893Sdim    }
778218893Sdim
779218893Sdim    void pop() {
780235633Sdim      Data.unbind(CGF);
781235633Sdim      Data.clear();
782218893Sdim    }
783218893Sdim
784218893Sdim    ~OpaqueValueMapping() {
785235633Sdim      if (Data.isValid()) Data.unbind(CGF);
786218893Sdim    }
787218893Sdim  };
788218893Sdim
789218893Sdim  /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
790218893Sdim  /// number that holds the value.
791218893Sdim  unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
792218893Sdim
793218893Sdim  /// BuildBlockByrefAddress - Computes address location of the
794218893Sdim  /// variable which is declared as __block.
795218893Sdim  llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr,
796218893Sdim                                      const VarDecl *V);
797193326Sedprivate:
798198893Srdivacky  CGDebugInfo *DebugInfo;
799221345Sdim  bool DisableDebugInfo;
800193326Sed
801223017Sdim  /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
802223017Sdim  /// calling llvm.stacksave for multiple VLAs in the same scope.
803223017Sdim  bool DidCallStackSave;
804223017Sdim
805199990Srdivacky  /// IndirectBranch - The first time an indirect goto is seen we create a block
806199990Srdivacky  /// with an indirect branch.  Every time we see the address of a label taken,
807199990Srdivacky  /// we add the label to the indirect goto.  Every subsequent indirect goto is
808199990Srdivacky  /// codegen'd as a jump to the IndirectBranch's basic block.
809198893Srdivacky  llvm::IndirectBrInst *IndirectBranch;
810193326Sed
811193326Sed  /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
812193326Sed  /// decls.
813218893Sdim  typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy;
814218893Sdim  DeclMapTy LocalDeclMap;
815193326Sed
816193326Sed  /// LabelMap - This keeps track of the LLVM basic block for each C label.
817218893Sdim  llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
818193326Sed
819193326Sed  // BreakContinueStack - This keeps track of where break and continue
820193326Sed  // statements should jump to.
821193326Sed  struct BreakContinue {
822210299Sed    BreakContinue(JumpDest Break, JumpDest Continue)
823210299Sed      : BreakBlock(Break), ContinueBlock(Continue) {}
824193326Sed
825210299Sed    JumpDest BreakBlock;
826210299Sed    JumpDest ContinueBlock;
827193326Sed  };
828226890Sdim  SmallVector<BreakContinue, 8> BreakContinueStack;
829193326Sed
830235633Sdim  /// SwitchInsn - This is nearest current switch instruction. It is null if
831193326Sed  /// current context is not in a switch.
832193326Sed  llvm::SwitchInst *SwitchInsn;
833193326Sed
834193326Sed  /// CaseRangeBlock - This block holds if condition check for last case
835193326Sed  /// statement range in current switch instruction.
836193326Sed  llvm::BasicBlock *CaseRangeBlock;
837193326Sed
838218893Sdim  /// OpaqueLValues - Keeps track of the current set of opaque value
839218893Sdim  /// expressions.
840218893Sdim  llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
841218893Sdim  llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
842218893Sdim
843193326Sed  // VLASizeMap - This keeps track of the associated size for each VLA type.
844198092Srdivacky  // We track this by the size expression rather than the type itself because
845198092Srdivacky  // in certain situations, like a const qualifier applied to an VLA typedef,
846198092Srdivacky  // multiple VLA types can share the same size expression.
847193326Sed  // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
848193326Sed  // enter/leave scopes.
849198092Srdivacky  llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
850193326Sed
851210299Sed  /// A block containing a single 'unreachable' instruction.  Created
852210299Sed  /// lazily by getUnreachableBlock().
853210299Sed  llvm::BasicBlock *UnreachableBlock;
854193326Sed
855252723Sdim  /// Counts of the number return expressions in the function.
856252723Sdim  unsigned NumReturnExprs;
857252723Sdim
858252723Sdim  /// Count the number of simple (constant) return expressions in the function.
859252723Sdim  unsigned NumSimpleReturnExprs;
860252723Sdim
861252723Sdim  /// The last regular (non-return) debug location (breakpoint) in the function.
862252723Sdim  SourceLocation LastStopPoint;
863252723Sdim
864252723Sdimpublic:
865252723Sdim  /// A scope within which we are constructing the fields of an object which
866252723Sdim  /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
867252723Sdim  /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
868252723Sdim  class FieldConstructionScope {
869252723Sdim  public:
870252723Sdim    FieldConstructionScope(CodeGenFunction &CGF, llvm::Value *This)
871252723Sdim        : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
872252723Sdim      CGF.CXXDefaultInitExprThis = This;
873252723Sdim    }
874252723Sdim    ~FieldConstructionScope() {
875252723Sdim      CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
876252723Sdim    }
877252723Sdim
878252723Sdim  private:
879252723Sdim    CodeGenFunction &CGF;
880252723Sdim    llvm::Value *OldCXXDefaultInitExprThis;
881252723Sdim  };
882252723Sdim
883252723Sdim  /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
884252723Sdim  /// is overridden to be the object under construction.
885252723Sdim  class CXXDefaultInitExprScope {
886252723Sdim  public:
887252723Sdim    CXXDefaultInitExprScope(CodeGenFunction &CGF)
888252723Sdim        : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue) {
889252723Sdim      CGF.CXXThisValue = CGF.CXXDefaultInitExprThis;
890252723Sdim    }
891252723Sdim    ~CXXDefaultInitExprScope() {
892252723Sdim      CGF.CXXThisValue = OldCXXThisValue;
893252723Sdim    }
894252723Sdim
895252723Sdim  public:
896252723Sdim    CodeGenFunction &CGF;
897252723Sdim    llvm::Value *OldCXXThisValue;
898252723Sdim  };
899252723Sdim
900252723Sdimprivate:
901199990Srdivacky  /// CXXThisDecl - When generating code for a C++ member function,
902199990Srdivacky  /// this will hold the implicit 'this' declaration.
903235633Sdim  ImplicitParamDecl *CXXABIThisDecl;
904235633Sdim  llvm::Value *CXXABIThisValue;
905204643Srdivacky  llvm::Value *CXXThisValue;
906198092Srdivacky
907252723Sdim  /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
908252723Sdim  /// this expression.
909252723Sdim  llvm::Value *CXXDefaultInitExprThis;
910198092Srdivacky
911252723Sdim  /// CXXStructorImplicitParamDecl - When generating code for a constructor or
912252723Sdim  /// destructor, this will hold the implicit argument (e.g. VTT).
913252723Sdim  ImplicitParamDecl *CXXStructorImplicitParamDecl;
914252723Sdim  llvm::Value *CXXStructorImplicitParamValue;
915252723Sdim
916218893Sdim  /// OutermostConditional - Points to the outermost active
917218893Sdim  /// conditional control.  This is used so that we know if a
918218893Sdim  /// temporary should be destroyed conditionally.
919218893Sdim  ConditionalEvaluation *OutermostConditional;
920198092Srdivacky
921252723Sdim  /// The current lexical scope.
922252723Sdim  LexicalScope *CurLexicalScope;
923218893Sdim
924263509Sdim  /// The current source location that should be used for exception
925263509Sdim  /// handling code.
926263509Sdim  SourceLocation CurEHLocation;
927263509Sdim
928198092Srdivacky  /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
929198092Srdivacky  /// type as well as the field number that contains the actual data.
930226890Sdim  llvm::DenseMap<const ValueDecl *, std::pair<llvm::Type *,
931198092Srdivacky                                              unsigned> > ByRefValueInfo;
932200583Srdivacky
933210299Sed  llvm::BasicBlock *TerminateLandingPad;
934200583Srdivacky  llvm::BasicBlock *TerminateHandler;
935200583Srdivacky  llvm::BasicBlock *TrapBB;
936200583Srdivacky
937245431Sdim  /// Add a kernel metadata node to the named metadata node 'opencl.kernels'.
938245431Sdim  /// In the kernel metadata node, reference the kernel function and metadata
939245431Sdim  /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2):
940252723Sdim  /// - A node for the vec_type_hint(<type>) qualifier contains string
941252723Sdim  ///   "vec_type_hint", an undefined value of the <type> data type,
942252723Sdim  ///   and a Boolean that is true if the <type> is integer and signed.
943245431Sdim  /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string
944245431Sdim  ///   "work_group_size_hint", and three 32-bit integers X, Y and Z.
945245431Sdim  /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string
946245431Sdim  ///   "reqd_work_group_size", and three 32-bit integers X, Y and Z.
947245431Sdim  void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
948245431Sdim                                llvm::Function *Fn);
949245431Sdim
950193326Sedpublic:
951245431Sdim  CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
952235633Sdim  ~CodeGenFunction();
953193326Sed
954212904Sdim  CodeGenTypes &getTypes() const { return CGM.getTypes(); }
955223017Sdim  ASTContext &getContext() const { return CGM.getContext(); }
956221345Sdim  CGDebugInfo *getDebugInfo() {
957221345Sdim    if (DisableDebugInfo)
958221345Sdim      return NULL;
959221345Sdim    return DebugInfo;
960221345Sdim  }
961221345Sdim  void disableDebugInfo() { DisableDebugInfo = true; }
962221345Sdim  void enableDebugInfo() { DisableDebugInfo = false; }
963193326Sed
964224145Sdim  bool shouldUseFusedARCCalls() {
965224145Sdim    return CGM.getCodeGenOpts().OptimizationLevel == 0;
966224145Sdim  }
967221345Sdim
968235633Sdim  const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
969218893Sdim
970226890Sdim  /// Returns a pointer to the function's exception object and selector slot,
971226890Sdim  /// which is assigned in every landing pad.
972210299Sed  llvm::Value *getExceptionSlot();
973223017Sdim  llvm::Value *getEHSelectorSlot();
974193326Sed
975226890Sdim  /// Returns the contents of the function's exception object and selector
976226890Sdim  /// slots.
977226890Sdim  llvm::Value *getExceptionFromSlot();
978226890Sdim  llvm::Value *getSelectorFromSlot();
979226890Sdim
980212904Sdim  llvm::Value *getNormalCleanupDestSlot();
981212904Sdim
982210299Sed  llvm::BasicBlock *getUnreachableBlock() {
983210299Sed    if (!UnreachableBlock) {
984210299Sed      UnreachableBlock = createBasicBlock("unreachable");
985210299Sed      new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
986210299Sed    }
987210299Sed    return UnreachableBlock;
988210299Sed  }
989210299Sed
990210299Sed  llvm::BasicBlock *getInvokeDest() {
991210299Sed    if (!EHStack.requiresLandingPad()) return 0;
992210299Sed    return getInvokeDestImpl();
993210299Sed  }
994210299Sed
995252723Sdim  const TargetInfo &getTarget() const { return Target; }
996218893Sdim  llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
997198092Srdivacky
998193326Sed  //===--------------------------------------------------------------------===//
999224145Sdim  //                                  Cleanups
1000224145Sdim  //===--------------------------------------------------------------------===//
1001224145Sdim
1002224145Sdim  typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty);
1003224145Sdim
1004224145Sdim  void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1005224145Sdim                                        llvm::Value *arrayEndPointer,
1006224145Sdim                                        QualType elementType,
1007235633Sdim                                        Destroyer *destroyer);
1008224145Sdim  void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1009224145Sdim                                      llvm::Value *arrayEnd,
1010224145Sdim                                      QualType elementType,
1011235633Sdim                                      Destroyer *destroyer);
1012224145Sdim
1013224145Sdim  void pushDestroy(QualType::DestructionKind dtorKind,
1014224145Sdim                   llvm::Value *addr, QualType type);
1015252723Sdim  void pushEHDestroy(QualType::DestructionKind dtorKind,
1016252723Sdim                     llvm::Value *addr, QualType type);
1017224145Sdim  void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type,
1018235633Sdim                   Destroyer *destroyer, bool useEHCleanupForArray);
1019263509Sdim  void pushLifetimeExtendedDestroy(CleanupKind kind, llvm::Value *addr,
1020263509Sdim                                   QualType type, Destroyer *destroyer,
1021263509Sdim                                   bool useEHCleanupForArray);
1022235633Sdim  void emitDestroy(llvm::Value *addr, QualType type, Destroyer *destroyer,
1023224145Sdim                   bool useEHCleanupForArray);
1024263509Sdim  llvm::Function *generateDestroyHelper(llvm::Constant *addr, QualType type,
1025235633Sdim                                        Destroyer *destroyer,
1026263509Sdim                                        bool useEHCleanupForArray,
1027263509Sdim                                        const VarDecl *VD);
1028224145Sdim  void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
1029235633Sdim                        QualType type, Destroyer *destroyer,
1030224145Sdim                        bool checkZeroLength, bool useEHCleanup);
1031224145Sdim
1032235633Sdim  Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
1033224145Sdim
1034224145Sdim  /// Determines whether an EH cleanup is required to destroy a type
1035224145Sdim  /// with the given destruction kind.
1036224145Sdim  bool needsEHCleanup(QualType::DestructionKind kind) {
1037224145Sdim    switch (kind) {
1038224145Sdim    case QualType::DK_none:
1039224145Sdim      return false;
1040224145Sdim    case QualType::DK_cxx_destructor:
1041224145Sdim    case QualType::DK_objc_weak_lifetime:
1042235633Sdim      return getLangOpts().Exceptions;
1043224145Sdim    case QualType::DK_objc_strong_lifetime:
1044235633Sdim      return getLangOpts().Exceptions &&
1045224145Sdim             CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
1046224145Sdim    }
1047224145Sdim    llvm_unreachable("bad destruction kind");
1048224145Sdim  }
1049224145Sdim
1050224145Sdim  CleanupKind getCleanupKind(QualType::DestructionKind kind) {
1051224145Sdim    return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
1052224145Sdim  }
1053224145Sdim
1054224145Sdim  //===--------------------------------------------------------------------===//
1055193326Sed  //                                  Objective-C
1056193326Sed  //===--------------------------------------------------------------------===//
1057193326Sed
1058193326Sed  void GenerateObjCMethod(const ObjCMethodDecl *OMD);
1059193326Sed
1060193326Sed  void StartObjCMethod(const ObjCMethodDecl *MD,
1061223017Sdim                       const ObjCContainerDecl *CD,
1062223017Sdim                       SourceLocation StartLoc);
1063193326Sed
1064193326Sed  /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
1065193326Sed  void GenerateObjCGetter(ObjCImplementationDecl *IMP,
1066193326Sed                          const ObjCPropertyImplDecl *PID);
1067226890Sdim  void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1068235633Sdim                              const ObjCPropertyImplDecl *propImpl,
1069245431Sdim                              const ObjCMethodDecl *GetterMothodDecl,
1070235633Sdim                              llvm::Constant *AtomicHelperFn);
1071218893Sdim
1072207619Srdivacky  void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1073207619Srdivacky                                  ObjCMethodDecl *MD, bool ctor);
1074193326Sed
1075193326Sed  /// GenerateObjCSetter - Synthesize an Objective-C property setter function
1076193326Sed  /// for the given property.
1077193326Sed  void GenerateObjCSetter(ObjCImplementationDecl *IMP,
1078193326Sed                          const ObjCPropertyImplDecl *PID);
1079226890Sdim  void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1080235633Sdim                              const ObjCPropertyImplDecl *propImpl,
1081235633Sdim                              llvm::Constant *AtomicHelperFn);
1082207619Srdivacky  bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
1083207619Srdivacky  bool IvarTypeWithAggrGCObjects(QualType Ty);
1084193326Sed
1085193326Sed  //===--------------------------------------------------------------------===//
1086193326Sed  //                                  Block Bits
1087193326Sed  //===--------------------------------------------------------------------===//
1088193326Sed
1089218893Sdim  llvm::Value *EmitBlockLiteral(const BlockExpr *);
1090235633Sdim  llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
1091235633Sdim  static void destroyBlockInfos(CGBlockInfo *info);
1092204643Srdivacky  llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
1093212904Sdim                                           const CGBlockInfo &Info,
1094226890Sdim                                           llvm::StructType *,
1095218893Sdim                                           llvm::Constant *BlockVarLayout);
1096193326Sed
1097210299Sed  llvm::Function *GenerateBlockFunction(GlobalDecl GD,
1098218893Sdim                                        const CGBlockInfo &Info,
1099235633Sdim                                        const DeclMapTy &ldm,
1100235633Sdim                                        bool IsLambdaConversionToBlock);
1101193326Sed
1102218893Sdim  llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
1103218893Sdim  llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
1104235633Sdim  llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
1105235633Sdim                                             const ObjCPropertyImplDecl *PID);
1106235633Sdim  llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
1107235633Sdim                                             const ObjCPropertyImplDecl *PID);
1108235633Sdim  llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
1109193326Sed
1110218893Sdim  void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
1111218893Sdim
1112221345Sdim  class AutoVarEmission;
1113221345Sdim
1114221345Sdim  void emitByrefStructureInit(const AutoVarEmission &emission);
1115221345Sdim  void enterByrefCleanup(const AutoVarEmission &emission);
1116221345Sdim
1117218893Sdim  llvm::Value *LoadBlockStruct() {
1118218893Sdim    assert(BlockPointer && "no block pointer set!");
1119218893Sdim    return BlockPointer;
1120218893Sdim  }
1121218893Sdim
1122208600Srdivacky  void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
1123235633Sdim  void AllocateBlockDecl(const DeclRefExpr *E);
1124218893Sdim  llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
1125226890Sdim  llvm::Type *BuildByRefType(const VarDecl *var);
1126193326Sed
1127221345Sdim  void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1128221345Sdim                    const CGFunctionInfo &FnInfo);
1129252723Sdim  void StartFunction(GlobalDecl GD,
1130252723Sdim                     QualType RetTy,
1131193326Sed                     llvm::Function *Fn,
1132221345Sdim                     const CGFunctionInfo &FnInfo,
1133193326Sed                     const FunctionArgList &Args,
1134193326Sed                     SourceLocation StartLoc);
1135193326Sed
1136204643Srdivacky  void EmitConstructorBody(FunctionArgList &Args);
1137204643Srdivacky  void EmitDestructorBody(FunctionArgList &Args);
1138252723Sdim  void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
1139263509Sdim  void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
1140204643Srdivacky
1141263509Sdim  void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
1142235633Sdim                                  CallArgList &CallArgs);
1143235633Sdim  void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
1144235633Sdim  void EmitLambdaBlockInvokeBody();
1145235633Sdim  void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
1146235633Sdim  void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
1147235633Sdim
1148193326Sed  /// EmitReturnBlock - Emit the unified return block, trying to avoid its
1149193326Sed  /// emission when possible.
1150193326Sed  void EmitReturnBlock();
1151193326Sed
1152193326Sed  /// FinishFunction - Complete IR generation of the current function. It is
1153193326Sed  /// legal to call this function even if there is no current insertion point.
1154193326Sed  void FinishFunction(SourceLocation EndLoc=SourceLocation());
1155193326Sed
1156263509Sdim  void StartThunk(llvm::Function *Fn, GlobalDecl GD, const CGFunctionInfo &FnInfo);
1157263509Sdim
1158263509Sdim  void EmitCallAndReturnForThunk(GlobalDecl GD, llvm::Value *Callee,
1159263509Sdim                                 const ThunkInfo *Thunk);
1160263509Sdim
1161206084Srdivacky  /// GenerateThunk - Generate a thunk for the given method.
1162221345Sdim  void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1163221345Sdim                     GlobalDecl GD, const ThunkInfo &Thunk);
1164218893Sdim
1165223017Sdim  void GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1166223017Sdim                            GlobalDecl GD, const ThunkInfo &Thunk);
1167223017Sdim
1168208600Srdivacky  void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
1169208600Srdivacky                        FunctionArgList &Args);
1170198893Srdivacky
1171235633Sdim  void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init,
1172235633Sdim                               ArrayRef<VarDecl *> ArrayIndexes);
1173235633Sdim
1174206084Srdivacky  /// InitializeVTablePointer - Initialize the vtable pointer of the given
1175206084Srdivacky  /// subobject.
1176206084Srdivacky  ///
1177218893Sdim  void InitializeVTablePointer(BaseSubobject Base,
1178207619Srdivacky                               const CXXRecordDecl *NearestVBase,
1179221345Sdim                               CharUnits OffsetFromNearestVBase,
1180206084Srdivacky                               const CXXRecordDecl *VTableClass);
1181198092Srdivacky
1182206084Srdivacky  typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1183218893Sdim  void InitializeVTablePointers(BaseSubobject Base,
1184207619Srdivacky                                const CXXRecordDecl *NearestVBase,
1185221345Sdim                                CharUnits OffsetFromNearestVBase,
1186206084Srdivacky                                bool BaseIsNonVirtualPrimaryBase,
1187206084Srdivacky                                const CXXRecordDecl *VTableClass,
1188206084Srdivacky                                VisitedVirtualBasesSetTy& VBases);
1189198092Srdivacky
1190206084Srdivacky  void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
1191200583Srdivacky
1192218893Sdim  /// GetVTablePtr - Return the Value of the vtable pointer member pointed
1193218893Sdim  /// to by This.
1194226890Sdim  llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty);
1195201361Srdivacky
1196263509Sdim
1197263509Sdim  /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
1198263509Sdim  /// expr can be devirtualized.
1199263509Sdim  bool CanDevirtualizeMemberFunctionCall(const Expr *Base,
1200263509Sdim                                         const CXXMethodDecl *MD);
1201263509Sdim
1202212904Sdim  /// EnterDtorCleanups - Enter the cleanups necessary to complete the
1203212904Sdim  /// given phase of destruction for a destructor.  The end result
1204212904Sdim  /// should call destructors on members and base classes in reverse
1205212904Sdim  /// order of their construction.
1206212904Sdim  void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
1207198092Srdivacky
1208210299Sed  /// ShouldInstrumentFunction - Return true if the current function should be
1209210299Sed  /// instrumented with __cyg_profile_func_* calls
1210210299Sed  bool ShouldInstrumentFunction();
1211210299Sed
1212210299Sed  /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
1213210299Sed  /// instrumentation function with the current function and the call site, if
1214210299Sed  /// function instrumentation is enabled.
1215210299Sed  void EmitFunctionInstrumentation(const char *Fn);
1216210299Sed
1217218893Sdim  /// EmitMCountInstrumentation - Emit call to .mcount.
1218218893Sdim  void EmitMCountInstrumentation();
1219218893Sdim
1220193326Sed  /// EmitFunctionProlog - Emit the target specific LLVM code to load the
1221193326Sed  /// arguments for the given function. This is also responsible for naming the
1222193326Sed  /// LLVM function arguments.
1223193326Sed  void EmitFunctionProlog(const CGFunctionInfo &FI,
1224193326Sed                          llvm::Function *Fn,
1225193326Sed                          const FunctionArgList &Args);
1226193326Sed
1227193326Sed  /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
1228193326Sed  /// given temporary.
1229263509Sdim  void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
1230263509Sdim                          SourceLocation EndLoc);
1231193326Sed
1232200583Srdivacky  /// EmitStartEHSpec - Emit the start of the exception spec.
1233200583Srdivacky  void EmitStartEHSpec(const Decl *D);
1234200583Srdivacky
1235200583Srdivacky  /// EmitEndEHSpec - Emit the end of the exception spec.
1236200583Srdivacky  void EmitEndEHSpec(const Decl *D);
1237200583Srdivacky
1238210299Sed  /// getTerminateLandingPad - Return a landing pad that just calls terminate.
1239210299Sed  llvm::BasicBlock *getTerminateLandingPad();
1240210299Sed
1241210299Sed  /// getTerminateHandler - Return a handler (not a landing pad, just
1242210299Sed  /// a catch handler) that just calls terminate.  This is used when
1243210299Sed  /// a terminate scope encloses a try.
1244200583Srdivacky  llvm::BasicBlock *getTerminateHandler();
1245200583Srdivacky
1246224145Sdim  llvm::Type *ConvertTypeForMem(QualType T);
1247224145Sdim  llvm::Type *ConvertType(QualType T);
1248224145Sdim  llvm::Type *ConvertType(const TypeDecl *T) {
1249203955Srdivacky    return ConvertType(getContext().getTypeDeclType(T));
1250203955Srdivacky  }
1251193326Sed
1252193326Sed  /// LoadObjCSelf - Load the value of self. This function is only valid while
1253193326Sed  /// generating code for an Objective-C method.
1254193326Sed  llvm::Value *LoadObjCSelf();
1255193326Sed
1256193326Sed  /// TypeOfSelfObject - Return type of object that this self represents.
1257193326Sed  QualType TypeOfSelfObject();
1258193326Sed
1259193326Sed  /// hasAggregateLLVMType - Return true if the specified AST type will map into
1260193326Sed  /// an aggregate LLVM type or is void.
1261252723Sdim  static TypeEvaluationKind getEvaluationKind(QualType T);
1262193326Sed
1263252723Sdim  static bool hasScalarEvaluationKind(QualType T) {
1264252723Sdim    return getEvaluationKind(T) == TEK_Scalar;
1265252723Sdim  }
1266252723Sdim
1267252723Sdim  static bool hasAggregateEvaluationKind(QualType T) {
1268252723Sdim    return getEvaluationKind(T) == TEK_Aggregate;
1269252723Sdim  }
1270252723Sdim
1271193326Sed  /// createBasicBlock - Create an LLVM basic block.
1272245431Sdim  llvm::BasicBlock *createBasicBlock(const Twine &name = "",
1273218893Sdim                                     llvm::Function *parent = 0,
1274218893Sdim                                     llvm::BasicBlock *before = 0) {
1275193326Sed#ifdef NDEBUG
1276218893Sdim    return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
1277193326Sed#else
1278218893Sdim    return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
1279193326Sed#endif
1280193326Sed  }
1281193326Sed
1282193326Sed  /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
1283193326Sed  /// label maps to.
1284218893Sdim  JumpDest getJumpDestForLabel(const LabelDecl *S);
1285193326Sed
1286199990Srdivacky  /// SimplifyForwardingBlocks - If the given basic block is only a branch to
1287199990Srdivacky  /// another basic block, simplify it. This assumes that no other code could
1288199990Srdivacky  /// potentially reference the basic block.
1289193326Sed  void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
1290193326Sed
1291193326Sed  /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
1292193326Sed  /// adding a fall-through branch from the current insert block if
1293193326Sed  /// necessary. It is legal to call this function even if there is no current
1294193326Sed  /// insertion point.
1295193326Sed  ///
1296193326Sed  /// IsFinished - If true, indicates that the caller has finished emitting
1297193326Sed  /// branches to the given block and does not expect to emit code into it. This
1298193326Sed  /// means the block can be ignored if it is unreachable.
1299193326Sed  void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
1300193326Sed
1301226890Sdim  /// EmitBlockAfterUses - Emit the given block somewhere hopefully
1302226890Sdim  /// near its uses, and leave the insertion point in it.
1303226890Sdim  void EmitBlockAfterUses(llvm::BasicBlock *BB);
1304226890Sdim
1305193326Sed  /// EmitBranch - Emit a branch to the specified basic block from the current
1306193326Sed  /// insert block, taking care to avoid creation of branches from dummy
1307193326Sed  /// blocks. It is legal to call this function even if there is no current
1308193326Sed  /// insertion point.
1309193326Sed  ///
1310193326Sed  /// This function clears the current insertion point. The caller should follow
1311193326Sed  /// calls to this function with calls to Emit*Block prior to generation new
1312193326Sed  /// code.
1313193326Sed  void EmitBranch(llvm::BasicBlock *Block);
1314193326Sed
1315193326Sed  /// HaveInsertPoint - True if an insertion point is defined. If not, this
1316193326Sed  /// indicates that the current code being emitted is unreachable.
1317193326Sed  bool HaveInsertPoint() const {
1318193326Sed    return Builder.GetInsertBlock() != 0;
1319193326Sed  }
1320193326Sed
1321193326Sed  /// EnsureInsertPoint - Ensure that an insertion point is defined so that
1322193326Sed  /// emitted IR has a place to go. Note that by definition, if this function
1323193326Sed  /// creates a block then that block is unreachable; callers may do better to
1324193326Sed  /// detect when no insertion point is defined and simply skip IR generation.
1325193326Sed  void EnsureInsertPoint() {
1326193326Sed    if (!HaveInsertPoint())
1327193326Sed      EmitBlock(createBasicBlock());
1328193326Sed  }
1329193326Sed
1330193326Sed  /// ErrorUnsupported - Print out an error that codegen doesn't support the
1331193326Sed  /// specified stmt yet.
1332263509Sdim  void ErrorUnsupported(const Stmt *S, const char *Type);
1333193326Sed
1334193326Sed  //===--------------------------------------------------------------------===//
1335193326Sed  //                                  Helpers
1336193326Sed  //===--------------------------------------------------------------------===//
1337193326Sed
1338235633Sdim  LValue MakeAddrLValue(llvm::Value *V, QualType T,
1339235633Sdim                        CharUnits Alignment = CharUnits()) {
1340218893Sdim    return LValue::MakeAddr(V, T, Alignment, getContext(),
1341218893Sdim                            CGM.getTBAAInfo(T));
1342198092Srdivacky  }
1343245431Sdim
1344235633Sdim  LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
1345235633Sdim    CharUnits Alignment;
1346235633Sdim    if (!T->isIncompleteType())
1347235633Sdim      Alignment = getContext().getTypeAlignInChars(T);
1348235633Sdim    return LValue::MakeAddr(V, T, Alignment, getContext(),
1349235633Sdim                            CGM.getTBAAInfo(T));
1350235633Sdim  }
1351198092Srdivacky
1352193326Sed  /// CreateTempAlloca - This creates a alloca and inserts it into the entry
1353203955Srdivacky  /// block. The caller is responsible for setting an appropriate alignment on
1354203955Srdivacky  /// the alloca.
1355226890Sdim  llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
1356226890Sdim                                     const Twine &Name = "tmp");
1357193326Sed
1358207619Srdivacky  /// InitTempAlloca - Provide an initial value for the given alloca.
1359207619Srdivacky  void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
1360207619Srdivacky
1361204643Srdivacky  /// CreateIRTemp - Create a temporary IR object of the given type, with
1362204643Srdivacky  /// appropriate alignment. This routine should only be used when an temporary
1363204643Srdivacky  /// value needs to be stored into an alloca (for example, to avoid explicit
1364204643Srdivacky  /// PHI construction), but the type is the IR type, not the type appropriate
1365204643Srdivacky  /// for storing in memory.
1366226890Sdim  llvm::AllocaInst *CreateIRTemp(QualType T, const Twine &Name = "tmp");
1367204643Srdivacky
1368203955Srdivacky  /// CreateMemTemp - Create a temporary memory object of the given type, with
1369203955Srdivacky  /// appropriate alignment.
1370226890Sdim  llvm::AllocaInst *CreateMemTemp(QualType T, const Twine &Name = "tmp");
1371203955Srdivacky
1372218893Sdim  /// CreateAggTemp - Create a temporary memory object for the given
1373218893Sdim  /// aggregate type.
1374226890Sdim  AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
1375235633Sdim    CharUnits Alignment = getContext().getTypeAlignInChars(T);
1376235633Sdim    return AggValueSlot::forAddr(CreateMemTemp(T, Name), Alignment,
1377235633Sdim                                 T.getQualifiers(),
1378226890Sdim                                 AggValueSlot::IsNotDestructed,
1379226890Sdim                                 AggValueSlot::DoesNotNeedGCBarriers,
1380226890Sdim                                 AggValueSlot::IsNotAliased);
1381218893Sdim  }
1382218893Sdim
1383218893Sdim  /// Emit a cast to void* in the appropriate address space.
1384218893Sdim  llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
1385218893Sdim
1386193326Sed  /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1387193326Sed  /// expression and compare the result against zero, returning an Int1Ty value.
1388193326Sed  llvm::Value *EvaluateExprAsBool(const Expr *E);
1389193326Sed
1390218893Sdim  /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
1391218893Sdim  void EmitIgnoredExpr(const Expr *E);
1392218893Sdim
1393193326Sed  /// EmitAnyExpr - Emit code to compute the specified expression which can have
1394193326Sed  /// any type.  The result is returned as an RValue struct.  If this is an
1395193326Sed  /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1396193326Sed  /// the result should be returned.
1397193326Sed  ///
1398245431Sdim  /// \param ignoreResult True if the resulting value isn't used.
1399218893Sdim  RValue EmitAnyExpr(const Expr *E,
1400245431Sdim                     AggValueSlot aggSlot = AggValueSlot::ignored(),
1401245431Sdim                     bool ignoreResult = false);
1402193326Sed
1403193326Sed  // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1404193326Sed  // or the value of the expression, depending on how va_list is defined.
1405193326Sed  llvm::Value *EmitVAListRef(const Expr *E);
1406193326Sed
1407193326Sed  /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
1408193326Sed  /// always be accessible even if no aggregate location is provided.
1409218893Sdim  RValue EmitAnyExprToTemp(const Expr *E);
1410193326Sed
1411221345Sdim  /// EmitAnyExprToMem - Emits the code necessary to evaluate an
1412207619Srdivacky  /// arbitrary expression into the given memory location.
1413207619Srdivacky  void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
1414224145Sdim                        Qualifiers Quals, bool IsInitializer);
1415207619Srdivacky
1416221345Sdim  /// EmitExprAsInit - Emits the code necessary to initialize a
1417221345Sdim  /// location in memory with the given initializer.
1418224145Sdim  void EmitExprAsInit(const Expr *init, const ValueDecl *D,
1419224145Sdim                      LValue lvalue, bool capturedByInit);
1420221345Sdim
1421252723Sdim  /// hasVolatileMember - returns true if aggregate type has a volatile
1422252723Sdim  /// member.
1423252723Sdim  bool hasVolatileMember(QualType T) {
1424252723Sdim    if (const RecordType *RT = T->getAs<RecordType>()) {
1425252723Sdim      const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
1426252723Sdim      return RD->hasVolatileMember();
1427252723Sdim    }
1428252723Sdim    return false;
1429252723Sdim  }
1430252723Sdim  /// EmitAggregateCopy - Emit an aggregate assignment.
1431245431Sdim  ///
1432245431Sdim  /// The difference to EmitAggregateCopy is that tail padding is not copied.
1433245431Sdim  /// This is required for correctness when assigning non-POD structures in C++.
1434245431Sdim  void EmitAggregateAssign(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1435252723Sdim                           QualType EltTy) {
1436252723Sdim    bool IsVolatile = hasVolatileMember(EltTy);
1437252723Sdim    EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, CharUnits::Zero(),
1438252723Sdim                      true);
1439245431Sdim  }
1440245431Sdim
1441252723Sdim  /// EmitAggregateCopy - Emit an aggregate copy.
1442193326Sed  ///
1443193326Sed  /// \param isVolatile - True iff either the source or the destination is
1444193326Sed  /// volatile.
1445245431Sdim  /// \param isAssignment - If false, allow padding to be copied.  This often
1446245431Sdim  /// yields more efficient.
1447193326Sed  void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1448235633Sdim                         QualType EltTy, bool isVolatile=false,
1449245431Sdim                         CharUnits Alignment = CharUnits::Zero(),
1450245431Sdim                         bool isAssignment = false);
1451193326Sed
1452193326Sed  /// StartBlock - Start new block named N. If insert block is a dummy block
1453193326Sed  /// then reuse it.
1454193326Sed  void StartBlock(const char *N);
1455193326Sed
1456193326Sed  /// GetAddrOfLocalVar - Return the address of a local variable.
1457212904Sdim  llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) {
1458212904Sdim    llvm::Value *Res = LocalDeclMap[VD];
1459212904Sdim    assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
1460212904Sdim    return Res;
1461212904Sdim  }
1462193326Sed
1463218893Sdim  /// getOpaqueLValueMapping - Given an opaque value expression (which
1464218893Sdim  /// must be mapped to an l-value), return its mapping.
1465218893Sdim  const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
1466218893Sdim    assert(OpaqueValueMapping::shouldBindAsLValue(e));
1467218893Sdim
1468218893Sdim    llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
1469218893Sdim      it = OpaqueLValues.find(e);
1470218893Sdim    assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
1471218893Sdim    return it->second;
1472218893Sdim  }
1473218893Sdim
1474218893Sdim  /// getOpaqueRValueMapping - Given an opaque value expression (which
1475218893Sdim  /// must be mapped to an r-value), return its mapping.
1476218893Sdim  const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
1477218893Sdim    assert(!OpaqueValueMapping::shouldBindAsLValue(e));
1478218893Sdim
1479218893Sdim    llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
1480218893Sdim      it = OpaqueRValues.find(e);
1481218893Sdim    assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
1482218893Sdim    return it->second;
1483218893Sdim  }
1484218893Sdim
1485193326Sed  /// getAccessedFieldNo - Given an encoded value and a result number, return
1486193326Sed  /// the input field number being accessed.
1487193326Sed  static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
1488193326Sed
1489218893Sdim  llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
1490198092Srdivacky  llvm::BasicBlock *GetIndirectGotoBlock();
1491193326Sed
1492208600Srdivacky  /// EmitNullInitialization - Generate code to set a value of the given type to
1493208600Srdivacky  /// null, If the type contains data member pointers, they will be initialized
1494208600Srdivacky  /// to -1 in accordance with the Itanium C++ ABI.
1495208600Srdivacky  void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
1496193326Sed
1497193326Sed  // EmitVAArg - Generate code to get an argument from the passed in pointer
1498193326Sed  // and update it accordingly. The return value is a pointer to the argument.
1499193326Sed  // FIXME: We should be able to get rid of this method and use the va_arg
1500193326Sed  // instruction in LLVM instead once it works well enough.
1501193326Sed  llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
1502193326Sed
1503224145Sdim  /// emitArrayLength - Compute the length of an array, even if it's a
1504224145Sdim  /// VLA, and drill down to the base element type.
1505224145Sdim  llvm::Value *emitArrayLength(const ArrayType *arrayType,
1506224145Sdim                               QualType &baseType,
1507224145Sdim                               llvm::Value *&addr);
1508224145Sdim
1509224145Sdim  /// EmitVLASize - Capture all the sizes for the VLA expressions in
1510224145Sdim  /// the given variably-modified type and store them in the VLASizeMap.
1511198092Srdivacky  ///
1512198092Srdivacky  /// This function can be called with a null (unreachable) insert point.
1513224145Sdim  void EmitVariablyModifiedType(QualType Ty);
1514193326Sed
1515224145Sdim  /// getVLASize - Returns an LLVM value that corresponds to the size,
1516224145Sdim  /// in non-variably-sized elements, of a variable length array type,
1517224145Sdim  /// plus that largest non-variably-sized element type.  Assumes that
1518224145Sdim  /// the type has already been emitted with EmitVariablyModifiedType.
1519224145Sdim  std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
1520224145Sdim  std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
1521193326Sed
1522193326Sed  /// LoadCXXThis - Load the value of 'this'. This function is only valid while
1523193326Sed  /// generating code for an C++ member function.
1524204643Srdivacky  llvm::Value *LoadCXXThis() {
1525204643Srdivacky    assert(CXXThisValue && "no 'this' value for this function");
1526204643Srdivacky    return CXXThisValue;
1527204643Srdivacky  }
1528198092Srdivacky
1529202379Srdivacky  /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
1530202379Srdivacky  /// virtual bases.
1531252723Sdim  // FIXME: Every place that calls LoadCXXVTT is something
1532252723Sdim  // that needs to be abstracted properly.
1533204643Srdivacky  llvm::Value *LoadCXXVTT() {
1534252723Sdim    assert(CXXStructorImplicitParamValue && "no VTT value for this function");
1535252723Sdim    return CXXStructorImplicitParamValue;
1536204643Srdivacky  }
1537203955Srdivacky
1538252723Sdim  /// LoadCXXStructorImplicitParam - Load the implicit parameter
1539252723Sdim  /// for a constructor/destructor.
1540252723Sdim  llvm::Value *LoadCXXStructorImplicitParam() {
1541252723Sdim    assert(CXXStructorImplicitParamValue &&
1542252723Sdim           "no implicit argument value for this function");
1543252723Sdim    return CXXStructorImplicitParamValue;
1544252723Sdim  }
1545252723Sdim
1546203955Srdivacky  /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
1547207619Srdivacky  /// complete class to the given direct base.
1548207619Srdivacky  llvm::Value *
1549207619Srdivacky  GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
1550207619Srdivacky                                        const CXXRecordDecl *Derived,
1551207619Srdivacky                                        const CXXRecordDecl *Base,
1552207619Srdivacky                                        bool BaseIsVirtual);
1553207619Srdivacky
1554199990Srdivacky  /// GetAddressOfBaseClass - This function will add the necessary delta to the
1555199990Srdivacky  /// load of 'this' and returns address of the base class.
1556218893Sdim  llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
1557207619Srdivacky                                     const CXXRecordDecl *Derived,
1558212904Sdim                                     CastExpr::path_const_iterator PathBegin,
1559212904Sdim                                     CastExpr::path_const_iterator PathEnd,
1560199990Srdivacky                                     bool NullCheckValue);
1561207619Srdivacky
1562199990Srdivacky  llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
1563207619Srdivacky                                        const CXXRecordDecl *Derived,
1564212904Sdim                                        CastExpr::path_const_iterator PathBegin,
1565212904Sdim                                        CastExpr::path_const_iterator PathEnd,
1566198092Srdivacky                                        bool NullCheckValue);
1567199990Srdivacky
1568252723Sdim  /// GetVTTParameter - Return the VTT parameter that should be passed to a
1569252723Sdim  /// base constructor/destructor with virtual bases.
1570252723Sdim  /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
1571252723Sdim  /// to ItaniumCXXABI.cpp together with all the references to VTT.
1572252723Sdim  llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
1573252723Sdim                               bool Delegating);
1574252723Sdim
1575204643Srdivacky  void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1576204643Srdivacky                                      CXXCtorType CtorType,
1577263509Sdim                                      const FunctionArgList &Args,
1578263509Sdim                                      SourceLocation Loc);
1579221345Sdim  // It's important not to confuse this and the previous function. Delegating
1580221345Sdim  // constructors are the C++0x feature. The constructor delegate optimization
1581221345Sdim  // is used to reduce duplication in the base and complete consturctors where
1582221345Sdim  // they are substantially the same.
1583221345Sdim  void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1584221345Sdim                                        const FunctionArgList &Args);
1585198092Srdivacky  void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
1586252723Sdim                              bool ForVirtualBase, bool Delegating,
1587252723Sdim                              llvm::Value *This,
1588193326Sed                              CallExpr::const_arg_iterator ArgBeg,
1589193326Sed                              CallExpr::const_arg_iterator ArgEnd);
1590218893Sdim
1591218893Sdim  void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1592218893Sdim                              llvm::Value *This, llvm::Value *Src,
1593218893Sdim                              CallExpr::const_arg_iterator ArgBeg,
1594218893Sdim                              CallExpr::const_arg_iterator ArgEnd);
1595193326Sed
1596198092Srdivacky  void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1597198092Srdivacky                                  const ConstantArrayType *ArrayTy,
1598199990Srdivacky                                  llvm::Value *ArrayPtr,
1599199990Srdivacky                                  CallExpr::const_arg_iterator ArgBeg,
1600212904Sdim                                  CallExpr::const_arg_iterator ArgEnd,
1601212904Sdim                                  bool ZeroInitialization = false);
1602218893Sdim
1603198092Srdivacky  void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1604198092Srdivacky                                  llvm::Value *NumElements,
1605199990Srdivacky                                  llvm::Value *ArrayPtr,
1606199990Srdivacky                                  CallExpr::const_arg_iterator ArgBeg,
1607212904Sdim                                  CallExpr::const_arg_iterator ArgEnd,
1608212904Sdim                                  bool ZeroInitialization = false);
1609198092Srdivacky
1610224145Sdim  static Destroyer destroyCXXObject;
1611198092Srdivacky
1612193326Sed  void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
1613252723Sdim                             bool ForVirtualBase, bool Delegating,
1614252723Sdim                             llvm::Value *This);
1615218893Sdim
1616226890Sdim  void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
1617226890Sdim                               llvm::Value *NewPtr, llvm::Value *NumElements);
1618198092Srdivacky
1619235633Sdim  void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
1620235633Sdim                        llvm::Value *Ptr);
1621198092Srdivacky
1622193326Sed  llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
1623198092Srdivacky  void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
1624198092Srdivacky
1625199482Srdivacky  void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
1626199482Srdivacky                      QualType DeleteTy);
1627199482Srdivacky
1628199482Srdivacky  llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
1629199482Srdivacky  llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
1630245431Sdim  llvm::Value* EmitCXXUuidofExpr(const CXXUuidofExpr *E);
1631199482Srdivacky
1632245431Sdim  /// \brief Situations in which we might emit a check for the suitability of a
1633245431Sdim  ///        pointer or glvalue.
1634245431Sdim  enum TypeCheckKind {
1635245431Sdim    /// Checking the operand of a load. Must be suitably sized and aligned.
1636245431Sdim    TCK_Load,
1637245431Sdim    /// Checking the destination of a store. Must be suitably sized and aligned.
1638245431Sdim    TCK_Store,
1639245431Sdim    /// Checking the bound value in a reference binding. Must be suitably sized
1640245431Sdim    /// and aligned, but is not required to refer to an object (until the
1641245431Sdim    /// reference is used), per core issue 453.
1642245431Sdim    TCK_ReferenceBinding,
1643245431Sdim    /// Checking the object expression in a non-static data member access. Must
1644245431Sdim    /// be an object within its lifetime.
1645245431Sdim    TCK_MemberAccess,
1646245431Sdim    /// Checking the 'this' pointer for a call to a non-static member function.
1647245431Sdim    /// Must be an object within its lifetime.
1648245431Sdim    TCK_MemberCall,
1649245431Sdim    /// Checking the 'this' pointer for a constructor call.
1650252723Sdim    TCK_ConstructorCall,
1651252723Sdim    /// Checking the operand of a static_cast to a derived pointer type. Must be
1652252723Sdim    /// null or an object within its lifetime.
1653252723Sdim    TCK_DowncastPointer,
1654252723Sdim    /// Checking the operand of a static_cast to a derived reference type. Must
1655252723Sdim    /// be an object within its lifetime.
1656252723Sdim    TCK_DowncastReference
1657245431Sdim  };
1658201361Srdivacky
1659245431Sdim  /// \brief Emit a check that \p V is the address of storage of the
1660245431Sdim  /// appropriate size and alignment for an object of type \p Type.
1661245431Sdim  void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
1662245431Sdim                     QualType Type, CharUnits Alignment = CharUnits::Zero());
1663245431Sdim
1664252723Sdim  /// \brief Emit a check that \p Base points into an array object, which
1665252723Sdim  /// we can access at index \p Index. \p Accessed should be \c false if we
1666252723Sdim  /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
1667252723Sdim  void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
1668252723Sdim                       QualType IndexType, bool Accessed);
1669252723Sdim
1670202379Srdivacky  llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1671202379Srdivacky                                       bool isInc, bool isPre);
1672202379Srdivacky  ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
1673202379Srdivacky                                         bool isInc, bool isPre);
1674193326Sed  //===--------------------------------------------------------------------===//
1675193326Sed  //                            Declaration Emission
1676193326Sed  //===--------------------------------------------------------------------===//
1677193326Sed
1678198092Srdivacky  /// EmitDecl - Emit a declaration.
1679198092Srdivacky  ///
1680198092Srdivacky  /// This function can be called with a null (unreachable) insert point.
1681193326Sed  void EmitDecl(const Decl &D);
1682198092Srdivacky
1683218893Sdim  /// EmitVarDecl - Emit a local variable declaration.
1684198092Srdivacky  ///
1685198092Srdivacky  /// This function can be called with a null (unreachable) insert point.
1686218893Sdim  void EmitVarDecl(const VarDecl &D);
1687198092Srdivacky
1688224145Sdim  void EmitScalarInit(const Expr *init, const ValueDecl *D,
1689224145Sdim                      LValue lvalue, bool capturedByInit);
1690224145Sdim  void EmitScalarInit(llvm::Value *init, LValue lvalue);
1691224145Sdim
1692210299Sed  typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
1693210299Sed                             llvm::Value *Address);
1694210299Sed
1695218893Sdim  /// EmitAutoVarDecl - Emit an auto variable declaration.
1696198092Srdivacky  ///
1697198092Srdivacky  /// This function can be called with a null (unreachable) insert point.
1698219077Sdim  void EmitAutoVarDecl(const VarDecl &D);
1699198092Srdivacky
1700219077Sdim  class AutoVarEmission {
1701219077Sdim    friend class CodeGenFunction;
1702219077Sdim
1703219077Sdim    const VarDecl *Variable;
1704219077Sdim
1705219077Sdim    /// The alignment of the variable.
1706219077Sdim    CharUnits Alignment;
1707219077Sdim
1708219077Sdim    /// The address of the alloca.  Null if the variable was emitted
1709219077Sdim    /// as a global constant.
1710219077Sdim    llvm::Value *Address;
1711219077Sdim
1712219077Sdim    llvm::Value *NRVOFlag;
1713219077Sdim
1714219077Sdim    /// True if the variable is a __block variable.
1715219077Sdim    bool IsByRef;
1716219077Sdim
1717219077Sdim    /// True if the variable is of aggregate type and has a constant
1718219077Sdim    /// initializer.
1719219077Sdim    bool IsConstantAggregate;
1720219077Sdim
1721252723Sdim    /// Non-null if we should use lifetime annotations.
1722252723Sdim    llvm::Value *SizeForLifetimeMarkers;
1723252723Sdim
1724219077Sdim    struct Invalid {};
1725219077Sdim    AutoVarEmission(Invalid) : Variable(0) {}
1726219077Sdim
1727219077Sdim    AutoVarEmission(const VarDecl &variable)
1728219077Sdim      : Variable(&variable), Address(0), NRVOFlag(0),
1729252723Sdim        IsByRef(false), IsConstantAggregate(false),
1730252723Sdim        SizeForLifetimeMarkers(0) {}
1731219077Sdim
1732219077Sdim    bool wasEmittedAsGlobal() const { return Address == 0; }
1733219077Sdim
1734219077Sdim  public:
1735219077Sdim    static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
1736219077Sdim
1737252723Sdim    bool useLifetimeMarkers() const { return SizeForLifetimeMarkers != 0; }
1738252723Sdim    llvm::Value *getSizeForLifetimeMarkers() const {
1739252723Sdim      assert(useLifetimeMarkers());
1740252723Sdim      return SizeForLifetimeMarkers;
1741252723Sdim    }
1742252723Sdim
1743252723Sdim    /// Returns the raw, allocated address, which is not necessarily
1744252723Sdim    /// the address of the object itself.
1745252723Sdim    llvm::Value *getAllocatedAddress() const {
1746252723Sdim      return Address;
1747252723Sdim    }
1748252723Sdim
1749219077Sdim    /// Returns the address of the object within this declaration.
1750219077Sdim    /// Note that this does not chase the forwarding pointer for
1751219077Sdim    /// __block decls.
1752219077Sdim    llvm::Value *getObjectAddress(CodeGenFunction &CGF) const {
1753219077Sdim      if (!IsByRef) return Address;
1754219077Sdim
1755219077Sdim      return CGF.Builder.CreateStructGEP(Address,
1756219077Sdim                                         CGF.getByRefValueLLVMField(Variable),
1757219077Sdim                                         Variable->getNameAsString());
1758219077Sdim    }
1759219077Sdim  };
1760219077Sdim  AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
1761219077Sdim  void EmitAutoVarInit(const AutoVarEmission &emission);
1762219077Sdim  void EmitAutoVarCleanups(const AutoVarEmission &emission);
1763224145Sdim  void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
1764224145Sdim                              QualType::DestructionKind dtorKind);
1765219077Sdim
1766218893Sdim  void EmitStaticVarDecl(const VarDecl &D,
1767218893Sdim                         llvm::GlobalValue::LinkageTypes Linkage);
1768193326Sed
1769193326Sed  /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
1770221345Sdim  void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, unsigned ArgNo);
1771193326Sed
1772218893Sdim  /// protectFromPeepholes - Protect a value that we're intending to
1773218893Sdim  /// store to the side, but which will probably be used later, from
1774218893Sdim  /// aggressive peepholing optimizations that might delete it.
1775218893Sdim  ///
1776218893Sdim  /// Pass the result to unprotectFromPeepholes to declare that
1777218893Sdim  /// protection is no longer required.
1778218893Sdim  ///
1779218893Sdim  /// There's no particular reason why this shouldn't apply to
1780218893Sdim  /// l-values, it's just that no existing peepholes work on pointers.
1781218893Sdim  PeepholeProtection protectFromPeepholes(RValue rvalue);
1782218893Sdim  void unprotectFromPeepholes(PeepholeProtection protection);
1783218893Sdim
1784193326Sed  //===--------------------------------------------------------------------===//
1785193326Sed  //                             Statement Emission
1786193326Sed  //===--------------------------------------------------------------------===//
1787193326Sed
1788193326Sed  /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
1789193326Sed  void EmitStopPoint(const Stmt *S);
1790193326Sed
1791193326Sed  /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
1792193326Sed  /// this function even if there is no current insertion point.
1793193326Sed  ///
1794193326Sed  /// This function may clear the current insertion point; callers should use
1795193326Sed  /// EnsureInsertPoint if they wish to subsequently generate code without first
1796193326Sed  /// calling EmitBlock, EmitBranch, or EmitStmt.
1797193326Sed  void EmitStmt(const Stmt *S);
1798193326Sed
1799193326Sed  /// EmitSimpleStmt - Try to emit a "simple" statement which does not
1800193326Sed  /// necessarily require an insertion point or debug information; typically
1801193326Sed  /// because the statement amounts to a jump or a container of other
1802193326Sed  /// statements.
1803193326Sed  ///
1804193326Sed  /// \return True if the statement was handled.
1805193326Sed  bool EmitSimpleStmt(const Stmt *S);
1806193326Sed
1807263509Sdim  llvm::Value *EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
1808263509Sdim                                AggValueSlot AVS = AggValueSlot::ignored());
1809263509Sdim  llvm::Value *EmitCompoundStmtWithoutScope(const CompoundStmt &S,
1810263509Sdim                                            bool GetLast = false,
1811263509Sdim                                            AggValueSlot AVS =
1812263509Sdim                                                AggValueSlot::ignored());
1813193326Sed
1814193326Sed  /// EmitLabel - Emit the block for the given label. It is legal to call this
1815193326Sed  /// function even if there is no current insertion point.
1816218893Sdim  void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
1817193326Sed
1818193326Sed  void EmitLabelStmt(const LabelStmt &S);
1819235633Sdim  void EmitAttributedStmt(const AttributedStmt &S);
1820193326Sed  void EmitGotoStmt(const GotoStmt &S);
1821193326Sed  void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
1822193326Sed  void EmitIfStmt(const IfStmt &S);
1823193326Sed  void EmitWhileStmt(const WhileStmt &S);
1824193326Sed  void EmitDoStmt(const DoStmt &S);
1825193326Sed  void EmitForStmt(const ForStmt &S);
1826193326Sed  void EmitReturnStmt(const ReturnStmt &S);
1827193326Sed  void EmitDeclStmt(const DeclStmt &S);
1828193326Sed  void EmitBreakStmt(const BreakStmt &S);
1829193326Sed  void EmitContinueStmt(const ContinueStmt &S);
1830193326Sed  void EmitSwitchStmt(const SwitchStmt &S);
1831193326Sed  void EmitDefaultStmt(const DefaultStmt &S);
1832193326Sed  void EmitCaseStmt(const CaseStmt &S);
1833193326Sed  void EmitCaseStmtRange(const CaseStmt &S);
1834193326Sed  void EmitAsmStmt(const AsmStmt &S);
1835193326Sed
1836193326Sed  void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
1837193326Sed  void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
1838193326Sed  void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
1839193326Sed  void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
1840224145Sdim  void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
1841193326Sed
1842223017Sdim  llvm::Constant *getUnwindResumeFn();
1843208600Srdivacky  llvm::Constant *getUnwindResumeOrRethrowFn();
1844210299Sed  void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
1845210299Sed  void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
1846204643Srdivacky
1847198092Srdivacky  void EmitCXXTryStmt(const CXXTryStmt &S);
1848263509Sdim  void EmitSEHTryStmt(const SEHTryStmt &S);
1849221345Sdim  void EmitCXXForRangeStmt(const CXXForRangeStmt &S);
1850218893Sdim
1851263509Sdim  llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
1852263509Sdim  llvm::Function *GenerateCapturedStmtFunction(const CapturedDecl *CD,
1853263509Sdim                                               const RecordDecl *RD,
1854263509Sdim                                               SourceLocation Loc);
1855263509Sdim
1856193326Sed  //===--------------------------------------------------------------------===//
1857193326Sed  //                         LValue Expression Emission
1858193326Sed  //===--------------------------------------------------------------------===//
1859193326Sed
1860193326Sed  /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
1861193326Sed  RValue GetUndefRValue(QualType Ty);
1862193326Sed
1863193326Sed  /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
1864193326Sed  /// and issue an ErrorUnsupported style diagnostic (using the
1865193326Sed  /// provided Name).
1866193326Sed  RValue EmitUnsupportedRValue(const Expr *E,
1867193326Sed                               const char *Name);
1868193326Sed
1869193326Sed  /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
1870193326Sed  /// an ErrorUnsupported style diagnostic (using the provided Name).
1871193326Sed  LValue EmitUnsupportedLValue(const Expr *E,
1872193326Sed                               const char *Name);
1873193326Sed
1874193326Sed  /// EmitLValue - Emit code to compute a designator that specifies the location
1875193326Sed  /// of the expression.
1876193326Sed  ///
1877193326Sed  /// This can return one of two things: a simple address or a bitfield
1878193326Sed  /// reference.  In either case, the LLVM Value* in the LValue structure is
1879193326Sed  /// guaranteed to be an LLVM pointer type.
1880193326Sed  ///
1881193326Sed  /// If this returns a bitfield reference, nothing about the pointee type of
1882193326Sed  /// the LLVM value is known: For example, it may not be a pointer to an
1883193326Sed  /// integer.
1884193326Sed  ///
1885193326Sed  /// If this returns a normal address, and if the lvalue's C type is fixed
1886193326Sed  /// size, this method guarantees that the returned pointer type will point to
1887193326Sed  /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
1888193326Sed  /// variable length type, this is not possible.
1889193326Sed  ///
1890193326Sed  LValue EmitLValue(const Expr *E);
1891193326Sed
1892245431Sdim  /// \brief Same as EmitLValue but additionally we generate checking code to
1893245431Sdim  /// guard against undefined behavior.  This is only suitable when we know
1894245431Sdim  /// that the address will be used to access the object.
1895245431Sdim  LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
1896201361Srdivacky
1897263509Sdim  RValue convertTempToRValue(llvm::Value *addr, QualType type,
1898263509Sdim                             SourceLocation Loc);
1899252723Sdim
1900252723Sdim  void EmitAtomicInit(Expr *E, LValue lvalue);
1901252723Sdim
1902263509Sdim  RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
1903252723Sdim                        AggValueSlot slot = AggValueSlot::ignored());
1904252723Sdim
1905252723Sdim  void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
1906252723Sdim
1907218893Sdim  /// EmitToMemory - Change a scalar value from its value
1908218893Sdim  /// representation to its in-memory representation.
1909218893Sdim  llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
1910218893Sdim
1911218893Sdim  /// EmitFromMemory - Change a scalar value from its memory
1912218893Sdim  /// representation to its value representation.
1913218893Sdim  llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
1914218893Sdim
1915193326Sed  /// EmitLoadOfScalar - Load a scalar value from an address, taking
1916193326Sed  /// care to appropriately convert from the memory representation to
1917193326Sed  /// the LLVM value representation.
1918193326Sed  llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
1919218893Sdim                                unsigned Alignment, QualType Ty,
1920263509Sdim                                SourceLocation Loc,
1921252723Sdim                                llvm::MDNode *TBAAInfo = 0,
1922252723Sdim                                QualType TBAABaseTy = QualType(),
1923252723Sdim                                uint64_t TBAAOffset = 0);
1924193326Sed
1925224145Sdim  /// EmitLoadOfScalar - Load a scalar value from an address, taking
1926224145Sdim  /// care to appropriately convert from the memory representation to
1927224145Sdim  /// the LLVM value representation.  The l-value must be a simple
1928224145Sdim  /// l-value.
1929263509Sdim  llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
1930224145Sdim
1931193326Sed  /// EmitStoreOfScalar - Store a scalar value to an address, taking
1932193326Sed  /// care to appropriately convert from the memory representation to
1933193326Sed  /// the LLVM value representation.
1934193326Sed  void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
1935218893Sdim                         bool Volatile, unsigned Alignment, QualType Ty,
1936252723Sdim                         llvm::MDNode *TBAAInfo = 0, bool isInit = false,
1937252723Sdim                         QualType TBAABaseTy = QualType(),
1938252723Sdim                         uint64_t TBAAOffset = 0);
1939193326Sed
1940224145Sdim  /// EmitStoreOfScalar - Store a scalar value to an address, taking
1941224145Sdim  /// care to appropriately convert from the memory representation to
1942224145Sdim  /// the LLVM value representation.  The l-value must be a simple
1943235633Sdim  /// l-value.  The isInit flag indicates whether this is an initialization.
1944235633Sdim  /// If so, atomic qualifiers are ignored and the store is always non-atomic.
1945235633Sdim  void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
1946224145Sdim
1947193326Sed  /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
1948193326Sed  /// this method emits the address of the lvalue, then loads the result as an
1949193326Sed  /// rvalue, returning the rvalue.
1950263509Sdim  RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
1951224145Sdim  RValue EmitLoadOfExtVectorElementLValue(LValue V);
1952224145Sdim  RValue EmitLoadOfBitfieldLValue(LValue LV);
1953193326Sed
1954193326Sed  /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1955193326Sed  /// lvalue, where both are guaranteed to the have the same type, and that type
1956193326Sed  /// is 'Ty'.
1957235633Sdim  void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false);
1958224145Sdim  void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
1959193326Sed
1960263509Sdim  /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
1961263509Sdim  /// as EmitStoreThroughLValue.
1962193326Sed  ///
1963193326Sed  /// \param Result [out] - If non-null, this will be set to a Value* for the
1964193326Sed  /// bit-field contents after the store, appropriate for use as the result of
1965193326Sed  /// an assignment to the bit-field.
1966224145Sdim  void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1967193326Sed                                      llvm::Value **Result=0);
1968193326Sed
1969218893Sdim  /// Emit an l-value for an assignment (simple or compound) of complex type.
1970218893Sdim  LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
1971218893Sdim  LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
1972263509Sdim  LValue EmitScalarCompooundAssignWithComplex(const CompoundAssignOperator *E,
1973263509Sdim                                              llvm::Value *&Result);
1974218893Sdim
1975221345Sdim  // Note: only available for agg return types
1976193326Sed  LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
1977218893Sdim  LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
1978193326Sed  // Note: only available for agg return types
1979193326Sed  LValue EmitCallExprLValue(const CallExpr *E);
1980193326Sed  // Note: only available for agg return types
1981193326Sed  LValue EmitVAArgExprLValue(const VAArgExpr *E);
1982193326Sed  LValue EmitDeclRefLValue(const DeclRefExpr *E);
1983193326Sed  LValue EmitStringLiteralLValue(const StringLiteral *E);
1984193326Sed  LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
1985193326Sed  LValue EmitPredefinedLValue(const PredefinedExpr *E);
1986193326Sed  LValue EmitUnaryOpLValue(const UnaryOperator *E);
1987252723Sdim  LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
1988252723Sdim                                bool Accessed = false);
1989193326Sed  LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
1990193326Sed  LValue EmitMemberExpr(const MemberExpr *E);
1991200583Srdivacky  LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
1992193326Sed  LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
1993245431Sdim  LValue EmitInitListLValue(const InitListExpr *E);
1994218893Sdim  LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
1995193326Sed  LValue EmitCastLValue(const CastExpr *E);
1996224145Sdim  LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
1997218893Sdim  LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
1998218893Sdim
1999263509Sdim  RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
2000235633Sdim
2001235633Sdim  class ConstantEmission {
2002235633Sdim    llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
2003235633Sdim    ConstantEmission(llvm::Constant *C, bool isReference)
2004235633Sdim      : ValueAndIsReference(C, isReference) {}
2005235633Sdim  public:
2006235633Sdim    ConstantEmission() {}
2007235633Sdim    static ConstantEmission forReference(llvm::Constant *C) {
2008235633Sdim      return ConstantEmission(C, true);
2009235633Sdim    }
2010235633Sdim    static ConstantEmission forValue(llvm::Constant *C) {
2011235633Sdim      return ConstantEmission(C, false);
2012235633Sdim    }
2013235633Sdim
2014263509Sdim    LLVM_EXPLICIT operator bool() const { return ValueAndIsReference.getOpaqueValue() != 0; }
2015235633Sdim
2016235633Sdim    bool isReference() const { return ValueAndIsReference.getInt(); }
2017235633Sdim    LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
2018235633Sdim      assert(isReference());
2019235633Sdim      return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
2020235633Sdim                                            refExpr->getType());
2021235633Sdim    }
2022235633Sdim
2023235633Sdim    llvm::Constant *getValue() const {
2024235633Sdim      assert(!isReference());
2025235633Sdim      return ValueAndIsReference.getPointer();
2026235633Sdim    }
2027235633Sdim  };
2028235633Sdim
2029235633Sdim  ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
2030235633Sdim
2031235633Sdim  RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
2032235633Sdim                                AggValueSlot slot = AggValueSlot::ignored());
2033235633Sdim  LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
2034235633Sdim
2035193326Sed  llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
2036193326Sed                              const ObjCIvarDecl *Ivar);
2037235633Sdim  LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
2038252723Sdim  LValue EmitLValueForLambdaField(const FieldDecl *Field);
2039218893Sdim
2040203955Srdivacky  /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
2041203955Srdivacky  /// if the Field is a reference, this will return the address of the reference
2042203955Srdivacky  /// and not the address of the value stored in the reference.
2043235633Sdim  LValue EmitLValueForFieldInitialization(LValue Base,
2044235633Sdim                                          const FieldDecl* Field);
2045218893Sdim
2046193326Sed  LValue EmitLValueForIvar(QualType ObjectTy,
2047193326Sed                           llvm::Value* Base, const ObjCIvarDecl *Ivar,
2048193326Sed                           unsigned CVRQualifiers);
2049193326Sed
2050193326Sed  LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
2051193326Sed  LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
2052235633Sdim  LValue EmitLambdaLValue(const LambdaExpr *E);
2053199482Srdivacky  LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
2054245431Sdim  LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
2055218893Sdim
2056193326Sed  LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
2057193326Sed  LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
2058193326Sed  LValue EmitStmtExprLValue(const StmtExpr *E);
2059198398Srdivacky  LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
2060210299Sed  LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
2061218893Sdim  void   EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init);
2062218893Sdim
2063193326Sed  //===--------------------------------------------------------------------===//
2064193326Sed  //                         Scalar Expression Emission
2065193326Sed  //===--------------------------------------------------------------------===//
2066193326Sed
2067193326Sed  /// EmitCall - Generate a call of the given function, expecting the given
2068193326Sed  /// result type, and using the given argument list which specifies both the
2069193326Sed  /// LLVM arguments and the types they were derived from.
2070193326Sed  ///
2071199990Srdivacky  /// \param TargetDecl - If given, the decl of the function in a direct call;
2072199990Srdivacky  /// used to set attributes on the call (noreturn, etc.).
2073193326Sed  RValue EmitCall(const CGFunctionInfo &FnInfo,
2074193326Sed                  llvm::Value *Callee,
2075201361Srdivacky                  ReturnValueSlot ReturnValue,
2076193326Sed                  const CallArgList &Args,
2077207619Srdivacky                  const Decl *TargetDecl = 0,
2078207619Srdivacky                  llvm::Instruction **callOrInvoke = 0);
2079198092Srdivacky
2080201361Srdivacky  RValue EmitCall(QualType FnType, llvm::Value *Callee,
2081263509Sdim                  SourceLocation CallLoc,
2082201361Srdivacky                  ReturnValueSlot ReturnValue,
2083193326Sed                  CallExpr::const_arg_iterator ArgBeg,
2084193326Sed                  CallExpr::const_arg_iterator ArgEnd,
2085193326Sed                  const Decl *TargetDecl = 0);
2086218893Sdim  RValue EmitCallExpr(const CallExpr *E,
2087201361Srdivacky                      ReturnValueSlot ReturnValue = ReturnValueSlot());
2088198092Srdivacky
2089252723Sdim  llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
2090252723Sdim                                  const Twine &name = "");
2091252723Sdim  llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
2092252723Sdim                                  ArrayRef<llvm::Value*> args,
2093252723Sdim                                  const Twine &name = "");
2094252723Sdim  llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
2095252723Sdim                                          const Twine &name = "");
2096252723Sdim  llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
2097252723Sdim                                          ArrayRef<llvm::Value*> args,
2098252723Sdim                                          const Twine &name = "");
2099252723Sdim
2100210299Sed  llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
2101226890Sdim                                  ArrayRef<llvm::Value *> Args,
2102226890Sdim                                  const Twine &Name = "");
2103224145Sdim  llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
2104226890Sdim                                  const Twine &Name = "");
2105252723Sdim  llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
2106252723Sdim                                         ArrayRef<llvm::Value*> args,
2107252723Sdim                                         const Twine &name = "");
2108252723Sdim  llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
2109252723Sdim                                         const Twine &name = "");
2110252723Sdim  void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2111252723Sdim                                       ArrayRef<llvm::Value*> args);
2112210299Sed
2113218893Sdim  llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
2114218893Sdim                                         NestedNameSpecifier *Qual,
2115226890Sdim                                         llvm::Type *Ty);
2116218893Sdim
2117218893Sdim  llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
2118218893Sdim                                                   CXXDtorType Type,
2119218893Sdim                                                   const CXXRecordDecl *RD);
2120199482Srdivacky
2121193326Sed  RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
2122245431Sdim                           SourceLocation CallLoc,
2123193326Sed                           llvm::Value *Callee,
2124201361Srdivacky                           ReturnValueSlot ReturnValue,
2125193326Sed                           llvm::Value *This,
2126252723Sdim                           llvm::Value *ImplicitParam,
2127252723Sdim                           QualType ImplicitParamTy,
2128193326Sed                           CallExpr::const_arg_iterator ArgBeg,
2129193326Sed                           CallExpr::const_arg_iterator ArgEnd);
2130201361Srdivacky  RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
2131201361Srdivacky                               ReturnValueSlot ReturnValue);
2132201361Srdivacky  RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
2133201361Srdivacky                                      ReturnValueSlot ReturnValue);
2134193326Sed
2135223017Sdim  llvm::Value *EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2136223017Sdim                                           const CXXMethodDecl *MD,
2137223017Sdim                                           llvm::Value *This);
2138193326Sed  RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
2139201361Srdivacky                                       const CXXMethodDecl *MD,
2140201361Srdivacky                                       ReturnValueSlot ReturnValue);
2141198092Srdivacky
2142226890Sdim  RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
2143226890Sdim                                ReturnValueSlot ReturnValue);
2144218893Sdim
2145226890Sdim
2146198092Srdivacky  RValue EmitBuiltinExpr(const FunctionDecl *FD,
2147193326Sed                         unsigned BuiltinID, const CallExpr *E);
2148193326Sed
2149201361Srdivacky  RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
2150193326Sed
2151193326Sed  /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
2152193326Sed  /// is unhandled by the current target.
2153193326Sed  llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2154193326Sed
2155263509Sdim  llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
2156263509Sdim                                             const llvm::CmpInst::Predicate Fp,
2157263509Sdim                                             const llvm::CmpInst::Predicate Ip,
2158263509Sdim                                             const llvm::Twine &Name = "");
2159263509Sdim  llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty);
2160252723Sdim  llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2161204793Srdivacky  llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2162218893Sdim  llvm::Value *EmitNeonCall(llvm::Function *F,
2163226890Sdim                            SmallVectorImpl<llvm::Value*> &O,
2164218893Sdim                            const char *name,
2165210299Sed                            unsigned shift = 0, bool rightshift = false);
2166218893Sdim  llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
2167226890Sdim  llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
2168210299Sed                                   bool negateForRightShift);
2169263509Sdim  llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
2170263509Sdim                                 llvm::Type *Ty, bool usgn, const char *name);
2171218893Sdim
2172235633Sdim  llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
2173193326Sed  llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2174193326Sed  llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2175193326Sed
2176193326Sed  llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
2177193326Sed  llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
2178245431Sdim  llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
2179235633Sdim  llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
2180235633Sdim  llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
2181235633Sdim  llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
2182235633Sdim                                const ObjCMethodDecl *MethodWithObjects);
2183193326Sed  llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
2184208600Srdivacky  RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
2185208600Srdivacky                             ReturnValueSlot Return = ReturnValueSlot());
2186193326Sed
2187224145Sdim  /// Retrieves the default cleanup kind for an ARC cleanup.
2188224145Sdim  /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
2189224145Sdim  CleanupKind getARCCleanupKind() {
2190224145Sdim    return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
2191224145Sdim             ? NormalAndEHCleanup : NormalCleanup;
2192224145Sdim  }
2193224145Sdim
2194224145Sdim  // ARC primitives.
2195224145Sdim  void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr);
2196224145Sdim  void EmitARCDestroyWeak(llvm::Value *addr);
2197224145Sdim  llvm::Value *EmitARCLoadWeak(llvm::Value *addr);
2198224145Sdim  llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr);
2199224145Sdim  llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr,
2200224145Sdim                                bool ignored);
2201224145Sdim  void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src);
2202224145Sdim  void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src);
2203224145Sdim  llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
2204224145Sdim  llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
2205224145Sdim  llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
2206252723Sdim                                  bool resultIgnored);
2207224145Sdim  llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value,
2208252723Sdim                                      bool resultIgnored);
2209224145Sdim  llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
2210224145Sdim  llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
2211226890Sdim  llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
2212252723Sdim  void EmitARCDestroyStrong(llvm::Value *addr, ARCPreciseLifetime_t precise);
2213252723Sdim  void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
2214224145Sdim  llvm::Value *EmitARCAutorelease(llvm::Value *value);
2215224145Sdim  llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
2216224145Sdim  llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
2217224145Sdim  llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
2218224145Sdim
2219224145Sdim  std::pair<LValue,llvm::Value*>
2220224145Sdim  EmitARCStoreAutoreleasing(const BinaryOperator *e);
2221224145Sdim  std::pair<LValue,llvm::Value*>
2222224145Sdim  EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
2223224145Sdim
2224226890Sdim  llvm::Value *EmitObjCThrowOperand(const Expr *expr);
2225226890Sdim
2226224145Sdim  llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr);
2227224145Sdim  llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
2228224145Sdim  llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
2229224145Sdim
2230226890Sdim  llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
2231224145Sdim  llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
2232224145Sdim  llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
2233224145Sdim
2234252723Sdim  void EmitARCIntrinsicUse(llvm::ArrayRef<llvm::Value*> values);
2235252723Sdim
2236224145Sdim  static Destroyer destroyARCStrongImprecise;
2237224145Sdim  static Destroyer destroyARCStrongPrecise;
2238224145Sdim  static Destroyer destroyARCWeak;
2239224145Sdim
2240224145Sdim  void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
2241224145Sdim  llvm::Value *EmitObjCAutoreleasePoolPush();
2242224145Sdim  llvm::Value *EmitObjCMRRAutoreleasePoolPush();
2243224145Sdim  void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
2244224145Sdim  void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
2245224145Sdim
2246263509Sdim  /// \brief Emits a reference binding to the passed in expression.
2247263509Sdim  RValue EmitReferenceBindingToExpr(const Expr *E);
2248198092Srdivacky
2249193326Sed  //===--------------------------------------------------------------------===//
2250193326Sed  //                           Expression Emission
2251193326Sed  //===--------------------------------------------------------------------===//
2252193326Sed
2253193326Sed  // Expressions are broken into three classes: scalar, complex, aggregate.
2254193326Sed
2255193326Sed  /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
2256193326Sed  /// scalar type, returning the result.
2257198092Srdivacky  llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
2258193326Sed
2259193326Sed  /// EmitScalarConversion - Emit a conversion from the specified type to the
2260193326Sed  /// specified destination type, both of which are LLVM scalar types.
2261193326Sed  llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
2262193326Sed                                    QualType DstTy);
2263193326Sed
2264193326Sed  /// EmitComplexToScalarConversion - Emit a conversion from the specified
2265193326Sed  /// complex type to the specified destination type, where the destination type
2266193326Sed  /// is an LLVM scalar type.
2267193326Sed  llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
2268193326Sed                                             QualType DstTy);
2269193326Sed
2270193326Sed
2271218893Sdim  /// EmitAggExpr - Emit the computation of the specified expression
2272218893Sdim  /// of aggregate type.  The result is computed into the given slot,
2273218893Sdim  /// which may be null to indicate that the value is not needed.
2274245431Sdim  void EmitAggExpr(const Expr *E, AggValueSlot AS);
2275193326Sed
2276203955Srdivacky  /// EmitAggExprToLValue - Emit the computation of the specified expression of
2277203955Srdivacky  /// aggregate type into a temporary LValue.
2278203955Srdivacky  LValue EmitAggExprToLValue(const Expr *E);
2279203955Srdivacky
2280198092Srdivacky  /// EmitGCMemmoveCollectable - Emit special API for structs with object
2281198092Srdivacky  /// pointers.
2282198092Srdivacky  void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
2283198092Srdivacky                                QualType Ty);
2284198092Srdivacky
2285224145Sdim  /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2286224145Sdim  /// make sure it survives garbage collection until this point.
2287224145Sdim  void EmitExtendGCLifetime(llvm::Value *object);
2288224145Sdim
2289193326Sed  /// EmitComplexExpr - Emit the computation of the specified expression of
2290193326Sed  /// complex type, returning the result.
2291218893Sdim  ComplexPairTy EmitComplexExpr(const Expr *E,
2292218893Sdim                                bool IgnoreReal = false,
2293218893Sdim                                bool IgnoreImag = false);
2294193326Sed
2295252723Sdim  /// EmitComplexExprIntoLValue - Emit the given expression of complex
2296252723Sdim  /// type and place its result into the specified l-value.
2297252723Sdim  void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
2298193326Sed
2299252723Sdim  /// EmitStoreOfComplex - Store a complex number into the specified l-value.
2300252723Sdim  void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
2301193326Sed
2302252723Sdim  /// EmitLoadOfComplex - Load a complex number from the specified l-value.
2303263509Sdim  ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
2304252723Sdim
2305218893Sdim  /// CreateStaticVarDecl - Create a zero-initialized LLVM global for
2306218893Sdim  /// a static local variable.
2307218893Sdim  llvm::GlobalVariable *CreateStaticVarDecl(const VarDecl &D,
2308218893Sdim                                            const char *Separator,
2309199990Srdivacky                                       llvm::GlobalValue::LinkageTypes Linkage);
2310218893Sdim
2311218893Sdim  /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
2312200583Srdivacky  /// global variable that has already been created for it.  If the initializer
2313200583Srdivacky  /// has a different type than GV does, this may free GV and return a different
2314200583Srdivacky  /// one.  Otherwise it just returns GV.
2315200583Srdivacky  llvm::GlobalVariable *
2316218893Sdim  AddInitializerToStaticVarDecl(const VarDecl &D,
2317218893Sdim                                llvm::GlobalVariable *GV);
2318193326Sed
2319193326Sed
2320198092Srdivacky  /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
2321198092Srdivacky  /// variable with global storage.
2322235633Sdim  void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
2323235633Sdim                                bool PerformInit);
2324198092Srdivacky
2325245431Sdim  /// Call atexit() with a function that passes the given argument to
2326245431Sdim  /// the given function.
2327263509Sdim  void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
2328263509Sdim                                    llvm::Constant *addr);
2329198092Srdivacky
2330218893Sdim  /// Emit code in this function to perform a guarded variable
2331218893Sdim  /// initialization.  Guarded initializations are used when it's not
2332218893Sdim  /// possible to prove that an initialization will be done exactly
2333218893Sdim  /// once, e.g. with a static local variable or a static data member
2334218893Sdim  /// of a class template.
2335235633Sdim  void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
2336235633Sdim                          bool PerformInit);
2337218893Sdim
2338198092Srdivacky  /// GenerateCXXGlobalInitFunc - Generates code for initializing global
2339198092Srdivacky  /// variables.
2340198092Srdivacky  void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
2341252723Sdim                                 ArrayRef<llvm::Constant *> Decls,
2342252723Sdim                                 llvm::GlobalVariable *Guard = 0);
2343198092Srdivacky
2344235633Sdim  /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
2345205408Srdivacky  /// variables.
2346235633Sdim  void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
2347235633Sdim                                  const std::vector<std::pair<llvm::WeakVH,
2348235633Sdim                                  llvm::Constant*> > &DtorsAndObjects);
2349205408Srdivacky
2350221345Sdim  void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
2351221345Sdim                                        const VarDecl *D,
2352235633Sdim                                        llvm::GlobalVariable *Addr,
2353235633Sdim                                        bool PerformInit);
2354202379Srdivacky
2355218893Sdim  void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
2356218893Sdim
2357218893Sdim  void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src,
2358218893Sdim                                  const Expr *Exp);
2359198092Srdivacky
2360235633Sdim  void enterFullExpression(const ExprWithCleanups *E) {
2361235633Sdim    if (E->getNumObjects() == 0) return;
2362235633Sdim    enterNonTrivialFullExpression(E);
2363235633Sdim  }
2364235633Sdim  void enterNonTrivialFullExpression(const ExprWithCleanups *E);
2365198092Srdivacky
2366252723Sdim  void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
2367199482Srdivacky
2368235633Sdim  void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
2369235633Sdim
2370226890Sdim  RValue EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest = 0);
2371226890Sdim
2372193326Sed  //===--------------------------------------------------------------------===//
2373226890Sdim  //                         Annotations Emission
2374226890Sdim  //===--------------------------------------------------------------------===//
2375226890Sdim
2376226890Sdim  /// Emit an annotation call (intrinsic or builtin).
2377226890Sdim  llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
2378226890Sdim                                  llvm::Value *AnnotatedVal,
2379252723Sdim                                  StringRef AnnotationStr,
2380226890Sdim                                  SourceLocation Location);
2381226890Sdim
2382226890Sdim  /// Emit local annotations for the local variable V, declared by D.
2383226890Sdim  void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
2384226890Sdim
2385226890Sdim  /// Emit field annotations for the given field & value. Returns the
2386226890Sdim  /// annotation result.
2387226890Sdim  llvm::Value *EmitFieldAnnotations(const FieldDecl *D, llvm::Value *V);
2388226890Sdim
2389226890Sdim  //===--------------------------------------------------------------------===//
2390193326Sed  //                             Internal Helpers
2391193326Sed  //===--------------------------------------------------------------------===//
2392193326Sed
2393193326Sed  /// ContainsLabel - Return true if the statement contains a label in it.  If
2394193326Sed  /// this statement is not executed normally, it not containing a label means
2395193326Sed  /// that we can just remove the code.
2396193326Sed  static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
2397193326Sed
2398221345Sdim  /// containsBreak - Return true if the statement contains a break out of it.
2399221345Sdim  /// If the statement (recursively) contains a switch or loop with a break
2400221345Sdim  /// inside of it, this is fine.
2401221345Sdim  static bool containsBreak(const Stmt *S);
2402221345Sdim
2403193326Sed  /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
2404221345Sdim  /// to a constant, or if it does but contains a label, return false.  If it
2405221345Sdim  /// constant folds return true and set the boolean result in Result.
2406221345Sdim  bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result);
2407193326Sed
2408221345Sdim  /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
2409221345Sdim  /// to a constant, or if it does but contains a label, return false.  If it
2410221345Sdim  /// constant folds return true and set the folded value.
2411245431Sdim  bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result);
2412221345Sdim
2413193326Sed  /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
2414193326Sed  /// if statement) to the specified blocks.  Based on the condition, this might
2415193326Sed  /// try to simplify the codegen of the conditional based on the branch.
2416193326Sed  void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
2417193326Sed                            llvm::BasicBlock *FalseBlock);
2418200583Srdivacky
2419245431Sdim  /// \brief Emit a description of a type in a format suitable for passing to
2420245431Sdim  /// a runtime sanitizer handler.
2421245431Sdim  llvm::Constant *EmitCheckTypeDescriptor(QualType T);
2422218893Sdim
2423245431Sdim  /// \brief Convert a value into a format suitable for passing to a runtime
2424245431Sdim  /// sanitizer handler.
2425245431Sdim  llvm::Value *EmitCheckValue(llvm::Value *V);
2426245431Sdim
2427245431Sdim  /// \brief Emit a description of a source location in a format suitable for
2428245431Sdim  /// passing to a runtime sanitizer handler.
2429245431Sdim  llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
2430245431Sdim
2431252723Sdim  /// \brief Specify under what conditions this check can be recovered
2432252723Sdim  enum CheckRecoverableKind {
2433252723Sdim    /// Always terminate program execution if this check fails
2434252723Sdim    CRK_Unrecoverable,
2435252723Sdim    /// Check supports recovering, allows user to specify which
2436252723Sdim    CRK_Recoverable,
2437252723Sdim    /// Runtime conditionally aborts, always need to support recovery.
2438252723Sdim    CRK_AlwaysRecoverable
2439252723Sdim  };
2440252723Sdim
2441245431Sdim  /// \brief Create a basic block that will call a handler function in a
2442245431Sdim  /// sanitizer runtime with the provided arguments, and create a conditional
2443245431Sdim  /// branch to it.
2444245431Sdim  void EmitCheck(llvm::Value *Checked, StringRef CheckName,
2445252723Sdim                 ArrayRef<llvm::Constant *> StaticArgs,
2446252723Sdim                 ArrayRef<llvm::Value *> DynamicArgs,
2447252723Sdim                 CheckRecoverableKind Recoverable);
2448245431Sdim
2449245431Sdim  /// \brief Create a basic block that will call the trap intrinsic, and emit a
2450245431Sdim  /// conditional branch to it, for the -ftrapv checks.
2451252723Sdim  void EmitTrapCheck(llvm::Value *Checked);
2452245431Sdim
2453206084Srdivacky  /// EmitCallArg - Emit a single call argument.
2454221345Sdim  void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
2455206084Srdivacky
2456208600Srdivacky  /// EmitDelegateCallArg - We are performing a delegate call; that
2457208600Srdivacky  /// is, the current function is delegating to another one.  Produce
2458208600Srdivacky  /// a r-value suitable for passing the given parameter.
2459263509Sdim  void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
2460263509Sdim                           SourceLocation loc);
2461208600Srdivacky
2462235633Sdim  /// SetFPAccuracy - Set the minimum required accuracy of the given floating
2463235633Sdim  /// point operation, expressed as the maximum relative error in ulp.
2464235633Sdim  void SetFPAccuracy(llvm::Value *Val, float Accuracy);
2465235633Sdim
2466193326Sedprivate:
2467235633Sdim  llvm::MDNode *getRangeForLoadFromType(QualType Ty);
2468193326Sed  void EmitReturnOfRValue(RValue RV, QualType Ty);
2469193326Sed
2470193326Sed  /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
2471193326Sed  /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
2472193326Sed  ///
2473193326Sed  /// \param AI - The first function argument of the expansion.
2474193326Sed  /// \return The argument following the last expanded function
2475193326Sed  /// argument.
2476193326Sed  llvm::Function::arg_iterator
2477193326Sed  ExpandTypeFromArgs(QualType Ty, LValue Dst,
2478193326Sed                     llvm::Function::arg_iterator AI);
2479193326Sed
2480193326Sed  /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
2481193326Sed  /// Ty, into individual arguments on the provided vector \arg Args. See
2482193326Sed  /// ABIArgInfo::Expand.
2483193326Sed  void ExpandTypeToArgs(QualType Ty, RValue Src,
2484263509Sdim                        SmallVectorImpl<llvm::Value *> &Args,
2485224145Sdim                        llvm::FunctionType *IRFuncTy);
2486193326Sed
2487245431Sdim  llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
2488193326Sed                            const Expr *InputExpr, std::string &ConstraintStr);
2489193326Sed
2490245431Sdim  llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
2491212904Sdim                                  LValue InputValue, QualType InputType,
2492263509Sdim                                  std::string &ConstraintStr,
2493263509Sdim                                  SourceLocation Loc);
2494212904Sdim
2495193326Sed  /// EmitCallArgs - Emit call arguments for a function.
2496198092Srdivacky  /// The CallArgTypeInfo parameter is used for iterating over the known
2497193326Sed  /// argument types of the function being called.
2498193326Sed  template<typename T>
2499193326Sed  void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
2500193326Sed                    CallExpr::const_arg_iterator ArgBeg,
2501263509Sdim                    CallExpr::const_arg_iterator ArgEnd,
2502263509Sdim                    bool ForceColumnInfo = false) {
2503263509Sdim    CGDebugInfo *DI = getDebugInfo();
2504263509Sdim    SourceLocation CallLoc;
2505263509Sdim    if (DI) CallLoc = DI->getLocation();
2506193326Sed
2507263509Sdim    CallExpr::const_arg_iterator Arg = ArgBeg;
2508263509Sdim
2509193326Sed    // First, use the argument types that the type info knows about
2510193326Sed    if (CallArgTypeInfo) {
2511193326Sed      for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
2512193326Sed           E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
2513199482Srdivacky        assert(Arg != ArgEnd && "Running over edge of argument list!");
2514193326Sed        QualType ArgType = *I;
2515218893Sdim#ifndef NDEBUG
2516218893Sdim        QualType ActualArgType = Arg->getType();
2517218893Sdim        if (ArgType->isPointerType() && ActualArgType->isPointerType()) {
2518218893Sdim          QualType ActualBaseType =
2519218893Sdim            ActualArgType->getAs<PointerType>()->getPointeeType();
2520218893Sdim          QualType ArgBaseType =
2521218893Sdim            ArgType->getAs<PointerType>()->getPointeeType();
2522218893Sdim          if (ArgBaseType->isVariableArrayType()) {
2523218893Sdim            if (const VariableArrayType *VAT =
2524218893Sdim                getContext().getAsVariableArrayType(ActualBaseType)) {
2525218893Sdim              if (!VAT->getSizeExpr())
2526218893Sdim                ActualArgType = ArgType;
2527218893Sdim            }
2528218893Sdim          }
2529218893Sdim        }
2530193326Sed        assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
2531198092Srdivacky               getTypePtr() ==
2532218893Sdim               getContext().getCanonicalType(ActualArgType).getTypePtr() &&
2533193326Sed               "type mismatch in call argument!");
2534218893Sdim#endif
2535221345Sdim        EmitCallArg(Args, *Arg, ArgType);
2536263509Sdim
2537263509Sdim        // Each argument expression could modify the debug
2538263509Sdim        // location. Restore it.
2539263509Sdim        if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2540193326Sed      }
2541198092Srdivacky
2542198092Srdivacky      // Either we've emitted all the call args, or we have a call to a
2543193326Sed      // variadic function.
2544198092Srdivacky      assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
2545193326Sed             "Extra arguments in non-variadic function!");
2546198092Srdivacky
2547193326Sed    }
2548198092Srdivacky
2549193326Sed    // If we still have any arguments, emit them using the type of the argument.
2550263509Sdim    for (; Arg != ArgEnd; ++Arg) {
2551221345Sdim      EmitCallArg(Args, *Arg, Arg->getType());
2552263509Sdim
2553263509Sdim      // Restore the debug location.
2554263509Sdim      if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2555263509Sdim    }
2556193326Sed  }
2557204643Srdivacky
2558204643Srdivacky  const TargetCodeGenInfo &getTargetHooks() const {
2559204643Srdivacky    return CGM.getTargetCodeGenInfo();
2560204643Srdivacky  }
2561210299Sed
2562210299Sed  void EmitDeclMetadata();
2563221345Sdim
2564221345Sdim  CodeGenModule::ByrefHelpers *
2565226890Sdim  buildByrefHelpers(llvm::StructType &byrefType,
2566221345Sdim                    const AutoVarEmission &emission);
2567235633Sdim
2568235633Sdim  void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
2569235633Sdim
2570245431Sdim  /// GetPointeeAlignment - Given an expression with a pointer type, emit the
2571245431Sdim  /// value and compute our best estimate of the alignment of the pointee.
2572245431Sdim  std::pair<llvm::Value*, unsigned> EmitPointerWithAlignment(const Expr *Addr);
2573193326Sed};
2574193326Sed
2575218893Sdim/// Helper class with most of the code for saving a value for a
2576218893Sdim/// conditional expression cleanup.
2577218893Sdimstruct DominatingLLVMValue {
2578218893Sdim  typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
2579218893Sdim
2580218893Sdim  /// Answer whether the given value needs extra work to be saved.
2581218893Sdim  static bool needsSaving(llvm::Value *value) {
2582218893Sdim    // If it's not an instruction, we don't need to save.
2583218893Sdim    if (!isa<llvm::Instruction>(value)) return false;
2584218893Sdim
2585218893Sdim    // If it's an instruction in the entry block, we don't need to save.
2586218893Sdim    llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
2587218893Sdim    return (block != &block->getParent()->getEntryBlock());
2588218893Sdim  }
2589218893Sdim
2590218893Sdim  /// Try to save the given value.
2591218893Sdim  static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
2592218893Sdim    if (!needsSaving(value)) return saved_type(value, false);
2593218893Sdim
2594218893Sdim    // Otherwise we need an alloca.
2595218893Sdim    llvm::Value *alloca =
2596218893Sdim      CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save");
2597218893Sdim    CGF.Builder.CreateStore(value, alloca);
2598218893Sdim
2599218893Sdim    return saved_type(alloca, true);
2600218893Sdim  }
2601218893Sdim
2602218893Sdim  static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
2603218893Sdim    if (!value.getInt()) return value.getPointer();
2604218893Sdim    return CGF.Builder.CreateLoad(value.getPointer());
2605218893Sdim  }
2606212904Sdim};
2607218893Sdim
2608218893Sdim/// A partial specialization of DominatingValue for llvm::Values that
2609218893Sdim/// might be llvm::Instructions.
2610218893Sdimtemplate <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
2611218893Sdim  typedef T *type;
2612218893Sdim  static type restore(CodeGenFunction &CGF, saved_type value) {
2613218893Sdim    return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
2614218893Sdim  }
2615218893Sdim};
2616218893Sdim
2617218893Sdim/// A specialization of DominatingValue for RValue.
2618218893Sdimtemplate <> struct DominatingValue<RValue> {
2619218893Sdim  typedef RValue type;
2620218893Sdim  class saved_type {
2621218893Sdim    enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
2622218893Sdim                AggregateAddress, ComplexAddress };
2623218893Sdim
2624218893Sdim    llvm::Value *Value;
2625218893Sdim    Kind K;
2626218893Sdim    saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {}
2627218893Sdim
2628218893Sdim  public:
2629218893Sdim    static bool needsSaving(RValue value);
2630218893Sdim    static saved_type save(CodeGenFunction &CGF, RValue value);
2631218893Sdim    RValue restore(CodeGenFunction &CGF);
2632218893Sdim
2633218893Sdim    // implementations in CGExprCXX.cpp
2634218893Sdim  };
2635218893Sdim
2636218893Sdim  static bool needsSaving(type value) {
2637218893Sdim    return saved_type::needsSaving(value);
2638218893Sdim  }
2639218893Sdim  static saved_type save(CodeGenFunction &CGF, type value) {
2640218893Sdim    return saved_type::save(CGF, value);
2641218893Sdim  }
2642218893Sdim  static type restore(CodeGenFunction &CGF, saved_type value) {
2643218893Sdim    return value.restore(CGF);
2644218893Sdim  }
2645218893Sdim};
2646218893Sdim
2647193326Sed}  // end namespace CodeGen
2648193326Sed}  // end namespace clang
2649193326Sed
2650193326Sed#endif
2651