Overhaul of Stmt allocation:
- Made allocation of Stmt objects using vanilla new/delete a *compiler
  error* by making this new/delete "protected" within class Stmt.
- Now the only way to allocate Stmt objects is by using the new
  operator that takes ASTContext& as an argument.  This ensures that
  all Stmt nodes are allocated from the same (pool) allocator.
- Naturally, these two changes required that *all* creation sites for
  AST nodes use new (ASTContext&).  This is a large patch, but the
  majority of the changes are just this mechanical adjustment.
- The above changes also mean that AST nodes can no longer be
  deallocated using 'delete'.  Instead, one most do
  StmtObject->Destroy(ASTContext&) or do
  ASTContextObject.Deallocate(StmtObject) (the latter not running the
  'Destroy' method).

Along the way I also...
- Made CompoundStmt allocate its array of Stmt* using the allocator in
  ASTContext (previously it used std::vector).  There are a whole
  bunch of other Stmt classes that need to be similarly changed to
  ensure that all memory allocated for ASTs comes from the allocator
  in ASTContext.
- Added a new smart pointer ExprOwningPtr to Sema.h.  This replaces
  the uses of llvm::OwningPtr within Sema, as llvm::OwningPtr used
  'delete' to free memory instead of a Stmt's 'Destroy' method.

Big thanks to Doug Gregor for helping with the acrobatics of making
'new/delete' private and the new smart pointer ExprOwningPtr!


git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@63997 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/AST/Expr.cpp b/lib/AST/Expr.cpp
index 89fdbe3..d686167 100644
--- a/lib/AST/Expr.cpp
+++ b/lib/AST/Expr.cpp
@@ -54,8 +54,8 @@
 }
 
 void StringLiteral::Destroy(ASTContext &C) {
-  C.Deallocate(const_cast<char*>(StrData));
   this->~StringLiteral();
+  C.Deallocate(const_cast<char*>(StrData));
 }
 
 bool UnaryOperator::isPostfix(Opcode Op) {
@@ -104,8 +104,8 @@
 // Postfix Operators.
 //===----------------------------------------------------------------------===//
 
-CallExpr::CallExpr(StmtClass SC, Expr *fn, Expr **args, unsigned numargs, 
-                   QualType t, SourceLocation rparenloc)
+CallExpr::CallExpr(StmtClass SC, Expr *fn, Expr **args,
+                   unsigned numargs, QualType t, SourceLocation rparenloc)
   : Expr(SC, t, 
          fn->isTypeDependent() || hasAnyTypeDependentArguments(args, numargs),
          fn->isValueDependent() || hasAnyValueDependentArguments(args, numargs)),
@@ -133,14 +133,14 @@
 /// setNumArgs - This changes the number of arguments present in this call.
 /// Any orphaned expressions are deleted by this, and any new operands are set
 /// to null.
-void CallExpr::setNumArgs(unsigned NumArgs) {
+void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) {
   // No change, just return.
   if (NumArgs == getNumArgs()) return;
   
   // If shrinking # arguments, just delete the extras and forgot them.
   if (NumArgs < getNumArgs()) {
     for (unsigned i = NumArgs, e = getNumArgs(); i != e; ++i)
-      delete getArg(i);
+      getArg(i)->Destroy(C);
     this->NumArgs = NumArgs;
     return;
   }
@@ -154,7 +154,7 @@
   for (unsigned i = getNumArgs()+ARGS_START; i != NumArgs+ARGS_START; ++i)
     NewSubExprs[i] = 0;
   
-  delete[] SubExprs;
+  delete [] SubExprs;
   SubExprs = NewSubExprs;
   this->NumArgs = NumArgs;
 }
@@ -1391,10 +1391,10 @@
   // will iterate over the size expression. However, this expression belongs
   // to the type, not to this, so we don't want to delete it.
   // We still want to delete this expression.
-  // FIXME: Same as in Stmt::Destroy - will be eventually in ASTContext's
-  // pool allocator.
-  if (isArgumentType())
-    delete this;
+  if (isArgumentType()) {
+    this->~SizeOfAlignOfExpr();
+    C.Deallocate(this);
+  }
   else
     Expr::Destroy(C);
 }
diff --git a/lib/AST/ExprCXX.cpp b/lib/AST/ExprCXX.cpp
index b328c1e..801a0f2 100644
--- a/lib/AST/ExprCXX.cpp
+++ b/lib/AST/ExprCXX.cpp
@@ -20,10 +20,10 @@
   // FIXME: Cannot destroy the decl here, because it is linked into the
   // DeclContext's chain.
   //getVarDecl()->Destroy(C);
-  delete this;
+  this->~CXXConditionDeclExpr();
+  C.Deallocate(this);
 }
 
-
 //===----------------------------------------------------------------------===//
 //  Child Iterators for iterating over subexpressions/substatements
 //===----------------------------------------------------------------------===//
diff --git a/lib/AST/Stmt.cpp b/lib/AST/Stmt.cpp
index 541bb04..49c8c80 100644
--- a/lib/AST/Stmt.cpp
+++ b/lib/AST/Stmt.cpp
@@ -219,7 +219,7 @@
 
 // CompoundStmt
 Stmt::child_iterator CompoundStmt::child_begin() { return &Body[0]; }
-Stmt::child_iterator CompoundStmt::child_end() { return &Body[0]+Body.size(); }
+Stmt::child_iterator CompoundStmt::child_end() { return &Body[0]+NumStmts; }
 
 // CaseStmt
 Stmt::child_iterator CaseStmt::child_begin() { return &SubExprs[0]; }
diff --git a/lib/AST/StmtSerialization.cpp b/lib/AST/StmtSerialization.cpp
index 8d6636d..92713cc 100644
--- a/lib/AST/StmtSerialization.cpp
+++ b/lib/AST/StmtSerialization.cpp
@@ -483,7 +483,8 @@
   S.EmitOwnedPtr(Init);
 }
 
-CompoundLiteralExpr* CompoundLiteralExpr::CreateImpl(Deserializer& D, ASTContext& C) {
+CompoundLiteralExpr* CompoundLiteralExpr::CreateImpl(Deserializer& D,
+                                                     ASTContext& C) {
   QualType Q = QualType::ReadVal(D);
   SourceLocation L = SourceLocation::ReadVal(D);
   bool fileScope = D.ReadBool();
@@ -495,10 +496,8 @@
 void CompoundStmt::EmitImpl(Serializer& S) const {
   S.Emit(LBracLoc);
   S.Emit(RBracLoc);
-  S.Emit(Body.size());
-  
-  for (const_body_iterator I=body_begin(), E=body_end(); I!=E; ++I)
-    S.EmitOwnedPtr(*I);
+  S.Emit(NumStmts);
+  if (NumStmts) S.BatchEmitOwnedPtrs(NumStmts, &Body[0]);
 }
 
 CompoundStmt* CompoundStmt::CreateImpl(Deserializer& D, ASTContext& C) {
@@ -507,13 +506,15 @@
   unsigned size = D.ReadInt();
   
   CompoundStmt* stmt = new (C, llvm::alignof<CompoundStmt>())
-    CompoundStmt(NULL, 0, LB, RB);
+    CompoundStmt(C, NULL, 0, LB, RB);
+
+  stmt->NumStmts = size;
   
-  stmt->Body.reserve(size);
-  
-  for (unsigned i = 0; i < size; ++i)
-    stmt->Body.push_back(D.ReadOwnedPtr<Stmt>(C));
-  
+  if (size) {
+    stmt->Body = new (C) Stmt*[size];
+    D.BatchReadOwnedPtrs(size, &stmt->Body[0], C);
+  }
+
   return stmt;
 }
 
@@ -1306,7 +1307,7 @@
   Expr *B = D.ReadOwnedPtr<Expr>(C);
   IdentifierInfo *A = D.ReadPtr<IdentifierInfo>();
   SourceLocation AL = SourceLocation::ReadVal(D);
-  return new ExtVectorElementExpr(T, B, *A, AL);
+  return new (C) ExtVectorElementExpr(T, B, *A, AL);
 }
 
 void BlockExpr::EmitImpl(Serializer& S) const {
diff --git a/lib/Sema/Sema.cpp b/lib/Sema/Sema.cpp
index 028c9eb..8667ee2 100644
--- a/lib/Sema/Sema.cpp
+++ b/lib/Sema/Sema.cpp
@@ -183,7 +183,7 @@
     ImpCast->setType(Ty);
     ImpCast->setLvalueCast(isLvalue);
   } else 
-    Expr = new ImplicitCastExpr(Ty, Expr, isLvalue);
+    Expr = new (Context) ImplicitCastExpr(Ty, Expr, isLvalue);
 }
 
 void Sema::DeleteExpr(ExprTy *E) {
diff --git a/lib/Sema/Sema.h b/lib/Sema/Sema.h
index 4878403..88d7a0f 100644
--- a/lib/Sema/Sema.h
+++ b/lib/Sema/Sema.h
@@ -1970,7 +1970,7 @@
   
   BlockDecl *TheDecl;
   
-  /// TheScope - This is the scope for the block itself, which contains
+  /// TheScope - This is the scope for the block itself, which containsfile://localhost/Volumes/Data/Users/kremenek/llvm/tools/clang
   /// arguments etc.
   Scope *TheScope;
   
@@ -1982,8 +1982,23 @@
   /// to the outer block.
   BlockSemaInfo *PrevBlockInfo;
 };
-
-
+  
+//===--------------------------------------------------------------------===//
+// Typed version of Parser::ExprArg (smart pointer for wrapping Expr pointers).
+template <typename T>
+class ExprOwningPtr : public Action::ExprArg {
+public:
+  ExprOwningPtr(Sema *S, T *expr) : Action::ExprArg(*S, expr) {};
+  
+  void reset(T* p) { Action::ExprArg::operator=(p); }
+  T* get() const { return static_cast<T*>(Action::ExprArg::get()); }
+  T* take() { return static_cast<T*>(Action::ExprArg::take()); }
+  T* release() { return take(); }
+  
+  T& operator*() const { return *get(); }
+  T* operator->() const { return get(); }
+};
+  
 }  // end namespace clang
 
 #endif
diff --git a/lib/Sema/SemaChecking.cpp b/lib/Sema/SemaChecking.cpp
index 92cad10..e52c730 100644
--- a/lib/Sema/SemaChecking.cpp
+++ b/lib/Sema/SemaChecking.cpp
@@ -306,9 +306,10 @@
     TheCall->setArg(i, 0);
   }
 
-  return Owned(new ShuffleVectorExpr(exprs.begin(), numElements+2, FAType,
-                                     TheCall->getCallee()->getLocStart(),
-                                     TheCall->getRParenLoc()));
+  return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
+                                            FAType,
+                                            TheCall->getCallee()->getLocStart(),
+                                            TheCall->getRParenLoc()));
 }
 
 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
diff --git a/lib/Sema/SemaDecl.cpp b/lib/Sema/SemaDecl.cpp
index bf16e1a..cdb6930 100644
--- a/lib/Sema/SemaDecl.cpp
+++ b/lib/Sema/SemaDecl.cpp
@@ -2260,7 +2260,7 @@
   // If there is no declaration, there was an error parsing it.  Just ignore
   // the initializer.
   if (RealDecl == 0) {
-    delete Init;
+    Init->Destroy(Context);
     return;
   }
   
@@ -2697,8 +2697,10 @@
     assert(FD == getCurFunctionDecl() && "Function parsing confused");
   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
     MD->setBody((Stmt*)Body);
-  } else
+  } else {
+    Body->Destroy(Context);
     return 0;
+  }
   PopDeclContext();
   // Verify and clean out per-function state.
   
@@ -2717,11 +2719,17 @@
       // the function body so that they aren't leaked and that the AST is well
       // formed.
       if (Body) {
-        L->setSubStmt(new NullStmt(L->getIdentLoc()));
-        cast<CompoundStmt>(Body)->push_back(L);
+#if 0
+        // FIXME: Why do this?  Having a 'push_back' in CompoundStmt is ugly,
+        // and the AST is malformed anyway.  We should just blow away 'L'.
+        L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
+        cast<CompoundStmt>(Body)->push_back(L);        
+#else
+        L->Destroy(Context);
+#endif
       } else {
         // The whole function wasn't parsed correctly, just delete this.
-        delete L;
+        L->Destroy(Context);
       }
     }
   }
@@ -3516,7 +3524,7 @@
       else
         Diag(IdLoc, diag::err_redefinition) << Id;
       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
-      delete Val;
+      Val->Destroy(Context);
       return 0;
     }
   }
@@ -3530,7 +3538,7 @@
     // C99 6.7.2.2p2: Make sure we have an integer constant expression.
     SourceLocation ExpLoc;
     if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
-      delete Val;
+      Val->Destroy(Context);
       Val = 0;  // Just forget about it.
     } else {
       EltTy = Val->getType();
@@ -3721,8 +3729,8 @@
     
     // Adjust the Expr initializer and type.
     if (ECD->getInitExpr())
-      ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(), 
-                                            /*isLvalue=*/false));
+      ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy, ECD->getInitExpr(), 
+                                                      /*isLvalue=*/false));
     if (getLangOptions().CPlusPlus)
       // C++ [dcl.enum]p4: Following the closing brace of an
       // enum-specifier, each enumerator has the type of its
@@ -3756,7 +3764,7 @@
         !Val.isPowerOf2() ||
         Val.getZExtValue() > 16) {
       Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
-      delete Alignment;
+      Alignment->Destroy(Context);
       return; // Ignore
     }
 
diff --git a/lib/Sema/SemaDeclCXX.cpp b/lib/Sema/SemaDeclCXX.cpp
index 35050e5..c4c526e 100644
--- a/lib/Sema/SemaDeclCXX.cpp
+++ b/lib/Sema/SemaDeclCXX.cpp
@@ -107,7 +107,7 @@
 Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc, 
                                 ExprTy *defarg) {
   ParmVarDecl *Param = (ParmVarDecl *)param;
-  llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
+  ExprOwningPtr<Expr> DefaultArg(this, (Expr *)defarg);
   QualType ParamType = Param->getType();
 
   // Default arguments are only permitted in C++
@@ -1503,7 +1503,7 @@
   // the initializer.
   if (RealDecl == 0) {
     for (unsigned i = 0; i != NumExprs; ++i)
-      delete static_cast<Expr *>(ExprTys[i]);
+      static_cast<Expr *>(ExprTys[i])->Destroy(Context);
     return;
   }
   
diff --git a/lib/Sema/SemaExpr.cpp b/lib/Sema/SemaExpr.cpp
index 201a0f9..8ce8bfd 100644
--- a/lib/Sema/SemaExpr.cpp
+++ b/lib/Sema/SemaExpr.cpp
@@ -454,8 +454,7 @@
   if (BaseObject) {
     // BaseObject is an anonymous struct/union variable (and is,
     // therefore, not part of another non-anonymous record).
-    delete BaseObjectExpr;
-
+    if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
     BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
                                      SourceLocation());
     ExtraQuals 
@@ -1770,7 +1769,7 @@
         << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
     // Use default arguments for missing arguments
     NumArgsToCheck = NumArgsInProto;
-    Call->setNumArgs(NumArgsInProto);
+    Call->setNumArgs(Context, NumArgsInProto);
   }
 
   // If too many are passed and not variadic, error on the extras and drop
@@ -1783,7 +1782,7 @@
         << SourceRange(Args[NumArgsInProto]->getLocStart(),
                        Args[NumArgs-1]->getLocEnd());
       // This deletes the extra arguments.
-      Call->setNumArgs(NumArgsInProto);
+      Call->setNumArgs(Context, NumArgsInProto);
       Invalid = true;
     }
     NumArgsToCheck = NumArgsInProto;
@@ -1945,7 +1944,7 @@
   // of arguments and function on error.
   // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
   // Destroy(), or nothing gets cleaned up.
-  llvm::OwningPtr<CallExpr> TheCall(new (Context) CallExpr(Fn, Args, NumArgs,
+  ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Fn, Args,NumArgs,
                                                  Context.BoolTy, RParenLoc));
 
   const FunctionType *FuncT;
@@ -4154,7 +4153,7 @@
       // Offset of an array sub-field.  TODO: Should we allow vector elements?
       const ArrayType *AT = Context.getAsArrayType(Res->getType());
       if (!AT) {
-        delete Res;
+        Res->Destroy(Context);
         return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
       }
       
@@ -4173,7 +4172,7 @@
     
     const RecordType *RC = Res->getType()->getAsRecordType();
     if (!RC) {
-      delete Res;
+      Res->Destroy(Context);
       return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
     }
       
@@ -4336,7 +4335,7 @@
                                           Scope *CurScope) {
   // Ensure that CurBlock is deleted.
   llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
-  llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
+  ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
 
   PopDeclContext();
 
diff --git a/lib/Sema/SemaExprCXX.cpp b/lib/Sema/SemaExprCXX.cpp
index 2a7c9a8..748eddc 100644
--- a/lib/Sema/SemaExprCXX.cpp
+++ b/lib/Sema/SemaExprCXX.cpp
@@ -70,8 +70,8 @@
 
   QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
 
-  return new CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(),
-                           SourceRange(OpLoc, RParenLoc));
+  return new (Context) CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(),
+                                     SourceRange(OpLoc, RParenLoc));
 }
 
 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
@@ -79,13 +79,13 @@
 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
   assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
          "Unknown C++ Boolean value!");
-  return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
+  return new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
 }
 
 /// ActOnCXXThrow - Parse throw expressions.
 Action::ExprResult
 Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
-  return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
+  return new (Context) CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
 }
 
 Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
@@ -100,7 +100,7 @@
 
   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
     if (MD->isInstance())
-      return new CXXThisExpr(ThisLoc, MD->getThisType(Context));
+      return new (Context) CXXThisExpr(ThisLoc, MD->getThisType(Context));
 
   return Diag(ThisLoc, diag::err_invalid_this_use);
 }
@@ -129,8 +129,8 @@
   if (NumExprs == 1) {
     if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
       return true;
-    return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc, 
-                                     Exprs[0], RParenLoc);
+    return new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty,
+                                               TyBeginLoc, Exprs[0], RParenLoc);
   }
 
   if (const RecordType *RT = Ty->getAsRecordType()) {
@@ -148,7 +148,7 @@
       if (!Constructor)
         return true;
 
-      return new CXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc, 
+      return new (Context) CXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc, 
                                         Exprs, NumExprs, RParenLoc);
     }
 
@@ -178,7 +178,7 @@
                              diag::err_invalid_incomplete_type_use, FullRange))
     return true;
 
-  return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
+  return new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
 }
 
 
@@ -312,8 +312,8 @@
 
   // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
 
-  return new CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs, NumPlaceArgs,
-                        ParenTypeId, ArraySize, Constructor, Init,
+  return new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
+                        NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
                         ConsArgs, NumConsArgs, OperatorDelete, ResultType,
                         StartLoc, Init ? ConstructorRParen : SourceLocation());
 }
@@ -384,7 +384,7 @@
   // We don't care about the actual value of this argument.
   // FIXME: Should the Sema create the expression and embed it in the syntax
   // tree? Or should the consumer just recalculate the value?
-  AllocArgs[0] = new IntegerLiteral(llvm::APInt::getNullValue(
+  AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
                                         Context.Target.getPointerWidth(0)),
                                     Context.getSizeType(),
                                     SourceLocation());
@@ -533,7 +533,7 @@
       // FIXME: Do we need to check for default arguments here?
       FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
       if (Func->getNumParams() == 1 &&
-          Context.getCanonicalType(Func->getParamDecl(0)->getType()) == Argument)
+          Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
         return;
     }
   }
@@ -594,8 +594,8 @@
   // along.
   // FIXME: Check access and ambiguity of operator delete and destructor.
 
-  return new CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 0, Ex,
-                           StartLoc);
+  return new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 0,
+                                     Ex, StartLoc);
 }
 
 
@@ -648,7 +648,7 @@
   if (VarDecl *VD = dyn_cast<VarDecl>((Decl *)Dcl))
     VD->setDeclaredInCondition(true);
 
-  return new CXXConditionDeclExpr(StartLoc, EqualLoc,
+  return new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc,
                                        cast<VarDecl>(static_cast<Decl *>(Dcl)));
 }
 
@@ -879,7 +879,7 @@
   // There is no point in eagerly computing the value. The traits are designed
   // to be used from type trait templates, so Ty will be a template parameter
   // 99% of the time.
-  return Owned(new UnaryTypeTraitExpr(KWLoc, OTT,
+  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
                                       QualType::getFromOpaquePtr(Ty),
                                       RParen, Context.BoolTy));
 }
diff --git a/lib/Sema/SemaExprObjC.cpp b/lib/Sema/SemaExprObjC.cpp
index 003e121..32ff7ff 100644
--- a/lib/Sema/SemaExprObjC.cpp
+++ b/lib/Sema/SemaExprObjC.cpp
@@ -38,7 +38,7 @@
         isWide = true;
       memcpy(p, S->getStrData(), S->getByteLength());
       p += S->getByteLength();
-      delete S;
+      S->Destroy(Context);
     }
     S = new (Context, 8) StringLiteral(Context, strBuf, Length, isWide,
                                        Context.getPointerType(Context.CharTy),
@@ -65,7 +65,7 @@
   } else {
     t = Context.getPointerType(t);
   }
-  return new ObjCStringLiteral(S, t, AtLoc);
+  return new (Context) ObjCStringLiteral(S, t, AtLoc);
 }
 
 Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
@@ -76,7 +76,7 @@
   QualType EncodedType = QualType::getFromOpaquePtr(Ty);
 
   QualType t = Context.getPointerType(Context.CharTy);
-  return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
+  return new (Context) ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
 }
 
 Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
@@ -85,7 +85,7 @@
                                                    SourceLocation LParenLoc,
                                                    SourceLocation RParenLoc) {
   QualType t = Context.getObjCSelType();
-  return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
+  return new (Context) ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
 }
 
 Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
@@ -103,7 +103,7 @@
   if (t.isNull())
     return true;
   t = Context.getPointerType(t);
-  return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
+  return new (Context) ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
 }
 
 bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs, 
@@ -199,7 +199,8 @@
       if (getCurMethodDecl()->isInstanceMethod()) {
         QualType superTy = Context.getObjCInterfaceType(ClassDecl);
         superTy = Context.getPointerType(superTy);
-        ExprResult ReceiverExpr = new ObjCSuperExpr(SourceLocation(), superTy);
+        ExprResult ReceiverExpr = new (Context) ObjCSuperExpr(SourceLocation(),
+                                                              superTy);
         // We are really in an instance method, redirect.
         return ActOnInstanceMessage(ReceiverExpr.get(), Sel, lbrac, rbrac,
                                     Args, NumArgs);
@@ -212,8 +213,8 @@
       NamedDecl *SuperDecl = LookupName(S, receiverName, LookupOrdinaryName);
       ValueDecl *VD = dyn_cast_or_null<ValueDecl>(SuperDecl);
       if (VD) {
-        ExprResult ReceiverExpr = new DeclRefExpr(VD, VD->getType(), 
-                                                  receiverLoc);
+        ExprResult ReceiverExpr = new (Context) DeclRefExpr(VD, VD->getType(), 
+                                                            receiverLoc);
         // We are really in an instance method, redirect.
         return ActOnInstanceMessage(ReceiverExpr.get(), Sel, lbrac, rbrac,
                                     Args, NumArgs);
@@ -277,11 +278,11 @@
   // For now, we simply pass the "super" identifier through (which isn't
   // consistent with instance methods.
   if (isSuper)
-    return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
-                               lbrac, rbrac, ArgExprs, NumArgs);
+    return new (Context) ObjCMessageExpr(receiverName, Sel, returnType, Method,
+                                         lbrac, rbrac, ArgExprs, NumArgs);
   else
-    return new ObjCMessageExpr(ClassDecl, Sel, returnType, Method,
-                               lbrac, rbrac, ArgExprs, NumArgs);
+    return new (Context) ObjCMessageExpr(ClassDecl, Sel, returnType, Method,
+                                         lbrac, rbrac, ArgExprs, NumArgs);
 }
 
 // ActOnInstanceMessage - used for both unary and keyword messages.
@@ -312,8 +313,8 @@
     if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false,
                                   lbrac, rbrac, returnType))
       return true;
-    return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac, 
-                               ArgExprs, NumArgs);
+    return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac,
+                                         rbrac, ArgExprs, NumArgs);
   }
 
   // Handle messages to id.
@@ -326,8 +327,8 @@
     if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false, 
                                   lbrac, rbrac, returnType))
       return true;
-    return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac, 
-                               ArgExprs, NumArgs);
+    return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac,
+                                         rbrac, ArgExprs, NumArgs);
   }
   
   // Handle messages to Class.
@@ -348,8 +349,8 @@
     if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false,
                                   lbrac, rbrac, returnType))
       return true;
-    return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac, 
-                               ArgExprs, NumArgs);
+    return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac,
+                                         rbrac, ArgExprs, NumArgs);
   }
   
   ObjCMethodDecl *Method = 0;
@@ -411,8 +412,8 @@
   if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false,
                                 lbrac, rbrac, returnType))
     return true;
-  return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac, 
-                             ArgExprs, NumArgs);
+  return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac,
+                                       rbrac, ArgExprs, NumArgs);
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/lib/Sema/SemaNamedCast.cpp b/lib/Sema/SemaNamedCast.cpp
index e2137b3..c5bee98 100644
--- a/lib/Sema/SemaNamedCast.cpp
+++ b/lib/Sema/SemaNamedCast.cpp
@@ -76,26 +76,26 @@
   case tok::kw_const_cast:
     if (!TypeDependent)
       CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
-    return new CXXConstCastExpr(DestType.getNonReferenceType(), Ex, 
-                                DestType, OpLoc);
+    return new (Context) CXXConstCastExpr(DestType.getNonReferenceType(), Ex, 
+                                          DestType, OpLoc);
 
   case tok::kw_dynamic_cast:
     if (!TypeDependent)
       CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange);
-    return new CXXDynamicCastExpr(DestType.getNonReferenceType(), Ex, 
-                                  DestType, OpLoc);
+    return new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(), Ex, 
+                                           DestType, OpLoc);
 
   case tok::kw_reinterpret_cast:
     if (!TypeDependent)
       CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange);
-    return new CXXReinterpretCastExpr(DestType.getNonReferenceType(), Ex, 
-                                      DestType, OpLoc);
+    return new (Context) CXXReinterpretCastExpr(DestType.getNonReferenceType(),
+                                                Ex, DestType, OpLoc);
 
   case tok::kw_static_cast:
     if (!TypeDependent)
       CheckStaticCast(*this, Ex, DestType, OpRange);
-    return new CXXStaticCastExpr(DestType.getNonReferenceType(), Ex, 
-                                 DestType, OpLoc);
+    return new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(), Ex, 
+                                           DestType, OpLoc);
   }
 
   return true;
diff --git a/lib/Sema/SemaOverload.cpp b/lib/Sema/SemaOverload.cpp
index cb65900..69bbf0e 100644
--- a/lib/Sema/SemaOverload.cpp
+++ b/lib/Sema/SemaOverload.cpp
@@ -3600,9 +3600,9 @@
   // Extract the object argument.
   Expr *ObjectArg = MemExpr->getBase();
   if (MemExpr->isArrow())
-    ObjectArg = new UnaryOperator(ObjectArg, UnaryOperator::Deref,
-                      ObjectArg->getType()->getAsPointerType()->getPointeeType(),
-                      SourceLocation());
+    ObjectArg = new (Context) UnaryOperator(ObjectArg, UnaryOperator::Deref,
+                     ObjectArg->getType()->getAsPointerType()->getPointeeType(),
+                     SourceLocation());
   CXXMethodDecl *Method = 0;
   if (OverloadedFunctionDecl *Ovl 
         = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
@@ -3647,8 +3647,8 @@
   }
 
   assert(Method && "Member call to something that isn't a method?");
-  llvm::OwningPtr<CXXMemberCallExpr> 
-    TheCall(new CXXMemberCallExpr(MemExpr, Args, NumArgs, 
+  ExprOwningPtr<CXXMemberCallExpr> 
+    TheCall(this, new (Context) CXXMemberCallExpr(MemExpr, Args, NumArgs, 
                                   Method->getResultType().getNonReferenceType(),
                                   RParenLoc));
 
@@ -3759,9 +3759,9 @@
   if (Best == CandidateSet.end()) {
     // We had an error; delete all of the subexpressions and return
     // the error.
-    delete Object;
+    Object->Destroy(Context);
     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
-      delete Args[ArgIdx];
+      Args[ArgIdx]->Destroy(Context);
     return true;
   }
 
@@ -3807,22 +3807,23 @@
   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
     MethodArgs[ArgIdx + 1] = Args[ArgIdx];
       
-  Expr *NewFn = new DeclRefExpr(Method, Method->getType(), 
-                                SourceLocation());
+  Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(), 
+                                          SourceLocation());
   UsualUnaryConversions(NewFn);
 
   // Once we've built TheCall, all of the expressions are properly
   // owned.
   QualType ResultTy = Method->getResultType().getNonReferenceType();
-  llvm::OwningPtr<CXXOperatorCallExpr> 
-    TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1,
-                                    ResultTy, RParenLoc));
+  ExprOwningPtr<CXXOperatorCallExpr> 
+    TheCall(this, new (Context) CXXOperatorCallExpr(NewFn, MethodArgs,
+                                                    NumArgs + 1,
+                                                    ResultTy, RParenLoc));
   delete [] MethodArgs;
 
   // We may have default arguments. If so, we need to allocate more
   // slots in the call for them.
   if (NumArgs < NumArgsInProto)
-    TheCall->setNumArgs(NumArgsInProto + 1);
+    TheCall->setNumArgs(Context, NumArgsInProto + 1);
   else if (NumArgs > NumArgsInProto)
     NumArgsToCheck = NumArgsInProto;
 
@@ -3842,7 +3843,7 @@
       if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
         return true;
     } else {
-      Arg = new CXXDefaultArgExpr(Method->getParamDecl(i));
+      Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
     }
 
     TheCall->setArg(i + 1, Arg);
@@ -3888,7 +3889,7 @@
     AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
                        /*SuppressUserConversions=*/false);
 
-  llvm::OwningPtr<Expr> BasePtr(Base);
+  ExprOwningPtr<Expr> BasePtr(this, Base);
 
   // Perform overload resolution.
   OverloadCandidateSet::iterator Best;
@@ -3924,9 +3925,10 @@
   BasePtr.take();
 
   // Build the operator call.
-  Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation());
+  Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
+                                           SourceLocation());
   UsualUnaryConversions(FnExpr);
-  Base = new CXXOperatorCallExpr(FnExpr, &Base, 1, 
+  Base = new (Context) CXXOperatorCallExpr(FnExpr, &Base, 1, 
                                  Method->getResultType().getNonReferenceType(),
                                  OpLoc);
   return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
diff --git a/lib/Sema/SemaStmt.cpp b/lib/Sema/SemaStmt.cpp
index 7697dbd..18d9ad6 100644
--- a/lib/Sema/SemaStmt.cpp
+++ b/lib/Sema/SemaStmt.cpp
@@ -16,6 +16,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/Expr.h"
+#include "clang/AST/ASTContext.h"
 #include "clang/Basic/TargetInfo.h"
 using namespace clang;
 
@@ -33,7 +34,7 @@
 
 
 Sema::OwningStmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) {
-  return Owned(new NullStmt(SemiLoc));
+  return Owned(new (Context) NullStmt(SemiLoc));
 }
 
 Sema::OwningStmtResult Sema::ActOnDeclStmt(DeclTy *decl,
@@ -58,11 +59,11 @@
 
   if (decls.size() == 1) {
     DeclGroupOwningRef DG(*decls.begin());                      
-    return Owned(new DeclStmt(DG, StartLoc, EndLoc));
+    return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
   }
   else {
     DeclGroupOwningRef DG(DeclGroup::Create(Context, decls.size(), &decls[0]));
-    return Owned(new DeclStmt(DG, StartLoc, EndLoc));
+    return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
   }
 }
 
@@ -115,7 +116,7 @@
       Diag(E->getExprLoc(), diag::warn_unused_expr) << E->getSourceRange();
   }
 
-  return Owned(new CompoundStmt(Elts, NumElts, L, R));
+  return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
 }
 
 Action::OwningStmtResult
@@ -148,7 +149,7 @@
   // Only now release the smart pointers.
   lhsval.release();
   rhsval.release();
-  CaseStmt *CS = new CaseStmt(LHSVal, RHSVal, SubStmt, CaseLoc);
+  CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, SubStmt, CaseLoc);
   SwitchStack.back()->addSwitchCase(CS);
   return Owned(CS);
 }
@@ -163,7 +164,7 @@
     return Owned(SubStmt);
   }
 
-  DefaultStmt *DS = new DefaultStmt(DefaultLoc, SubStmt);
+  DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, SubStmt);
   SwitchStack.back()->addSwitchCase(DS);
   return Owned(DS);
 }
@@ -177,7 +178,7 @@
 
   // If not forward referenced or defined already, just create a new LabelStmt.
   if (LabelDecl == 0)
-    return Owned(LabelDecl = new LabelStmt(IdentLoc, II, SubStmt));
+    return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt));
 
   assert(LabelDecl->getID() == II && "Label mismatch!");
 
@@ -228,7 +229,8 @@
   }
 
   CondVal.release();
-  return Owned(new IfStmt(IfLoc, condExpr, thenStmt, (Stmt*)ElseVal.release()));
+  return Owned(new (Context) IfStmt(IfLoc, condExpr, thenStmt,
+                                    (Stmt*)ElseVal.release()));
 }
 
 Action::OwningStmtResult
@@ -260,7 +262,7 @@
     UsualUnaryConversions(Cond);
   }
 
-  SwitchStmt *SS = new SwitchStmt(Cond);
+  SwitchStmt *SS = new (Context) SwitchStmt(Cond);
   SwitchStack.push_back(SS);
   return Owned(SS);
 }
@@ -549,7 +551,8 @@
       << condType << condExpr->getSourceRange());
 
   Cond.release();
-  return Owned(new WhileStmt(condExpr, (Stmt*)Body.release(), WhileLoc));
+  return Owned(new (Context) WhileStmt(condExpr, (Stmt*)Body.release(),
+                                       WhileLoc));
 }
 
 Action::OwningStmtResult
@@ -570,7 +573,7 @@
       << condType << condExpr->getSourceRange());
 
   Cond.release();
-  return Owned(new DoStmt((Stmt*)Body.release(), condExpr, DoLoc));
+  return Owned(new (Context) DoStmt((Stmt*)Body.release(), condExpr, DoLoc));
 }
 
 Action::OwningStmtResult
@@ -614,7 +617,7 @@
   second.release();
   third.release();
   body.release();
-  return Owned(new ForStmt(First, Second, Third, Body, ForLoc));
+  return Owned(new (Context) ForStmt(First, Second, Third, Body, ForLoc));
 }
 
 Action::OwningStmtResult
@@ -665,8 +668,8 @@
   first.release();
   second.release();
   body.release();
-  return Owned(new ObjCForCollectionStmt(First, Second, Body,
-                                         ForLoc, RParenLoc));
+  return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
+                                                   ForLoc, RParenLoc));
 }
 
 Action::OwningStmtResult
@@ -681,9 +684,9 @@
 
   // If we haven't seen this label yet, create a forward reference.
   if (LabelDecl == 0)
-    LabelDecl = new LabelStmt(LabelLoc, LabelII, 0);
+    LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0);
 
-  return Owned(new GotoStmt(LabelDecl, GotoLoc, LabelLoc));
+  return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc));
 }
 
 Action::OwningStmtResult
@@ -691,7 +694,7 @@
                             ExprArg DestExp) {
   // FIXME: Verify that the operand is convertible to void*.
 
-  return Owned(new IndirectGotoStmt((Expr*)DestExp.release()));
+  return Owned(new (Context) IndirectGotoStmt((Expr*)DestExp.release()));
 }
 
 Action::OwningStmtResult
@@ -702,7 +705,7 @@
     return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
   }
 
-  return Owned(new ContinueStmt(ContinueLoc));
+  return Owned(new (Context) ContinueStmt(ContinueLoc));
 }
 
 Action::OwningStmtResult
@@ -713,7 +716,7 @@
     return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
   }
 
-  return Owned(new BreakStmt(BreakLoc));
+  return Owned(new (Context) BreakStmt(BreakLoc));
 }
 
 /// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
@@ -740,10 +743,10 @@
   if (CurBlock->ReturnType->isVoidType()) {
     if (RetValExp) {
       Diag(ReturnLoc, diag::err_return_block_has_expr);
-      delete RetValExp;
+      RetValExp->Destroy(Context);
       RetValExp = 0;
     }
-    return Owned(new ReturnStmt(ReturnLoc, RetValExp));
+    return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
   }
 
   if (!RetValExp)
@@ -766,7 +769,7 @@
     if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
   }
 
-  return Owned(new ReturnStmt(ReturnLoc, RetValExp));
+  return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
 }
 
 Action::OwningStmtResult
@@ -796,7 +799,7 @@
           << RetValExp->getSourceRange();
       }
     }
-    return Owned(new ReturnStmt(ReturnLoc, RetValExp));
+    return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
   }
 
   if (!RetValExp) {
@@ -808,7 +811,7 @@
       Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
     else
       Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
-    return Owned(new ReturnStmt(ReturnLoc, (Expr*)0));
+    return Owned(new (Context) ReturnStmt(ReturnLoc, (Expr*)0));
   }
 
   if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
@@ -828,7 +831,7 @@
     if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
   }
 
-  return Owned(new ReturnStmt(ReturnLoc, RetValExp));
+  return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
 }
 
 Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
@@ -945,9 +948,10 @@
   exprs.release();
   asmString.release();
   clobbers.release();
-  return Owned(new AsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs,
-                           Names, Constraints, Exprs, AsmString, NumClobbers,
-                           Clobbers, RParenLoc));
+  return Owned(new (Context) AsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
+                                     NumInputs, Names, Constraints, Exprs,
+                                     AsmString, NumClobbers,
+                                     Clobbers, RParenLoc));
 }
 
 Action::OwningStmtResult
@@ -955,7 +959,7 @@
                            SourceLocation RParen, StmtArg Parm,
                            StmtArg Body, StmtArg catchList) {
   Stmt *CatchList = static_cast<Stmt*>(catchList.release());
-  ObjCAtCatchStmt *CS = new ObjCAtCatchStmt(AtLoc, RParen,
+  ObjCAtCatchStmt *CS = new (Context) ObjCAtCatchStmt(AtLoc, RParen,
     static_cast<Stmt*>(Parm.release()), static_cast<Stmt*>(Body.release()),
     CatchList);
   return Owned(CatchList ? CatchList : CS);
@@ -963,27 +967,29 @@
 
 Action::OwningStmtResult
 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) {
-  return Owned(new ObjCAtFinallyStmt(AtLoc,
-                                     static_cast<Stmt*>(Body.release())));
+  return Owned(new (Context) ObjCAtFinallyStmt(AtLoc,
+                                           static_cast<Stmt*>(Body.release())));
 }
 
 Action::OwningStmtResult
 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc,
                          StmtArg Try, StmtArg Catch, StmtArg Finally) {
-  return Owned(new ObjCAtTryStmt(AtLoc, static_cast<Stmt*>(Try.release()),
+  return Owned(new (Context) ObjCAtTryStmt(AtLoc,
+                                        static_cast<Stmt*>(Try.release()),
                                         static_cast<Stmt*>(Catch.release()),
                                         static_cast<Stmt*>(Finally.release())));
 }
 
 Action::OwningStmtResult
 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg Throw) {
-  return Owned(new ObjCAtThrowStmt(AtLoc, static_cast<Expr*>(Throw.release())));
+  return Owned(new (Context) ObjCAtThrowStmt(AtLoc,
+                                          static_cast<Expr*>(Throw.release())));
 }
 
 Action::OwningStmtResult
 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr,
                                   StmtArg SynchBody) {
-  return Owned(new ObjCAtSynchronizedStmt(AtLoc,
+  return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc,
                      static_cast<Stmt*>(SynchExpr.release()),
                      static_cast<Stmt*>(SynchBody.release())));
 }
@@ -994,8 +1000,9 @@
 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclTy *ExDecl,
                          StmtArg HandlerBlock) {
   // There's nothing to test that ActOnExceptionDecl didn't already test.
-  return Owned(new CXXCatchStmt(CatchLoc, static_cast<VarDecl*>(ExDecl),
-                                static_cast<Stmt*>(HandlerBlock.release())));
+  return Owned(new (Context) CXXCatchStmt(CatchLoc,
+                                  static_cast<VarDecl*>(ExDecl),
+                                  static_cast<Stmt*>(HandlerBlock.release())));
 }
 
 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
@@ -1022,6 +1029,7 @@
   // and warns.
 
   RawHandlers.release();
-  return Owned(new CXXTryStmt(TryLoc, static_cast<Stmt*>(TryBlock.release()),
-                              Handlers, NumHandlers));
+  return Owned(new (Context) CXXTryStmt(TryLoc,
+                                        static_cast<Stmt*>(TryBlock.release()),
+                                        Handlers, NumHandlers));
 }
diff --git a/lib/Sema/SemaType.cpp b/lib/Sema/SemaType.cpp
index e6d1833..e206c40 100644
--- a/lib/Sema/SemaType.cpp
+++ b/lib/Sema/SemaType.cpp
@@ -424,7 +424,10 @@
         Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
           << ArraySize->getType() << ArraySize->getSourceRange();
         D.setInvalidType(true);
-        delete ArraySize;
+        
+        Context.Deallocate(ArraySize);
+        ArraySize->~Expr();
+
         ATI.NumElts = ArraySize = 0;
       }
       llvm::APSInt ConstVal(32);