blob: a8fefb01656d2f2e0fc534303b004f90ca2535d0 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar9b414d32010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000035 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000036 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000037 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000041 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000042 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000043 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000044 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner2c64b7b2007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattner01c57482007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner5f9e2722011-07-23 10:55:15 +000070 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000072 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +000076 SmallVector<Stmt *, 32> Stmts;
77 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffd82a9ab2008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000084
Steve Naroffebf2b562007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Fariborz Jahanianb586cce2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Steve Naroff874e2322007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Steve Naroff621edce2009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Steve Naroffa7b402d2008-03-28 22:26:09 +0000115 std::string InFileName;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000116 raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000120
Steve Naroffba92b2e2008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000122
123 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000124 SmallVector<BlockExpr *, 32> Blocks;
125 SmallVector<int, 32> InnerDeclRefsCount;
126 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000127
Chris Lattner5f9e2722011-07-23 10:55:15 +0000128 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Steve Naroff54055232008-10-27 17:20:55 +0000130 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000131 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000133 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff54055232008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroffc77a6362008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000142 llvm::DenseMap<Expr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000145 llvm::DenseMap<Expr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Steve Naroff4c3580e2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000151
Steve Naroff54055232008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Steve Naroffb619d952008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Nick Lewycky7e749242010-10-31 21:07:24 +0000158 static const int OBJC_ABI_VERSION = 7;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000159 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattnerf04da132007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
165 HandleTopLevelSingleDecl(*I);
166 }
167 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000168 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000169 RewriteObjC(std::string inFile, raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000170 Diagnostic &D, const LangOptions &LOpts,
171 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000172
173 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000175 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000177 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000178 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Steve Naroff4c3580e2008-12-04 23:50:32 +0000180 if (ReplacingStmt)
181 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000182
Steve Naroffb619d952008-12-09 12:56:34 +0000183 if (DisableReplaceStmt)
184 return; // Used when rewriting the assignment of a property setter.
185
Steve Naroff4c3580e2008-12-04 23:50:32 +0000186 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000187 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000188 ReplacedNodes[Old] = New;
189 return;
190 }
191 if (SilenceRewriteMacroWarning)
192 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000193 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
194 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000195 }
Steve Naroffb619d952008-12-09 12:56:34 +0000196
197 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Nick Lewycky7e749242010-10-31 21:07:24 +0000198 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000199 int Size = Rewrite.getRangeSize(SrcRange);
200 if (Size == -1) {
201 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
202 << Old->getSourceRange();
203 return;
204 }
205 // Get the new text.
206 std::string SStr;
207 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000208 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000209 const std::string &Str = S.str();
210
211 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000212 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000213 ReplacedNodes[Old] = New;
214 return;
215 }
216 if (SilenceRewriteMacroWarning)
217 return;
218 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
219 << Old->getSourceRange();
220 }
221
Chris Lattner5f9e2722011-07-23 10:55:15 +0000222 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000223 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000224 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000225 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000226 SilenceRewriteMacroWarning)
227 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230 }
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattneraadaf782008-01-31 19:51:04 +0000232 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000233 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000234 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000235 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000236 SilenceRewriteMacroWarning)
237 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
240 }
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattnerf04da132007-10-24 17:06:59 +0000242 // Syntactic Rewriting.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000243 void RewriteInclude();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000244 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000245 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
246 ObjCImplementationDecl *IMD,
247 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000248 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000249 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000250 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
251 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000252 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
253 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000254 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000255 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000256 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
257 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
258 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
259 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000260 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000261 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000262 void RewriteBlockPointerType(std::string& Str, QualType Type);
263 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000266 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000267 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000268 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000269 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000270 QualType getConstantStringStructType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +0000271 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffbaf58c32008-05-31 14:15:04 +0000272 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattnerf04da132007-10-24 17:06:59 +0000274 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000275 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000276 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Steve Naroff8599e7a2008-12-08 16:43:47 +0000278 Stmt *CurrentBody;
279 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattnere64b7772007-10-24 16:57:36 +0000281 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000282 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
283 bool &replaced);
284 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000285 Stmt *RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr);
286 Stmt *RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000287 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000288 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000289 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000290 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000291 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000292 void WarnAboutReturnGotoStmts(Stmt *S);
293 void HasReturnStmts(Stmt *S, bool &hasReturns);
294 void RewriteTryReturnStmts(Stmt *S);
295 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000296 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000297 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000298 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000299 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
300 SourceLocation OrigEnd);
Fariborz Jahanian42f1e652011-02-24 21:29:21 +0000301 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Mike Stump1eb44332009-09-09 15:08:12 +0000302 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000303 Expr **args, unsigned nargs,
304 SourceLocation StartLoc=SourceLocation(),
305 SourceLocation EndLoc=SourceLocation());
306 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
307 SourceLocation StartLoc=SourceLocation(),
308 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000309 Stmt *RewriteBreakStmt(BreakStmt *S);
310 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000311 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Steve Naroff09b266e2007-10-30 23:14:51 +0000313 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000314 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000315 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000316 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000317 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000318 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000319 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000320 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000321 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000322 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Chris Lattnerf04da132007-10-24 17:06:59 +0000324 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000325 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000326 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000328 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000329 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Douglas Gregor653f1b12009-04-23 01:02:12 +0000331 template<typename MethodIterator>
332 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
333 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000334 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000335 StringRef prefix,
336 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +0000337 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Steve Naroff621edce2009-04-29 16:37:50 +0000339 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000340 StringRef prefix,
341 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000342 std::string &Result);
343 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000344 StringRef prefix,
345 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000346 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000347 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000348 std::string &Result);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000349 void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000350 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000351 void RewriteImplementations();
352 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Steve Naroff54055232008-10-27 17:20:55 +0000354 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000355 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000356 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Steve Naroff54055232008-10-27 17:20:55 +0000358 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
359 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000360
361 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000362 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000363 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000364 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000365 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000366 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000367 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000368
369 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000370 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000371 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000372 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000373 std::string SynthesizeBlockImpl(BlockExpr *CE,
374 std::string Tag, std::string Desc);
375 std::string SynthesizeBlockDescriptor(std::string DescTag,
376 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000377 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000378 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000379 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000380 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000381 StringRef FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000382 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Steve Naroff54055232008-10-27 17:20:55 +0000384 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000385 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000386 void GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000387 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000388 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Steve Naroff54055232008-10-27 17:20:55 +0000390 // We avoid calling Type::isBlockPointerType(), since it operates on the
391 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000392 bool isTopLevelBlockPointerType(QualType T) {
393 return isa<BlockPointerType>(T);
394 }
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000396 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
397 /// to a function pointer type and upon success, returns true; false
398 /// otherwise.
399 bool convertBlockPointerToFunctionPointer(QualType &T) {
400 if (isTopLevelBlockPointerType(T)) {
401 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
402 T = Context->getPointerType(BPT->getPointeeType());
403 return true;
404 }
405 return false;
406 }
407
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000408 void convertToUnqualifiedObjCType(QualType &T) {
409 if (T->isObjCQualifiedIdType())
410 T = Context->getObjCIdType();
411 else if (T->isObjCQualifiedClassType())
412 T = Context->getObjCClassType();
413 else if (T->isObjCObjectPointerType() &&
414 T->getPointeeType()->isObjCQualifiedInterfaceType())
415 T = Context->getObjCIdType();
416 }
417
Steve Naroff54055232008-10-27 17:20:55 +0000418 // FIXME: This predicate seems like it would be useful to add to ASTContext.
419 bool isObjCType(QualType T) {
420 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
421 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Steve Naroff54055232008-10-27 17:20:55 +0000423 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Steve Naroff54055232008-10-27 17:20:55 +0000425 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
426 OCT == Context->getCanonicalType(Context->getObjCClassType()))
427 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Ted Kremenek6217b802009-07-29 21:53:49 +0000429 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000430 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000431 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000432 return true;
433 }
434 return false;
435 }
436 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000437 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000438 void GetExtentOfArgList(const char *Name, const char *&LParen,
439 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000440 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Chris Lattner5f9e2722011-07-23 10:55:15 +0000442 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000443 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000444 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Steve Naroff621edce2009-04-29 16:37:50 +0000446 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000447 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000448 if (From[i] == '"')
449 To += "\\\"";
450 else
451 To += From[i];
452 }
453 }
John McCalle23cf432010-12-14 08:05:40 +0000454
455 QualType getSimpleFunctionType(QualType result,
456 const QualType *args,
457 unsigned numArgs,
458 bool variadic = false) {
459 FunctionProtoType::ExtProtoInfo fpi;
460 fpi.Variadic = variadic;
461 return Context->getFunctionType(result, args, numArgs, fpi);
462 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000463 };
John McCall9d125032010-01-15 18:39:57 +0000464
465 // Helper function: create a CStyleCastExpr with trivial type source info.
466 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000467 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000468 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +0000469 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallf871d0c2010-08-07 06:22:56 +0000470 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000471 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000472}
473
Mike Stump1eb44332009-09-09 15:08:12 +0000474void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
475 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000476 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000477 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000478 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000479 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000480 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000481 // All the args are checked/rewritten. Don't call twice!
482 RewriteBlockPointerDecl(D);
483 break;
484 }
485 }
486}
487
488void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000489 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000490 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000491 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000492}
493
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000494static bool IsHeaderFile(const std::string &Filename) {
495 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000497 if (DotPos == std::string::npos) {
498 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000499 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000500 }
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000502 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
503 // C header: .h
504 // C++ header: .hh or .H;
505 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000506}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000507
Chris Lattner5f9e2722011-07-23 10:55:15 +0000508RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000509 Diagnostic &D, const LangOptions &LOpts,
510 bool silenceMacroWarn)
511 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
512 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000513 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000514 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000515 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000516 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000517 "rewriter doesn't support user-specified control flow semantics "
518 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000519}
520
Eli Friedmanbce831b2009-05-18 22:29:17 +0000521ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000522 raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000523 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000524 const LangOptions &LOpts,
525 bool SilenceRewriteMacroWarning) {
526 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000527}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000528
Steve Naroffb29b4272008-04-14 22:03:09 +0000529void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000530 Context = &context;
531 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000532 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000533 MsgSendFunctionDecl = 0;
534 MsgSendSuperFunctionDecl = 0;
535 MsgSendStretFunctionDecl = 0;
536 MsgSendSuperStretFunctionDecl = 0;
537 MsgSendFpretFunctionDecl = 0;
538 GetClassFunctionDecl = 0;
539 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000540 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000541 SelGetUidFunctionDecl = 0;
542 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000543 ConstantStringClassReference = 0;
544 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000545 CurMethodDef = 0;
546 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000547 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000548 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000549 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000550 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000551 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000552 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000553 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000554 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000555 PropParentMap = 0;
556 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000557 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000558 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000560 // Get the ID and start/end of the main file.
561 MainFileID = SM->getMainFileID();
562 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
563 MainFileStart = MainBuf->getBufferStart();
564 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Chris Lattner2c78b872009-04-14 23:22:57 +0000566 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000568 // declaring objc_selector outside the parameter list removes a silly
569 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000570 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000571 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000572 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000573 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000574 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000575 if (LangOpts.Microsoft) {
576 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000577 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
578 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000579 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000580 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000581 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000582 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
583 Preamble += "typedef struct objc_object Protocol;\n";
584 Preamble += "#define _REWRITER_typedef_Protocol\n";
585 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000586 if (LangOpts.Microsoft) {
587 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
588 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
589 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000590 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000591 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000592 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000593 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000594 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000595 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000596 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000597 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000598 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000599 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000600 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000601 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000602 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000603 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
604 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000605 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000606 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000607 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
608 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
609 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
610 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
611 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000612 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000613 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000614 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
615 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
616 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000617 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
618 Preamble += "struct __objcFastEnumerationState {\n\t";
619 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000620 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000621 Preamble += "unsigned long *mutationsPtr;\n\t";
622 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000623 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000624 Preamble += "#define __FASTENUMERATIONSTATE\n";
625 Preamble += "#endif\n";
626 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
627 Preamble += "struct __NSConstantStringImpl {\n";
628 Preamble += " int *isa;\n";
629 Preamble += " int flags;\n";
630 Preamble += " char *str;\n";
631 Preamble += " long length;\n";
632 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000633 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
634 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
635 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000636 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000637 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000638 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
639 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000640 // Blocks preamble.
641 Preamble += "#ifndef BLOCK_IMPL\n";
642 Preamble += "#define BLOCK_IMPL\n";
643 Preamble += "struct __block_impl {\n";
644 Preamble += " void *isa;\n";
645 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000646 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000647 Preamble += " void *FuncPtr;\n";
648 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000649 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000650 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000651 Preamble += "extern \"C\" __declspec(dllexport) "
652 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000653 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
654 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
655 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
656 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000657 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
658 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000659 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
660 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
661 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000662 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000663 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000664 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
665 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000666 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000667 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000668 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000669 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000670 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000671 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000672 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000673 Preamble += "#define __weak\n";
674 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000675 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
676 // as this avoids warning in any 64bit/32bit compilation model.
677 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000678}
679
680
Chris Lattnerf04da132007-10-24 17:06:59 +0000681//===----------------------------------------------------------------------===//
682// Top Level Driver Code
683//===----------------------------------------------------------------------===//
684
Chris Lattner682bf922009-03-29 16:50:03 +0000685void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000686 if (Diags.hasErrorOccurred())
687 return;
688
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000689 // Two cases: either the decl could be in the main file, or it could be in a
690 // #included file. If the former, rewrite it now. If the later, check to see
691 // if we rewrote the #include/#import.
692 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000693 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000695 // If this is for a builtin, ignore it.
696 if (Loc.isInvalid()) return;
697
Steve Naroffebf2b562007-10-23 23:50:29 +0000698 // Look for built-in declarations that we need to refer during the rewrite.
699 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000700 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000701 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000702 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000703 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000704 ConstantStringClassReference = FVD;
705 return;
706 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000707 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000708 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000709 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000710 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000711 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000712 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000713 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000714 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000715 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000716 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
717 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000718 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
719 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000720 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000721 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000722 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000723 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000724 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000725 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000726}
727
Chris Lattnerf04da132007-10-24 17:06:59 +0000728//===----------------------------------------------------------------------===//
729// Syntactic (non-AST) Rewriting Code
730//===----------------------------------------------------------------------===//
731
Steve Naroffb29b4272008-04-14 22:03:09 +0000732void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000733 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000734 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000735 const char *MainBufStart = MainBuf.begin();
736 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000737 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000739 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000740 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
741 if (*BufPtr == '#') {
742 if (++BufPtr == MainBufEnd)
743 return;
744 while (*BufPtr == ' ' || *BufPtr == '\t')
745 if (++BufPtr == MainBufEnd)
746 return;
747 if (!strncmp(BufPtr, "import", ImportLen)) {
748 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000749 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000750 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000751 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000752 BufPtr += ImportLen;
753 }
754 }
755 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000756}
757
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000758static std::string getIvarAccessString(ObjCIvarDecl *OID) {
759 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000760 std::string S;
761 S = "((struct ";
762 S += ClassDecl->getIdentifier()->getName();
763 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000764 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000765 return S;
766}
767
Steve Naroffa0876e82008-12-02 17:36:43 +0000768void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
769 ObjCImplementationDecl *IMD,
770 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000771 static bool objcGetPropertyDefined = false;
772 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000773 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000774 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000775 const char *startBuf = SM->getCharacterData(startLoc);
776 assert((*startBuf == '@') && "bogus @synthesize location");
777 const char *semiBuf = strchr(startBuf, ';');
778 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000779 SourceLocation onePastSemiLoc =
780 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000781
782 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
783 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Steve Naroffeb0646c2008-12-02 15:48:25 +0000785 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000786 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000787 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000789 if (!OID)
790 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000791 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000792 if (!PD->getGetterMethodDecl()->isDefined()) {
793 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
794 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
795 ObjCPropertyDecl::OBJC_PR_copy));
796 std::string Getr;
797 if (GenGetProperty && !objcGetPropertyDefined) {
798 objcGetPropertyDefined = true;
799 // FIXME. Is this attribute correct in all cases?
800 Getr = "\nextern \"C\" __declspec(dllimport) "
801 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000802 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000803 RewriteObjCMethodDecl(OID->getContainingInterface(),
804 PD->getGetterMethodDecl(), Getr);
805 Getr += "{ ";
806 // Synthesize an explicit cast to gain access to the ivar.
807 // See objc-act.c:objc_synthesize_new_getter() for details.
808 if (GenGetProperty) {
809 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
810 Getr += "typedef ";
811 const FunctionType *FPRetType = 0;
812 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
813 FPRetType);
814 Getr += " _TYPE";
815 if (FPRetType) {
816 Getr += ")"; // close the precedence "scope" for "*".
817
818 // Now, emit the argument types (if any).
819 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
820 Getr += "(";
821 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
822 if (i) Getr += ", ";
823 std::string ParamStr = FT->getArgType(i).getAsString(
824 Context->PrintingPolicy);
825 Getr += ParamStr;
826 }
827 if (FT->isVariadic()) {
828 if (FT->getNumArgs()) Getr += ", ";
829 Getr += "...";
830 }
831 Getr += ")";
832 } else
833 Getr += "()";
834 }
835 Getr += ";\n";
836 Getr += "return (_TYPE)";
837 Getr += "objc_getProperty(self, _cmd, ";
838 SynthesizeIvarOffsetComputation(OID, Getr);
839 Getr += ", 1)";
840 }
841 else
842 Getr += "return " + getIvarAccessString(OID);
843 Getr += "; }";
844 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000845 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000846
847 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000848 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Steve Naroffeb0646c2008-12-02 15:48:25 +0000850 // Generate the 'setter' function.
851 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000852 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
853 ObjCPropertyDecl::OBJC_PR_copy);
854 if (GenSetProperty && !objcSetPropertyDefined) {
855 objcSetPropertyDefined = true;
856 // FIXME. Is this attribute correct in all cases?
857 Setr = "\nextern \"C\" __declspec(dllimport) "
858 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
859 }
860
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000861 RewriteObjCMethodDecl(OID->getContainingInterface(),
862 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000863 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000864 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000865 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000866 if (GenSetProperty) {
867 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000868 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000869 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000870 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000871 Setr += ", ";
872 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
873 Setr += "0, ";
874 else
875 Setr += "1, ";
876 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
877 Setr += "1)";
878 else
879 Setr += "0)";
880 }
881 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000882 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000883 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000884 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000885 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000886 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000887}
Chris Lattner8a12c272007-10-11 18:38:32 +0000888
Steve Naroffb29b4272008-04-14 22:03:09 +0000889void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000890 // Get the start location and compute the semi location.
891 SourceLocation startLoc = ClassDecl->getLocation();
892 const char *startBuf = SM->getCharacterData(startLoc);
893 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Chris Lattnerf04da132007-10-24 17:06:59 +0000895 // Translate to typedef's that forward reference structs with the same name
896 // as the class. As a convenience, we include the original declaration
897 // as a comment.
898 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000899 typedefString += "// @class ";
900 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
901 I != E; ++I) {
902 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
903 typedefString += ForwardDecl->getNameAsString();
904 if (I+1 != E)
905 typedefString += ", ";
906 else
907 typedefString += ";\n";
908 }
909
Chris Lattner67956052009-02-20 18:04:31 +0000910 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
911 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000912 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000913 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000914 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000915 typedefString += "\n";
916 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000917 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000918 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000919 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000920 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000921 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000922 }
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Steve Naroff934f2762007-10-24 22:48:43 +0000924 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000925 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000926}
927
Steve Naroffb29b4272008-04-14 22:03:09 +0000928void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000929 // When method is a synthesized one, such as a getter/setter there is
930 // nothing to rewrite.
931 if (Method->isSynthesized())
932 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000933 SourceLocation LocStart = Method->getLocStart();
934 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Chandler Carruth64211622011-07-25 21:09:52 +0000936 if (SM->getExpansionLineNumber(LocEnd) >
937 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000938 InsertText(LocStart, "#if 0\n");
939 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000940 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000941 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000942 }
943}
944
Mike Stump1eb44332009-09-09 15:08:12 +0000945void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000946 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Benjamin Kramerd999b372010-02-14 14:14:16 +0000948 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000949 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000950}
951
Steve Naroffb29b4272008-04-14 22:03:09 +0000952void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000953 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Steve Naroff423cb562007-10-30 13:30:57 +0000955 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000956 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000958 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
959 E = CatDecl->prop_end(); I != E; ++I)
960 RewriteProperty(*I);
961
Mike Stump1eb44332009-09-09 15:08:12 +0000962 for (ObjCCategoryDecl::instmeth_iterator
963 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000964 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000965 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000966 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000967 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000968 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000969 RewriteMethodDeclaration(*I);
970
Steve Naroff423cb562007-10-30 13:30:57 +0000971 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000972 ReplaceText(CatDecl->getAtEndRange().getBegin(),
973 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000974}
975
Steve Naroffb29b4272008-04-14 22:03:09 +0000976void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000977 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Steve Naroff752d6ef2007-10-30 16:42:30 +0000979 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000980 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000981
982 for (ObjCProtocolDecl::instmeth_iterator
983 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000984 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000985 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000986 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000987 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000988 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000989 RewriteMethodDeclaration(*I);
990
Fariborz Jahanian07acdf42010-09-24 18:36:58 +0000991 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
992 E = PDecl->prop_end(); I != E; ++I)
993 RewriteProperty(*I);
994
Steve Naroff752d6ef2007-10-30 16:42:30 +0000995 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000996 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000997 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000998
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000999 // Must comment out @optional/@required
1000 const char *startBuf = SM->getCharacterData(LocStart);
1001 const char *endBuf = SM->getCharacterData(LocEnd);
1002 for (const char *p = startBuf; p < endBuf; p++) {
1003 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001004 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001005 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001007 }
1008 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001009 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001010 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001012 }
1013 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001014}
1015
Steve Naroffb29b4272008-04-14 22:03:09 +00001016void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001017 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001018 if (LocStart.isInvalid())
1019 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001020 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001021 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001022}
1023
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001024void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1025 const FunctionType *&FPRetType) {
1026 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001027 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001028 else if (T->isFunctionPointerType() ||
1029 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001030 // needs special handling, since pointer-to-functions have special
1031 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001032 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001033 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001034 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001035 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001036 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001037 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001038 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001039 ResultStr += FPRetType->getResultType().getAsString(
1040 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001041 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001042 }
1043 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001044 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001045}
1046
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001047void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1048 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001049 std::string &ResultStr) {
1050 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1051 const FunctionType *FPRetType = 0;
1052 ResultStr += "\nstatic ";
1053 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001054 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001056 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001057 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001059 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001060 NameStr += "_I_";
1061 else
1062 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001064 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001065 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001066
1067 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001068 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001069 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001070 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001071 }
Mike Stump1eb44332009-09-09 15:08:12 +00001072 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001073 {
1074 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001075 int len = selString.size();
1076 for (int i = 0; i < len; i++)
1077 if (selString[i] == ':')
1078 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001079 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001080 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001081 // Remember this name for metadata emission
1082 MethodInternalNames[OMD] = NameStr;
1083 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001085 // Rewrite arguments
1086 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001088 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001089 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001090 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001091 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001092 if (!LangOpts.Microsoft) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001093 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001094 ResultStr += "struct ";
1095 }
1096 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001097 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001098 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001099 }
1100 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001101 ResultStr += Context->getObjCClassType().getAsString(
1102 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001104 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001105 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001106 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001108 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001109 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1110 E = OMD->param_end(); PI != E; ++PI) {
1111 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001112 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001113 if (PDecl->getType()->isObjCQualifiedIdType()) {
1114 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001115 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001116 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001117 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001118 QualType QT = PDecl->getType();
1119 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1120 if (convertBlockPointerToFunctionPointer(QT))
1121 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1122 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001123 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001124 ResultStr += Name;
1125 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001126 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001127 if (OMD->isVariadic())
1128 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001129 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Steve Naroff76e429d2008-07-16 14:40:40 +00001131 if (FPRetType) {
1132 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Steve Naroff76e429d2008-07-16 14:40:40 +00001134 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001135 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001136 ResultStr += "(";
1137 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1138 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001139 std::string ParamStr = FT->getArgType(i).getAsString(
1140 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001141 ResultStr += ParamStr;
1142 }
1143 if (FT->isVariadic()) {
1144 if (FT->getNumArgs()) ResultStr += ", ";
1145 ResultStr += "...";
1146 }
1147 ResultStr += ")";
1148 } else {
1149 ResultStr += "()";
1150 }
1151 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001152}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001153void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001154 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1155 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001157 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001159 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001160 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1161 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001162 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001163 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001164 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001165 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001166 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001167 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001168
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001169 const char *startBuf = SM->getCharacterData(LocStart);
1170 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001171 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001172 }
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001174 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001175 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1176 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001177 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001178 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001179 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001180 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001181 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001182 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001184 const char *startBuf = SM->getCharacterData(LocStart);
1185 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001186 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001187 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001188 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001189 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001190 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001191 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001192 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001193 }
1194
Benjamin Kramerd999b372010-02-14 14:14:16 +00001195 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001196}
1197
Steve Naroffb29b4272008-04-14 22:03:09 +00001198void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001199 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001200 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001201 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001202 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001203 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001204 ResultStr += "\n";
1205 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001206 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001207 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001208 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001209 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001210 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001211 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001212 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001213 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001214 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001215
1216 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001217 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001218 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001219 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001220 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001221 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001222 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001223 for (ObjCInterfaceDecl::classmeth_iterator
1224 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001225 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001226 RewriteMethodDeclaration(*I);
1227
Steve Naroff2feac5e2007-10-30 03:43:13 +00001228 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001229 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1230 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001231}
1232
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001233Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001234 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001235 ObjCMethodDecl *OMD = 0;
1236 QualType Ty;
1237 Selector Sel;
Duncan Sands54bd4572010-10-20 08:21:16 +00001238 Stmt *Receiver = 0;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001239 bool Super = false;
1240 QualType SuperTy;
1241 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001242 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001243 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001244 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCall12f78a62010-12-02 01:19:52 +00001245 if (ObjCPropertyRefExpr *PropRefExpr =
1246 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001247 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001248 if (PropRefExpr->isExplicitProperty()) {
1249 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1250 OMD = PDecl->getSetterMethodDecl();
1251 Ty = PDecl->getType();
1252 Sel = PDecl->getSetterName();
1253 } else {
1254 OMD = PropRefExpr->getImplicitPropertySetter();
1255 Sel = OMD->getSelector();
1256 Ty = PropRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001257 }
John McCall12f78a62010-12-02 01:19:52 +00001258 Super = PropRefExpr->isSuperReceiver();
1259 if (!Super) {
1260 Receiver = PropRefExpr->getBase();
1261 } else {
1262 SuperTy = PropRefExpr->getSuperReceiverType();
1263 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001264 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001265 }
1266
1267 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Chris Lattner5f9e2722011-07-23 10:55:15 +00001268 SmallVector<Expr *, 1> ExprVec;
Steve Naroffc77a6362008-12-04 16:24:46 +00001269 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001271 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001272 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001273 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001274 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001275 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001276 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001277 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001278 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001279 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001280 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001281 &ExprVec[0], 1,
1282 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001283 else {
1284 // FIXME. Refactor this into common code with that in
1285 // RewritePropertyOrImplicitGetter
1286 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1287 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1288 if (PropGetters[Exp])
1289 // This allows us to handle chain/nested property/implicit getters.
1290 Receiver = PropGetters[Exp];
1291
Douglas Gregor04badcf2010-04-21 00:45:42 +00001292 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001293 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001294 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001295 /*FIXME: */SourceLocation(),
1296 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001297 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001298 &ExprVec[0], 1,
1299 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001300 }
Steve Naroffc77a6362008-12-04 16:24:46 +00001301 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001302
Steve Naroffc77a6362008-12-04 16:24:46 +00001303 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001304 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001305 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001306 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1307 // to things that stay around.
1308 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001309 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001310}
1311
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001312Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1313 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001314 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001315 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001316 ObjCMethodDecl *OMD = 0;
1317 QualType Ty;
1318 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001319 bool Super = false;
1320 QualType SuperTy;
1321 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001322 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001323 if (ObjCPropertyRefExpr *PropRefExpr =
1324 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001325 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001326 if (PropRefExpr->isExplicitProperty()) {
1327 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1328 OMD = PDecl->getGetterMethodDecl();
1329 Ty = PDecl->getType();
1330 Sel = PDecl->getGetterName();
1331 } else {
1332 OMD = PropRefExpr->getImplicitPropertyGetter();
1333 Sel = OMD->getSelector();
1334 Ty = PropRefExpr->getType();
1335 }
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001336 Super = PropRefExpr->isSuperReceiver();
1337 if (!Super)
1338 Receiver = PropRefExpr->getBase();
1339 else {
John McCall12f78a62010-12-02 01:19:52 +00001340 SuperTy = PropRefExpr->getSuperReceiverType();
1341 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001342 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001343 }
1344
1345 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1346
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001347 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001348 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001349 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001350 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001351 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001352 PropOrGetterRefExpr->getLocStart(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001353 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001354 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001355 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001356 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001357 0, 0,
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001358 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001359 else {
1360 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1361 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1362 if (PropGetters[Exp])
1363 // This allows us to handle chain/nested property/implicit getters.
1364 Receiver = PropGetters[Exp];
Douglas Gregor04badcf2010-04-21 00:45:42 +00001365 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001366 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001367 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001368 PropOrGetterRefExpr->getLocStart(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001369 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001370 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001371 0, 0,
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001372 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001373 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001374
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001375 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr, MsgExpr->getLocStart(),
1376 MsgExpr->getLocEnd());
Steve Naroff8599e7a2008-12-08 16:43:47 +00001377
1378 if (!PropParentMap)
1379 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001380 bool NestedPropertyRef = false;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001381 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001382 ImplicitCastExpr*ICE=0;
1383 if (Parent)
1384 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1385 assert((ICE->getCastKind() == CK_GetObjCProperty)
1386 && "RewritePropertyOrImplicitGetter");
1387 Parent = PropParentMap->getParent(Parent);
1388 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1389 }
1390 if (NestedPropertyRef) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001391 // We stash away the ReplacingStmt since actually doing the
1392 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001393 PropGetters[ICE] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001394 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1395 // to things that stay around.
1396 Context->Deallocate(MsgExpr);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001397 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001398 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001399 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001400 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001401 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1402 // to things that stay around.
1403 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001404 return ReplacingStmt;
1405 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001406}
1407
Mike Stump1eb44332009-09-09 15:08:12 +00001408Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001409 SourceLocation OrigStart,
1410 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001411 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001412 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001413 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001414 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001415 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001416 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001417 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001418 // lookup which class implements the instance variable.
1419 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001420 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001421 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001422 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Steve Narofff0757612008-05-08 17:52:16 +00001424 // Synthesize an explicit cast to gain access to the ivar.
1425 std::string RecName = clsDeclared->getIdentifier()->getName();
1426 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001427 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001428 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001429 SourceLocation(), SourceLocation(),
1430 II);
Steve Narofff0757612008-05-08 17:52:16 +00001431 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1432 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001433 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001434 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001435 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001436 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001437 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCallf89e55a2010-11-18 06:31:45 +00001438 IV->getBase()->getLocEnd(),
1439 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001440 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001441 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001442 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001443 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001444 IV->getLocation(),
1445 D->getType(),
1446 VK_LValue, OK_Ordinary);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001447 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001448 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001449 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001450 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001451 // Cannot delete IV->getBase(), since PE points to it.
1452 // Replace the old base with the cast. This is important when doing
1453 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001454 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001455 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001456 }
Steve Naroff84472a82008-04-18 21:55:08 +00001457 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001458 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Steve Naroff9f525972008-05-06 23:20:07 +00001460 // Explicit ivar refs need to have a cast inserted.
1461 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001462 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001463 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001464 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001465 // lookup which class implements the instance variable.
1466 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001467 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001468 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001469 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Steve Naroff9f525972008-05-06 23:20:07 +00001471 // Synthesize an explicit cast to gain access to the ivar.
1472 std::string RecName = clsDeclared->getIdentifier()->getName();
1473 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001474 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001475 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001476 SourceLocation(), SourceLocation(),
1477 II);
Steve Naroff9f525972008-05-06 23:20:07 +00001478 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1479 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001480 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001481 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001482 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001483 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001484 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001485 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001486 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001487 // Cannot delete IV->getBase(), since PE points to it.
1488 // Replace the old base with the cast. This is important when doing
1489 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001490 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001491 return IV;
1492 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001493 }
Steve Naroff84472a82008-04-18 21:55:08 +00001494 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001495}
1496
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001497Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
John McCall7502c1d2011-02-13 04:07:26 +00001498 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001499 if (*CI) {
1500 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1501 if (newStmt)
1502 *CI = newStmt;
1503 }
1504 }
1505 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1506 SourceRange OrigStmtRange = S->getSourceRange();
1507 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1508 replaced);
1509 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001510 }
1511 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1512 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1513 return newStmt;
1514 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001515 return S;
1516}
1517
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001518/// SynthCountByEnumWithState - To print:
1519/// ((unsigned int (*)
1520/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001521/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001522/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001523/// "countByEnumeratingWithState:objects:count:"),
1524/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001525/// (id *)items, (unsigned int)16)
1526///
Steve Naroffb29b4272008-04-14 22:03:09 +00001527void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001528 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1529 "id *, unsigned int))(void *)objc_msgSend)";
1530 buf += "\n\t\t";
1531 buf += "((id)l_collection,\n\t\t";
1532 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1533 buf += "\n\t\t";
1534 buf += "&enumState, "
1535 "(id *)items, (unsigned int)16)";
1536}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001537
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001538/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1539/// statement to exit to its outer synthesized loop.
1540///
Steve Naroffb29b4272008-04-14 22:03:09 +00001541Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001542 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1543 return S;
1544 // replace break with goto __break_label
1545 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001547 SourceLocation startLoc = S->getLocStart();
1548 buf = "goto __break_label_";
1549 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001550 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001551
1552 return 0;
1553}
1554
1555/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1556/// statement to continue with its inner synthesized loop.
1557///
Steve Naroffb29b4272008-04-14 22:03:09 +00001558Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001559 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1560 return S;
1561 // replace continue with goto __continue_label
1562 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001564 SourceLocation startLoc = S->getLocStart();
1565 buf = "goto __continue_label_";
1566 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001567 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001569 return 0;
1570}
1571
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001572/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001573/// It rewrites:
1574/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001576/// Into:
1577/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001578/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001579/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001580/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001581/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001582/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001583/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001584/// if (limit) {
1585/// unsigned long startMutations = *enumState.mutationsPtr;
1586/// do {
1587/// unsigned long counter = 0;
1588/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001589/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001590/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001591/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001592/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001593/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001594/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001595/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001596/// objects:items count:16]);
1597/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001598/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001599/// }
1600/// else
1601/// elem = nil;
1602/// }
1603///
Steve Naroffb29b4272008-04-14 22:03:09 +00001604Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001605 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001606 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001607 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001608 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001609 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001610 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001612 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001613 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001614 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001615 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001616 std::string buf;
1617 buf = "\n{\n\t";
1618 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1619 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001620 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001621 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001622 if (ElementType->isObjCQualifiedIdType() ||
1623 ElementType->isObjCQualifiedInterfaceType())
1624 // Simply use 'id' for all qualified types.
1625 elementTypeAsString = "id";
1626 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001627 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001628 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001629 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001630 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001631 buf += elementName;
1632 buf += ";\n\t";
1633 }
Chris Lattner06767512008-04-08 05:52:18 +00001634 else {
1635 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001636 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001637 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1638 if (VD->getType()->isObjCQualifiedIdType() ||
1639 VD->getType()->isObjCQualifiedInterfaceType())
1640 // Simply use 'id' for all qualified types.
1641 elementTypeAsString = "id";
1642 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001643 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001644 }
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001646 // struct __objcFastEnumerationState enumState = { 0 };
1647 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1648 // id items[16];
1649 buf += "id items[16];\n\t";
1650 // id l_collection = (id)
1651 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001652 // Find start location of 'collection' the hard way!
1653 const char *startCollectionBuf = startBuf;
1654 startCollectionBuf += 3; // skip 'for'
1655 startCollectionBuf = strchr(startCollectionBuf, '(');
1656 startCollectionBuf++; // skip '('
1657 // find 'in' and skip it.
1658 while (*startCollectionBuf != ' ' ||
1659 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1660 (*(startCollectionBuf+3) != ' ' &&
1661 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1662 startCollectionBuf++;
1663 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001664
1665 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001666 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001667 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001668 SourceLocation rightParenLoc = S->getRParenLoc();
1669 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1670 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001671 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001673 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1674 // objects:items count:16];
1675 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001676 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001677 // ((unsigned int (*)
1678 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001679 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001680 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001681 // "countByEnumeratingWithState:objects:count:"),
1682 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001683 // (id *)items, (unsigned int)16);
1684 buf += "unsigned long limit =\n\t\t";
1685 SynthCountByEnumWithState(buf);
1686 buf += ";\n\t";
1687 /// if (limit) {
1688 /// unsigned long startMutations = *enumState.mutationsPtr;
1689 /// do {
1690 /// unsigned long counter = 0;
1691 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001692 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001693 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001694 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001695 buf += "if (limit) {\n\t";
1696 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1697 buf += "do {\n\t\t";
1698 buf += "unsigned long counter = 0;\n\t\t";
1699 buf += "do {\n\t\t\t";
1700 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1701 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1702 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001703 buf += " = (";
1704 buf += elementTypeAsString;
1705 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001706 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001707 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001709 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001710 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001711 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001712 /// objects:items count:16]);
1713 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001714 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001715 /// }
1716 /// else
1717 /// elem = nil;
1718 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001719 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001720 buf = ";\n\t";
1721 buf += "__continue_label_";
1722 buf += utostr(ObjCBcLabelNo.back());
1723 buf += ": ;";
1724 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001725 buf += "} while (counter < limit);\n\t";
1726 buf += "} while (limit = ";
1727 SynthCountByEnumWithState(buf);
1728 buf += ");\n\t";
1729 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001730 buf += " = ((";
1731 buf += elementTypeAsString;
1732 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001733 buf += "__break_label_";
1734 buf += utostr(ObjCBcLabelNo.back());
1735 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001736 buf += "}\n\t";
1737 buf += "else\n\t\t";
1738 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001739 buf += " = ((";
1740 buf += elementTypeAsString;
1741 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001742 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001744 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001745 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001746 if (isa<CompoundStmt>(S->getBody())) {
1747 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001748 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001749 } else {
1750 /* Need to treat single statements specially. For example:
1751 *
1752 * for (A *a in b) if (stuff()) break;
1753 * for (A *a in b) xxxyy;
1754 *
1755 * The following code simply scans ahead to the semi to find the actual end.
1756 */
1757 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1758 const char *semiBuf = strchr(stmtBuf, ';');
1759 assert(semiBuf && "Can't find ';'");
1760 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001761 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001762 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001763 Stmts.pop_back();
1764 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001765 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001766}
1767
Mike Stump1eb44332009-09-09 15:08:12 +00001768/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001769/// This routine rewrites @synchronized(expr) stmt;
1770/// into:
1771/// objc_sync_enter(expr);
1772/// @try stmt @finally { objc_sync_exit(expr); }
1773///
Steve Naroffb29b4272008-04-14 22:03:09 +00001774Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001775 // Get the start location and compute the semi location.
1776 SourceLocation startLoc = S->getLocStart();
1777 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001779 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001780
1781 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001782 buf = "objc_sync_enter((id)";
1783 const char *lparenBuf = startBuf;
1784 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001785 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001786 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1787 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001788 // been rewritten! (which implies the SourceLocation's are invalid).
1789 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001790 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001791 while (*endBuf != ')') endBuf--;
1792 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001793 buf = ");\n";
1794 // declare a new scope with two variables, _stack and _rethrow.
1795 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1796 buf += "int buf[18/*32-bit i386*/];\n";
1797 buf += "char *pointers[4];} _stack;\n";
1798 buf += "id volatile _rethrow = 0;\n";
1799 buf += "objc_exception_try_enter(&_stack);\n";
1800 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001801 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001802 startLoc = S->getSynchBody()->getLocEnd();
1803 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Steve Naroffc7089f12008-08-19 13:04:19 +00001805 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001806 SourceLocation lastCurlyLoc = startLoc;
1807 buf = "}\nelse {\n";
1808 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001809 buf += "}\n";
1810 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001811 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001812
1813 std::string syncBuf;
1814 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001815 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00001816 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001817 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001818 std::string syncExprBufS;
1819 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001820 syncExpr->printPretty(syncExprBuf, *Context, 0,
1821 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001822 syncBuf += syncExprBuf.str();
1823 syncBuf += ");";
1824
1825 buf += syncBuf;
1826 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001827 buf += "}\n";
1828 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Benjamin Kramerd999b372010-02-14 14:14:16 +00001830 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001831
1832 bool hasReturns = false;
1833 HasReturnStmts(S->getSynchBody(), hasReturns);
1834 if (hasReturns)
1835 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1836
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001837 return 0;
1838}
1839
Steve Naroffb85e77a2009-12-05 21:43:12 +00001840void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1841{
Steve Naroff8c565152008-12-05 17:03:39 +00001842 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001843 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001844 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001845 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001846
Steve Naroffb85e77a2009-12-05 21:43:12 +00001847 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001848 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001849 TryFinallyContainsReturnDiag);
1850 }
1851 return;
1852}
1853
Steve Naroffb85e77a2009-12-05 21:43:12 +00001854void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1855{
1856 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001857 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001858 if (*CI)
1859 HasReturnStmts(*CI, hasReturns);
1860
1861 if (isa<ReturnStmt>(S))
1862 hasReturns = true;
1863 return;
1864}
1865
1866void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1867 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001868 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001869 if (*CI) {
1870 RewriteTryReturnStmts(*CI);
1871 }
1872 if (isa<ReturnStmt>(S)) {
1873 SourceLocation startLoc = S->getLocStart();
1874 const char *startBuf = SM->getCharacterData(startLoc);
1875
1876 const char *semiBuf = strchr(startBuf, ';');
1877 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1878 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1879
1880 std::string buf;
1881 buf = "{ objc_exception_try_exit(&_stack); return";
1882
Benjamin Kramerd999b372010-02-14 14:14:16 +00001883 ReplaceText(startLoc, 6, buf);
1884 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001885 }
1886 return;
1887}
1888
1889void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1890 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001891 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001892 if (*CI) {
1893 RewriteSyncReturnStmts(*CI, syncExitBuf);
1894 }
1895 if (isa<ReturnStmt>(S)) {
1896 SourceLocation startLoc = S->getLocStart();
1897 const char *startBuf = SM->getCharacterData(startLoc);
1898
1899 const char *semiBuf = strchr(startBuf, ';');
1900 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1901 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1902
1903 std::string buf;
1904 buf = "{ objc_exception_try_exit(&_stack);";
1905 buf += syncExitBuf;
1906 buf += " return";
1907
Benjamin Kramerd999b372010-02-14 14:14:16 +00001908 ReplaceText(startLoc, 6, buf);
1909 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001910 }
1911 return;
1912}
1913
Steve Naroffb29b4272008-04-14 22:03:09 +00001914Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001915 // Get the start location and compute the semi location.
1916 SourceLocation startLoc = S->getLocStart();
1917 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Steve Naroff75730982007-11-07 04:08:17 +00001919 assert((*startBuf == '@') && "bogus @try location");
1920
1921 std::string buf;
1922 // declare a new scope with two variables, _stack and _rethrow.
1923 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1924 buf += "int buf[18/*32-bit i386*/];\n";
1925 buf += "char *pointers[4];} _stack;\n";
1926 buf += "id volatile _rethrow = 0;\n";
1927 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001928 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001929
Benjamin Kramerd999b372010-02-14 14:14:16 +00001930 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001931
Steve Naroff75730982007-11-07 04:08:17 +00001932 startLoc = S->getTryBody()->getLocEnd();
1933 startBuf = SM->getCharacterData(startLoc);
1934
1935 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Steve Naroff75730982007-11-07 04:08:17 +00001937 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001938 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001939 startLoc = startLoc.getFileLocWithOffset(1);
1940 buf = " /* @catch begin */ else {\n";
1941 buf += " id _caught = objc_exception_extract(&_stack);\n";
1942 buf += " objc_exception_try_enter (&_stack);\n";
1943 buf += " if (_setjmp(_stack.buf))\n";
1944 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1945 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Benjamin Kramerd999b372010-02-14 14:14:16 +00001947 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001948 } else { /* no catch list */
1949 buf = "}\nelse {\n";
1950 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1951 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001952 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001953 }
Steve Naroff75730982007-11-07 04:08:17 +00001954 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001955 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1956 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001957 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001958
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001959 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001960 buf = "if ("; // we are generating code for the first catch clause
1961 else
1962 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001963 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001964 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001965
Steve Naroff75730982007-11-07 04:08:17 +00001966 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Steve Naroff75730982007-11-07 04:08:17 +00001968 const char *lParenLoc = strchr(startBuf, '(');
1969
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001970 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001971 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001972 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001973 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1974 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001975 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001976 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001977 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Steve Naroffe12e6922008-02-01 20:02:07 +00001979 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001980 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001981 } else if (catchDecl) {
1982 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001983 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001984 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001985 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001986 } else if (const ObjCObjectPointerType *Ptr =
1987 t->getAs<ObjCObjectPointerType>()) {
1988 // Should be a pointer to a class.
1989 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1990 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001991 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001992 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001993 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001994 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001995 }
1996 }
1997 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001998 lastCatchBody = Catch->getCatchBody();
1999 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00002000 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2001 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2002 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2003 assert((*rParenBuf == ')') && "bogus @catch paren location");
2004 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Mike Stump1eb44332009-09-09 15:08:12 +00002006 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002007 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002008 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002009 } else {
Steve Naroff75730982007-11-07 04:08:17 +00002010 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002011 }
Steve Naroff75730982007-11-07 04:08:17 +00002012 }
2013 // Complete the catch list...
2014 if (lastCatchBody) {
2015 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002016 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2017 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Steve Naroff378f47a2008-09-11 15:29:03 +00002019 // Insert the last (implicit) else clause *before* the right curly brace.
2020 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2021 buf = "} /* last catch end */\n";
2022 buf += "else {\n";
2023 buf += " _rethrow = _caught;\n";
2024 buf += " objc_exception_try_exit(&_stack);\n";
2025 buf += "} } /* @catch end */\n";
2026 if (!S->getFinallyStmt())
2027 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002028 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Steve Naroff75730982007-11-07 04:08:17 +00002030 // Set lastCurlyLoc
2031 lastCurlyLoc = lastCatchBody->getLocEnd();
2032 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002033 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002034 startLoc = finalStmt->getLocStart();
2035 startBuf = SM->getCharacterData(startLoc);
2036 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Benjamin Kramerd999b372010-02-14 14:14:16 +00002038 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002039
Steve Naroff75730982007-11-07 04:08:17 +00002040 Stmt *body = finalStmt->getFinallyBody();
2041 SourceLocation startLoc = body->getLocStart();
2042 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002043 assert(*SM->getCharacterData(startLoc) == '{' &&
2044 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002045 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002046 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Steve Naroff75730982007-11-07 04:08:17 +00002048 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002049 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00002050 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002051 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Steve Naroff75730982007-11-07 04:08:17 +00002053 // Set lastCurlyLoc
2054 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Steve Naroff8c565152008-12-05 17:03:39 +00002056 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002057 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002058 } else { /* no finally clause - make sure we synthesize an implicit one */
2059 buf = "{ /* implicit finally clause */\n";
2060 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2061 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2062 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002063 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002064
2065 // Now check for any return/continue/go statements within the @try.
2066 // The implicit finally clause won't called if the @try contains any
2067 // jump statements.
2068 bool hasReturns = false;
2069 HasReturnStmts(S->getTryBody(), hasReturns);
2070 if (hasReturns)
2071 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002072 }
2073 // Now emit the final closing curly brace...
2074 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002075 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002076 return 0;
2077}
2078
Mike Stump1eb44332009-09-09 15:08:12 +00002079// This can't be done with ReplaceStmt(S, ThrowExpr), since
2080// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002081// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002082Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002083 // Get the start location and compute the semi location.
2084 SourceLocation startLoc = S->getLocStart();
2085 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Steve Naroff2bd03922007-11-07 15:32:26 +00002087 assert((*startBuf == '@') && "bogus @throw location");
2088
2089 std::string buf;
2090 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002091 if (S->getThrowExpr())
2092 buf = "objc_exception_throw(";
2093 else // add an implicit argument
2094 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002096 // handle "@ throw" correctly.
2097 const char *wBuf = strchr(startBuf, 'w');
2098 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002099 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Steve Naroff2bd03922007-11-07 15:32:26 +00002101 const char *semiBuf = strchr(startBuf, ';');
2102 assert((*semiBuf == ';') && "@throw: can't find ';'");
2103 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002104 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002105 return 0;
2106}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002107
Steve Naroffb29b4272008-04-14 22:03:09 +00002108Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002109 // Create a new string expression.
2110 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002111 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002112 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002113 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002114 StringLiteral::Ascii, false,
2115 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002116 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Chris Lattner07506182007-11-30 22:53:43 +00002118 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002119 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002120 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002121}
2122
Steve Naroffb29b4272008-04-14 22:03:09 +00002123Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002124 if (!SelGetUidFunctionDecl)
2125 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002126 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2127 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002128 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002129 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002130 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002131 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002132 StringLiteral::Ascii, false,
2133 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002134 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2135 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002136 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002137 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002138 return SelExp;
2139}
2140
Steve Naroffb29b4272008-04-14 22:03:09 +00002141CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002142 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2143 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002144 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002145 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Steve Naroffebf2b562007-10-23 23:50:29 +00002147 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002148 DeclRefExpr *DRE =
2149 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Steve Naroffebf2b562007-10-23 23:50:29 +00002151 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002152 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002153 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002154 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002155 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002156
John McCall183700f2009-09-21 23:43:11 +00002157 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002159 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002160 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002161 FT->getCallResultType(*Context),
2162 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002163 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002164}
2165
Steve Naroffd5255f52007-11-01 13:24:47 +00002166static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2167 const char *&startRef, const char *&endRef) {
2168 while (startBuf < endBuf) {
2169 if (*startBuf == '<')
2170 startRef = startBuf; // mark the start.
2171 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002172 if (startRef && *startRef == '<') {
2173 endRef = startBuf; // mark the end.
2174 return true;
2175 }
2176 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002177 }
2178 startBuf++;
2179 }
2180 return false;
2181}
2182
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002183static void scanToNextArgument(const char *&argRef) {
2184 int angle = 0;
2185 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2186 if (*argRef == '<')
2187 angle++;
2188 else if (*argRef == '>')
2189 angle--;
2190 argRef++;
2191 }
2192 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2193}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002194
Steve Naroffb29b4272008-04-14 22:03:09 +00002195bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002196 if (T->isObjCQualifiedIdType())
2197 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002198 if (const PointerType *PT = T->getAs<PointerType>()) {
2199 if (PT->getPointeeType()->isObjCQualifiedIdType())
2200 return true;
2201 }
2202 if (T->isObjCObjectPointerType()) {
2203 T = T->getPointeeType();
2204 return T->isObjCQualifiedInterfaceType();
2205 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002206 if (T->isArrayType()) {
2207 QualType ElemTy = Context->getBaseElementType(T);
2208 return needToScanForQualifiers(ElemTy);
2209 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002210 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002211}
2212
Steve Naroff4f95b752008-07-29 18:15:38 +00002213void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2214 QualType Type = E->getType();
2215 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002216 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Steve Naroffcda658e2008-11-19 21:15:47 +00002218 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2219 Loc = ECE->getLParenLoc();
2220 EndLoc = ECE->getRParenLoc();
2221 } else {
2222 Loc = E->getLocStart();
2223 EndLoc = E->getLocEnd();
2224 }
2225 // This will defend against trying to rewrite synthesized expressions.
2226 if (Loc.isInvalid() || EndLoc.isInvalid())
2227 return;
2228
Steve Naroff4f95b752008-07-29 18:15:38 +00002229 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002230 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002231 const char *startRef = 0, *endRef = 0;
2232 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2233 // Get the locations of the startRef, endRef.
2234 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2235 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2236 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002237 InsertText(LessLoc, "/*");
2238 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002239 }
2240 }
2241}
2242
Steve Naroffb29b4272008-04-14 22:03:09 +00002243void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002244 SourceLocation Loc;
2245 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002246 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002247 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2248 Loc = VD->getLocation();
2249 Type = VD->getType();
2250 }
2251 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2252 Loc = FD->getLocation();
2253 // Check for ObjC 'id' and class types that have been adorned with protocol
2254 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002255 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002256 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002257 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002258 if (!proto)
2259 return;
2260 Type = proto->getResultType();
2261 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002262 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2263 Loc = FD->getLocation();
2264 Type = FD->getType();
2265 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002266 else
2267 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002268
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002269 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002270 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002271
Steve Naroffd5255f52007-11-01 13:24:47 +00002272 const char *endBuf = SM->getCharacterData(Loc);
2273 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002274 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002275 startBuf--; // scan backward (from the decl location) for return type.
2276 const char *startRef = 0, *endRef = 0;
2277 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2278 // Get the locations of the startRef, endRef.
2279 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2280 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2281 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002282 InsertText(LessLoc, "/*");
2283 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002284 }
2285 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002286 if (!proto)
2287 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002288 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002289 const char *startBuf = SM->getCharacterData(Loc);
2290 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002291 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2292 if (needToScanForQualifiers(proto->getArgType(i))) {
2293 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Steve Naroffd5255f52007-11-01 13:24:47 +00002295 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002296 // scan forward (from the decl location) for argument types.
2297 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002298 const char *startRef = 0, *endRef = 0;
2299 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2300 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002301 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002302 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002303 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002304 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002305 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002306 InsertText(LessLoc, "/*");
2307 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002308 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002309 startBuf = ++endBuf;
2310 }
2311 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002312 // If the function name is derived from a macro expansion, then the
2313 // argument buffer will not follow the name. Need to speak with Chris.
2314 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002315 startBuf++; // scan forward (from the decl location) for argument types.
2316 startBuf++;
2317 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002318 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002319}
2320
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002321void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2322 QualType QT = ND->getType();
2323 const Type* TypePtr = QT->getAs<Type>();
2324 if (!isa<TypeOfExprType>(TypePtr))
2325 return;
2326 while (isa<TypeOfExprType>(TypePtr)) {
2327 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2328 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2329 TypePtr = QT->getAs<Type>();
2330 }
2331 // FIXME. This will not work for multiple declarators; as in:
2332 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002333 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002334 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2335 const char *startBuf = SM->getCharacterData(DeclLoc);
2336 if (ND->getInit()) {
2337 std::string Name(ND->getNameAsString());
2338 TypeAsString += " " + Name + " = ";
2339 Expr *E = ND->getInit();
2340 SourceLocation startLoc;
2341 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2342 startLoc = ECE->getLParenLoc();
2343 else
2344 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002345 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002346 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002347 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002348 }
2349 else {
2350 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002351 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002352 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002353 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002354 }
2355}
2356
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002357// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002358void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002359 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002360 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002361 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002362 QualType getFuncType =
2363 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002364 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002365 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002366 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002367 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002368 SC_Extern,
2369 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002370}
2371
Steve Naroffb29b4272008-04-14 22:03:09 +00002372void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002373 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002374 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002375 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002376 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002377 return;
2378 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002379 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002380}
2381
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002382void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2383 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002384 const char *argPtr = TypeString.c_str();
2385 if (!strchr(argPtr, '^')) {
2386 Str += TypeString;
2387 return;
2388 }
2389 while (*argPtr) {
2390 Str += (*argPtr == '^' ? '*' : *argPtr);
2391 argPtr++;
2392 }
2393}
2394
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002395// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002396void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2397 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002398 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002399 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002400 const char *argPtr = TypeString.c_str();
2401 int paren = 0;
2402 while (*argPtr) {
2403 switch (*argPtr) {
2404 case '(':
2405 Str += *argPtr;
2406 paren++;
2407 break;
2408 case ')':
2409 Str += *argPtr;
2410 paren--;
2411 break;
2412 case '^':
2413 Str += '*';
2414 if (paren == 1)
2415 Str += VD->getNameAsString();
2416 break;
2417 default:
2418 Str += *argPtr;
2419 break;
2420 }
2421 argPtr++;
2422 }
2423}
2424
2425
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002426void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2427 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2428 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2429 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2430 if (!proto)
2431 return;
2432 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002433 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002434 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002435 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002436 FdStr += "(";
2437 unsigned numArgs = proto->getNumArgs();
2438 for (unsigned i = 0; i < numArgs; i++) {
2439 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002440 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002441 if (i+1 < numArgs)
2442 FdStr += ", ";
2443 }
2444 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002445 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002446 CurFunctionDeclToDeclareForBlock = 0;
2447}
2448
Steve Naroffc0a123c2008-03-11 17:37:02 +00002449// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002450void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002451 if (SuperContructorFunctionDecl)
2452 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002453 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002454 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002455 QualType argT = Context->getObjCIdType();
2456 assert(!argT.isNull() && "Can't find 'id' type");
2457 ArgTys.push_back(argT);
2458 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002459 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2460 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002461 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002462 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002463 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002464 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002465 SC_Extern,
2466 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002467}
2468
Steve Naroff09b266e2007-10-30 23:14:51 +00002469// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002470void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002471 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002472 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002473 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002474 assert(!argT.isNull() && "Can't find 'id' type");
2475 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002476 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002477 assert(!argT.isNull() && "Can't find 'SEL' type");
2478 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002479 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2480 &ArgTys[0], ArgTys.size(),
2481 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002482 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002483 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002484 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002485 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002486 SC_Extern,
2487 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002488}
2489
Steve Naroff874e2322007-11-15 10:28:18 +00002490// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002491void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002492 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002493 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002494 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002495 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002496 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002497 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2498 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2499 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002500 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002501 assert(!argT.isNull() && "Can't find 'SEL' type");
2502 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002503 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2504 &ArgTys[0], ArgTys.size(),
2505 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002506 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002507 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002508 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002509 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002510 SC_Extern,
2511 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002512}
2513
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002514// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002515void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002516 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002517 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002518 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002519 assert(!argT.isNull() && "Can't find 'id' type");
2520 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002521 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002522 assert(!argT.isNull() && "Can't find 'SEL' type");
2523 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002524 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2525 &ArgTys[0], ArgTys.size(),
2526 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002527 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002528 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002529 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002530 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002531 SC_Extern,
2532 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002533}
2534
Mike Stump1eb44332009-09-09 15:08:12 +00002535// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002536// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002537void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002538 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002539 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002540 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002541 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002542 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002543 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002544 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2545 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2546 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002547 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002548 assert(!argT.isNull() && "Can't find 'SEL' type");
2549 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002550 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2551 &ArgTys[0], ArgTys.size(),
2552 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002553 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002554 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002555 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002556 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002557 SC_Extern,
2558 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002559}
2560
Steve Naroff1284db82008-05-08 22:02:18 +00002561// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002562void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002563 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002564 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002565 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002566 assert(!argT.isNull() && "Can't find 'id' type");
2567 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002568 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002569 assert(!argT.isNull() && "Can't find 'SEL' type");
2570 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002571 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2572 &ArgTys[0], ArgTys.size(),
2573 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002574 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002575 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002576 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002577 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002578 SC_Extern,
2579 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002580}
2581
Steve Naroff09b266e2007-10-30 23:14:51 +00002582// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002583void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002584 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002585 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002586 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002587 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2588 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002589 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002590 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002591 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002592 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002593 SC_Extern,
2594 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002595}
2596
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002597// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2598void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2599 IdentifierInfo *getSuperClassIdent =
2600 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002601 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002602 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002603 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2604 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002605 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002606 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002607 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002608 getSuperClassIdent,
2609 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002610 SC_Extern,
2611 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002612 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002613}
2614
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002615// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002616void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002617 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002618 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002619 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002620 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2621 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002622 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002623 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002624 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002625 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002626 SC_Extern,
2627 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002628}
2629
Steve Naroffb29b4272008-04-14 22:03:09 +00002630Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002631 QualType strType = getConstantStringStructType();
2632
2633 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002634
2635 std::string tmpName = InFileName;
2636 unsigned i;
2637 for (i=0; i < tmpName.length(); i++) {
2638 char c = tmpName.at(i);
2639 // replace any non alphanumeric characters with '_'.
2640 if (!isalpha(c) && (c < '0' || c > '9'))
2641 tmpName[i] = '_';
2642 }
2643 S += tmpName;
2644 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002645 S += utostr(NumObjCStringLiterals++);
2646
Steve Naroffba92b2e2008-03-27 22:29:16 +00002647 Preamble += "static __NSConstantStringImpl " + S;
2648 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2649 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002650 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002651 std::string prettyBufS;
2652 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002653 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2654 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002655 Preamble += prettyBuf.str();
2656 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002657 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002658
2659 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002660 SourceLocation(), &Context->Idents.get(S),
2661 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002662 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2663 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002664 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002665 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002666 VK_RValue, OK_Ordinary,
2667 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002668 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002669 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00002670 CK_BitCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002671 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002672 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002673 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002674}
2675
Steve Naroff874e2322007-11-15 10:28:18 +00002676// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002677QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002678 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002679 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002680 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002681 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002682 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002683
Steve Naroff874e2322007-11-15 10:28:18 +00002684 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002685 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002686 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002687 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002688
Steve Naroff874e2322007-11-15 10:28:18 +00002689 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002690 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002691 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002692 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002693 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002694 FieldTypes[i], 0,
2695 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002696 /*Mutable=*/false,
2697 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002698 }
Mike Stump1eb44332009-09-09 15:08:12 +00002699
Douglas Gregor838db382010-02-11 01:19:42 +00002700 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002701 }
2702 return Context->getTagDeclType(SuperStructDecl);
2703}
2704
Steve Naroffb29b4272008-04-14 22:03:09 +00002705QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002706 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002707 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002708 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002709 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002710 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002711
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002712 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002713 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002714 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002715 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002716 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002717 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002718 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002719 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002720
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002721 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002722 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002723 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2724 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002725 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002726 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002727 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002728 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002729 /*Mutable=*/true,
2730 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002731 }
2732
Douglas Gregor838db382010-02-11 01:19:42 +00002733 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002734 }
2735 return Context->getTagDeclType(ConstantStringDecl);
2736}
2737
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002738Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2739 SourceLocation StartLoc,
2740 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002741 if (!SelGetUidFunctionDecl)
2742 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002743 if (!MsgSendFunctionDecl)
2744 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002745 if (!MsgSendSuperFunctionDecl)
2746 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002747 if (!MsgSendStretFunctionDecl)
2748 SynthMsgSendStretFunctionDecl();
2749 if (!MsgSendSuperStretFunctionDecl)
2750 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002751 if (!MsgSendFpretFunctionDecl)
2752 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002753 if (!GetClassFunctionDecl)
2754 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002755 if (!GetSuperClassFunctionDecl)
2756 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002757 if (!GetMetaClassFunctionDecl)
2758 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002759
Steve Naroff874e2322007-11-15 10:28:18 +00002760 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002761 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2762 // May need to use objc_msgSend_stret() as well.
2763 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002764 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2765 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002766 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002767 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002768 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002769 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002770 }
Mike Stump1eb44332009-09-09 15:08:12 +00002771
Steve Naroff934f2762007-10-24 22:48:43 +00002772 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002773 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002774 switch (Exp->getReceiverKind()) {
2775 case ObjCMessageExpr::SuperClass: {
2776 MsgSendFlavor = MsgSendSuperFunctionDecl;
2777 if (MsgSendStretFlavor)
2778 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2779 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002780
Douglas Gregor04badcf2010-04-21 00:45:42 +00002781 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002782
Chris Lattner5f9e2722011-07-23 10:55:15 +00002783 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002784
Douglas Gregor04badcf2010-04-21 00:45:42 +00002785 // set the receiver to self, the first argument to all methods.
2786 InitExprs.push_back(
2787 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002788 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002789 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002790 Context->getObjCIdType(),
2791 VK_RValue,
2792 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002793 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002794
Douglas Gregor04badcf2010-04-21 00:45:42 +00002795 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002796 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002797 QualType argType = Context->getPointerType(Context->CharTy);
2798 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002799 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002800 StringLiteral::Ascii, false,
2801 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002802 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2803 &ClsExprs[0],
2804 ClsExprs.size(),
2805 StartLoc,
2806 EndLoc);
2807 // (Class)objc_getClass("CurrentClass")
2808 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2809 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002810 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002811 ClsExprs.clear();
2812 ClsExprs.push_back(ArgExpr);
2813 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2814 &ClsExprs[0], ClsExprs.size(),
2815 StartLoc, EndLoc);
2816
2817 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2818 // To turn off a warning, type-cast to 'id'
2819 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2820 NoTypeInfoCStyleCastExpr(Context,
2821 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002822 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002823 // struct objc_super
2824 QualType superType = getSuperStructType();
2825 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002826
Douglas Gregor04badcf2010-04-21 00:45:42 +00002827 if (LangOpts.Microsoft) {
2828 SynthSuperContructorFunctionDecl();
2829 // Simulate a contructor call...
2830 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002831 superType, VK_LValue,
2832 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002833 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2834 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002835 superType, VK_LValue,
2836 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002837 // The code for super is a little tricky to prevent collision with
2838 // the structure definition in the header. The rewriter has it's own
2839 // internal definition (__rw_objc_super) that is uses. This is why
2840 // we need the cast below. For example:
2841 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2842 //
John McCall2de56d12010-08-25 11:45:40 +00002843 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002844 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002845 VK_RValue, OK_Ordinary,
2846 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002847 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2848 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002849 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002850 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002851 // (struct objc_super) { <exprs from above> }
2852 InitListExpr *ILE =
2853 new (Context) InitListExpr(*Context, SourceLocation(),
2854 &InitExprs[0], InitExprs.size(),
2855 SourceLocation());
2856 TypeSourceInfo *superTInfo
2857 = Context->getTrivialTypeSourceInfo(superType);
2858 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002859 superType, VK_LValue,
2860 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002861 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002862 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002863 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002864 VK_RValue, OK_Ordinary,
2865 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002866 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002867 MsgExprs.push_back(SuperRep);
2868 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002869 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002870
2871 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002872 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002873 QualType argType = Context->getPointerType(Context->CharTy);
2874 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002875 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002876 IdentifierInfo *clsName = Class->getIdentifier();
2877 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002878 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002879 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002880 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002881 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2882 &ClsExprs[0],
2883 ClsExprs.size(),
2884 StartLoc, EndLoc);
2885 MsgExprs.push_back(Cls);
2886 break;
2887 }
2888
2889 case ObjCMessageExpr::SuperInstance:{
2890 MsgSendFlavor = MsgSendSuperFunctionDecl;
2891 if (MsgSendStretFlavor)
2892 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2893 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2894 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002895 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002896
2897 InitExprs.push_back(
2898 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002899 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002900 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002901 Context->getObjCIdType(),
2902 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002903 ); // set the 'receiver'.
2904
2905 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002906 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002907 QualType argType = Context->getPointerType(Context->CharTy);
2908 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002909 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002910 StringLiteral::Ascii, false, argType,
2911 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002912 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2913 &ClsExprs[0],
2914 ClsExprs.size(),
2915 StartLoc, EndLoc);
2916 // (Class)objc_getClass("CurrentClass")
2917 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2918 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002919 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002920 ClsExprs.clear();
2921 ClsExprs.push_back(ArgExpr);
2922 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2923 &ClsExprs[0], ClsExprs.size(),
2924 StartLoc, EndLoc);
2925
2926 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2927 // To turn off a warning, type-cast to 'id'
2928 InitExprs.push_back(
2929 // set 'super class', using class_getSuperclass().
2930 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002931 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002932 // struct objc_super
2933 QualType superType = getSuperStructType();
2934 Expr *SuperRep;
2935
2936 if (LangOpts.Microsoft) {
2937 SynthSuperContructorFunctionDecl();
2938 // Simulate a contructor call...
2939 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002940 superType, VK_LValue,
2941 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002942 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2943 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002944 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002945 // The code for super is a little tricky to prevent collision with
2946 // the structure definition in the header. The rewriter has it's own
2947 // internal definition (__rw_objc_super) that is uses. This is why
2948 // we need the cast below. For example:
2949 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2950 //
John McCall2de56d12010-08-25 11:45:40 +00002951 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002952 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002953 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002954 SourceLocation());
2955 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2956 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002957 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002958 } else {
2959 // (struct objc_super) { <exprs from above> }
2960 InitListExpr *ILE =
2961 new (Context) InitListExpr(*Context, SourceLocation(),
2962 &InitExprs[0], InitExprs.size(),
2963 SourceLocation());
2964 TypeSourceInfo *superTInfo
2965 = Context->getTrivialTypeSourceInfo(superType);
2966 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002967 superType, VK_RValue, ILE,
2968 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002969 }
2970 MsgExprs.push_back(SuperRep);
2971 break;
2972 }
2973
2974 case ObjCMessageExpr::Instance: {
2975 // Remove all type-casts because it may contain objc-style types; e.g.
2976 // Foo<Proto> *.
2977 Expr *recExpr = Exp->getInstanceReceiver();
2978 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2979 recExpr = CE->getSubExpr();
2980 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002981 CK_BitCast, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002982 MsgExprs.push_back(recExpr);
2983 break;
2984 }
2985 }
2986
Steve Naroffbeaf2992007-11-03 11:27:19 +00002987 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002988 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00002989 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002990 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002991 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002992 StringLiteral::Ascii, false,
2993 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002994 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002995 &SelExprs[0], SelExprs.size(),
2996 StartLoc,
2997 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002998 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002999
Steve Naroff934f2762007-10-24 22:48:43 +00003000 // Now push any user supplied arguments.
3001 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00003002 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00003003 // Make all implicit casts explicit...ICE comes in handy:-)
3004 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3005 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00003006 QualType type = ICE->getType();
3007 if (needToScanForQualifiers(type))
3008 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003009 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003010 (void)convertBlockPointerToFunctionPointer(type);
John McCalla5bbc502010-11-15 09:46:46 +00003011 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003012 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003013 }
3014 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003015 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003016 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003017 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003018 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00003019 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00003020 CK_BitCast, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003021 }
Mike Stump1eb44332009-09-09 15:08:12 +00003022 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003023 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003024 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3025 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003026 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003027 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003028 }
Steve Naroffab972d32007-11-04 22:37:50 +00003029 // Generate the funky cast.
3030 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003031 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00003032 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003033
Steve Naroffab972d32007-11-04 22:37:50 +00003034 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003035 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3036 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3037 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003038 ArgTypes.push_back(Context->getObjCIdType());
3039 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003040 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003041 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003042 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3043 E = OMD->param_end(); PI != E; ++PI) {
3044 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003045 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003046 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003047 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003048 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003049 ArgTypes.push_back(t);
3050 }
Chris Lattner89951a82009-02-20 18:43:26 +00003051 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3052 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003053 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003054 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003055 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003056 }
3057 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003058 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003059
Steve Naroffab972d32007-11-04 22:37:50 +00003060 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003061 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003062 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003063
Mike Stump1eb44332009-09-09 15:08:12 +00003064 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003065 // If we don't do this cast, we get the following bizarre warning/note:
3066 // xx.m:13: warning: function called through a non-compatible type
3067 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003068 cast = NoTypeInfoCStyleCastExpr(Context,
3069 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003070 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003071
Steve Naroffab972d32007-11-04 22:37:50 +00003072 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003073 QualType castType =
3074 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3075 // If we don't have a method decl, force a variadic cast.
3076 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003077 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003078 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003079 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003080
3081 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003082 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003083
John McCall183700f2009-09-21 23:43:11 +00003084 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003085 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003086 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003087 FT->getResultType(), VK_RValue,
3088 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003089 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003090 if (MsgSendStretFlavor) {
3091 // We have the method which returns a struct/union. Must also generate
3092 // call to objc_msgSend_stret and hang both varieties on a conditional
3093 // expression which dictate which one to envoke depending on size of
3094 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003095
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003096 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003097 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003098 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003099 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003100 cast = NoTypeInfoCStyleCastExpr(Context,
3101 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003102 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003103 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003104 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3105 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003106 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003107 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003108 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003109
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003110 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003111 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003112
John McCall183700f2009-09-21 23:43:11 +00003113 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003114 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003115 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003116 FT->getResultType(), VK_RValue,
3117 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003118
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003119 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003120 UnaryExprOrTypeTraitExpr *sizeofExpr =
3121 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3122 Context->getTrivialTypeSourceInfo(returnType),
3123 Context->getSizeType(), SourceLocation(),
3124 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003125 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3126 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3127 // For X86 it is more complicated and some kind of target specific routine
3128 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003129 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003130 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003131 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3132 llvm::APInt(IntSize, 8),
3133 Context->IntTy,
3134 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003135 BinaryOperator *lessThanExpr =
3136 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3137 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003138 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003139 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003140 new (Context) ConditionalOperator(lessThanExpr,
3141 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003142 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003143 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003144 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3145 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003146 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003147 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003148 return ReplacingStmt;
3149}
3150
Steve Naroffb29b4272008-04-14 22:03:09 +00003151Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003152 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3153 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003154
Steve Naroff934f2762007-10-24 22:48:43 +00003155 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003156 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003157
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003158 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003159 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003160}
3161
Steve Naroff621edce2009-04-29 16:37:50 +00003162// typedef struct objc_object Protocol;
3163QualType RewriteObjC::getProtocolType() {
3164 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003165 TypeSourceInfo *TInfo
3166 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003167 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003168 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003169 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003170 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003171 }
3172 return Context->getTypeDeclType(ProtocolTypeDecl);
3173}
3174
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003175/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003176/// a synthesized/forward data reference (to the protocol's metadata).
3177/// The forward references (and metadata) are generated in
3178/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003179Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003180 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3181 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003182 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003183 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003184 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003185 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3186 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003187 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003188 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003189 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003190 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003191 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003192 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003193 ReplaceStmt(Exp, castExpr);
3194 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003195 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003196 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003197
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003198}
3199
Mike Stump1eb44332009-09-09 15:08:12 +00003200bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003201 const char *endBuf) {
3202 while (startBuf < endBuf) {
3203 if (*startBuf == '#') {
3204 // Skip whitespace.
3205 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3206 ;
3207 if (!strncmp(startBuf, "if", strlen("if")) ||
3208 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3209 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3210 !strncmp(startBuf, "define", strlen("define")) ||
3211 !strncmp(startBuf, "undef", strlen("undef")) ||
3212 !strncmp(startBuf, "else", strlen("else")) ||
3213 !strncmp(startBuf, "elif", strlen("elif")) ||
3214 !strncmp(startBuf, "endif", strlen("endif")) ||
3215 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3216 !strncmp(startBuf, "include", strlen("include")) ||
3217 !strncmp(startBuf, "import", strlen("import")) ||
3218 !strncmp(startBuf, "include_next", strlen("include_next")))
3219 return true;
3220 }
3221 startBuf++;
3222 }
3223 return false;
3224}
3225
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003226/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003227/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003228void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003229 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003230 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003231 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003232 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003233 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003234 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003235 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003236 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003237 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003238 SourceLocation LocStart = CDecl->getLocStart();
3239 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003240
Steve Narofffea763e82007-11-14 19:25:57 +00003241 const char *startBuf = SM->getCharacterData(LocStart);
3242 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003243
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003244 // If no ivars and no root or if its root, directly or indirectly,
3245 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003246 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3247 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003248 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003249 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003250 return;
3251 }
Mike Stump1eb44332009-09-09 15:08:12 +00003252
3253 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003254 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003255 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003256 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003257 if (LangOpts.Microsoft)
3258 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003259
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003260 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003261 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003262 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003263 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003264 // If the buffer contains preprocessor directives, we do more fine-grained
3265 // rewrites. This is intended to fix code that looks like (which occurs in
3266 // NSURL.h, for example):
3267 //
3268 // #ifdef XYZ
3269 // @interface Foo : NSObject
3270 // #else
3271 // @interface FooBar : NSObject
3272 // #endif
3273 // {
3274 // int i;
3275 // }
3276 // @end
3277 //
3278 // This clause is segregated to avoid breaking the common case.
3279 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003280 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003281 CDecl->getClassLoc();
3282 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003283 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003284
Chris Lattnercafeb352009-02-20 18:18:36 +00003285 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003286 // advance to the end of the referenced protocols.
3287 while (endHeader < cursor && *endHeader != '>') endHeader++;
3288 endHeader++;
3289 }
3290 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003291 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003292 } else {
3293 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003294 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003295 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003296 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003297 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003298 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003299 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003300 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003301 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003302
Steve Narofffea763e82007-11-14 19:25:57 +00003303 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003304 SourceLocation OnePastCurly =
3305 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003306 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003307 }
3308 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003309
Steve Narofffea763e82007-11-14 19:25:57 +00003310 // Now comment out any visibility specifiers.
3311 while (cursor < endBuf) {
3312 if (*cursor == '@') {
3313 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003314 // Skip whitespace.
3315 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3316 /*scan*/;
3317
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003318 // FIXME: presence of @public, etc. inside comment results in
3319 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003320 if (!strncmp(cursor, "public", strlen("public")) ||
3321 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003322 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003323 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003324 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003325 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003326 // FIXME: If there are cases where '<' is used in ivar declaration part
3327 // of user code, then scan the ivar list and use needToScanForQualifiers
3328 // for type checking.
3329 else if (*cursor == '<') {
3330 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003331 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003332 cursor = strchr(cursor, '>');
3333 cursor++;
3334 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003335 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003336 } else if (*cursor == '^') { // rewrite block specifier.
3337 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003338 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003339 }
Steve Narofffea763e82007-11-14 19:25:57 +00003340 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003341 }
Steve Narofffea763e82007-11-14 19:25:57 +00003342 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003343 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003344 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003345 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003346 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003347 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003348 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003349 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003350 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003351 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003352 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003353 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003354 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003355 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003356}
3357
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003358// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003359/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003360template<typename MethodIterator>
3361void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3362 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003363 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003364 StringRef prefix,
3365 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003366 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003367 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003368
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003369 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003370 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003371 SEL _cmd;
3372 char *method_types;
3373 void *_imp;
3374 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003375 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003376 Result += "\nstruct _objc_method {\n";
3377 Result += "\tSEL _cmd;\n";
3378 Result += "\tchar *method_types;\n";
3379 Result += "\tvoid *_imp;\n";
3380 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003381
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003382 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003383 }
Mike Stump1eb44332009-09-09 15:08:12 +00003384
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003385 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003386
Steve Naroff946a6932008-03-11 00:12:29 +00003387 /* struct {
3388 struct _objc_method_list *next_method;
3389 int method_count;
3390 struct _objc_method method_list[];
3391 }
3392 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003393 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003394 Result += "\nstatic struct {\n";
3395 Result += "\tstruct _objc_method_list *next_method;\n";
3396 Result += "\tint method_count;\n";
3397 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003398 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003399 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003400 Result += prefix;
3401 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3402 Result += "_METHODS_";
3403 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003404 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003405 Result += IsInstanceMethod ? "inst" : "cls";
3406 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003407 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003408
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003409 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003410 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003411 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003412 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003413 Result += "\", \"";
3414 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003415 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003416 Result += MethodInternalNames[*MethodBegin];
3417 Result += "}\n";
3418 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3419 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003420 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003421 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003422 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003423 Result += "\", \"";
3424 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003425 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003426 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003427 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003428 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003429 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003430}
3431
Steve Naroff621edce2009-04-29 16:37:50 +00003432/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003433void RewriteObjC::
Chris Lattner5f9e2722011-07-23 10:55:15 +00003434RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, StringRef prefix,
3435 StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003436 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003437
3438 // Output struct protocol_methods holder of method selector and type.
3439 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3440 /* struct protocol_methods {
3441 SEL _cmd;
3442 char *method_types;
3443 }
3444 */
3445 Result += "\nstruct _protocol_methods {\n";
3446 Result += "\tstruct objc_selector *_cmd;\n";
3447 Result += "\tchar *method_types;\n";
3448 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003449
Steve Naroff621edce2009-04-29 16:37:50 +00003450 objc_protocol_methods = true;
3451 }
3452 // Do not synthesize the protocol more than once.
3453 if (ObjCSynthesizedProtocols.count(PDecl))
3454 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003455
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003456 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3457 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3458 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003459 /* struct _objc_protocol_method_list {
3460 int protocol_method_count;
3461 struct protocol_methods protocols[];
3462 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003463 */
Steve Naroff621edce2009-04-29 16:37:50 +00003464 Result += "\nstatic struct {\n";
3465 Result += "\tint protocol_method_count;\n";
3466 Result += "\tstruct _protocol_methods protocol_methods[";
3467 Result += utostr(NumMethods);
3468 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3469 Result += PDecl->getNameAsString();
3470 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3471 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003472
Steve Naroff621edce2009-04-29 16:37:50 +00003473 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003474 for (ObjCProtocolDecl::instmeth_iterator
3475 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003476 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003477 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003478 Result += "\t ,{{(struct objc_selector *)\"";
3479 else
3480 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003481 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003482 std::string MethodTypeString;
3483 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3484 Result += "\", \"";
3485 Result += MethodTypeString;
3486 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003487 }
Steve Naroff621edce2009-04-29 16:37:50 +00003488 Result += "\t }\n};\n";
3489 }
Mike Stump1eb44332009-09-09 15:08:12 +00003490
Steve Naroff621edce2009-04-29 16:37:50 +00003491 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003492 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3493 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003494 if (NumMethods > 0) {
3495 /* struct _objc_protocol_method_list {
3496 int protocol_method_count;
3497 struct protocol_methods protocols[];
3498 }
3499 */
3500 Result += "\nstatic struct {\n";
3501 Result += "\tint protocol_method_count;\n";
3502 Result += "\tstruct _protocol_methods protocol_methods[";
3503 Result += utostr(NumMethods);
3504 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3505 Result += PDecl->getNameAsString();
3506 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3507 "{\n\t";
3508 Result += utostr(NumMethods);
3509 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003510
Steve Naroff621edce2009-04-29 16:37:50 +00003511 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003512 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003513 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003514 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003515 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003516 Result += "\t ,{{(struct objc_selector *)\"";
3517 else
3518 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003519 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003520 std::string MethodTypeString;
3521 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3522 Result += "\", \"";
3523 Result += MethodTypeString;
3524 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003525 }
Steve Naroff621edce2009-04-29 16:37:50 +00003526 Result += "\t }\n};\n";
3527 }
3528
3529 // Output:
3530 /* struct _objc_protocol {
3531 // Objective-C 1.0 extensions
3532 struct _objc_protocol_extension *isa;
3533 char *protocol_name;
3534 struct _objc_protocol **protocol_list;
3535 struct _objc_protocol_method_list *instance_methods;
3536 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003537 };
Steve Naroff621edce2009-04-29 16:37:50 +00003538 */
3539 static bool objc_protocol = false;
3540 if (!objc_protocol) {
3541 Result += "\nstruct _objc_protocol {\n";
3542 Result += "\tstruct _objc_protocol_extension *isa;\n";
3543 Result += "\tchar *protocol_name;\n";
3544 Result += "\tstruct _objc_protocol **protocol_list;\n";
3545 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3546 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003547 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003548
Steve Naroff621edce2009-04-29 16:37:50 +00003549 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003550 }
Mike Stump1eb44332009-09-09 15:08:12 +00003551
Steve Naroff621edce2009-04-29 16:37:50 +00003552 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3553 Result += PDecl->getNameAsString();
3554 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3555 "{\n\t0, \"";
3556 Result += PDecl->getNameAsString();
3557 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003558 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003559 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3560 Result += PDecl->getNameAsString();
3561 Result += ", ";
3562 }
3563 else
3564 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003565 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003566 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3567 Result += PDecl->getNameAsString();
3568 Result += "\n";
3569 }
3570 else
3571 Result += "0\n";
3572 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003573
Steve Naroff621edce2009-04-29 16:37:50 +00003574 // Mark this protocol as having been generated.
3575 if (!ObjCSynthesizedProtocols.insert(PDecl))
3576 assert(false && "protocol already synthesized");
3577
3578}
3579
3580void RewriteObjC::
3581RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003582 StringRef prefix, StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003583 std::string &Result) {
3584 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003585
Steve Naroff621edce2009-04-29 16:37:50 +00003586 for (unsigned i = 0; i != Protocols.size(); i++)
3587 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3588
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003589 // Output the top lovel protocol meta-data for the class.
3590 /* struct _objc_protocol_list {
3591 struct _objc_protocol_list *next;
3592 int protocol_count;
3593 struct _objc_protocol *class_protocols[];
3594 }
3595 */
3596 Result += "\nstatic struct {\n";
3597 Result += "\tstruct _objc_protocol_list *next;\n";
3598 Result += "\tint protocol_count;\n";
3599 Result += "\tstruct _objc_protocol *class_protocols[";
3600 Result += utostr(Protocols.size());
3601 Result += "];\n} _OBJC_";
3602 Result += prefix;
3603 Result += "_PROTOCOLS_";
3604 Result += ClassName;
3605 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3606 "{\n\t0, ";
3607 Result += utostr(Protocols.size());
3608 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003609
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003610 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003611 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003612 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003613
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003614 for (unsigned i = 1; i != Protocols.size(); i++) {
3615 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003616 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003617 Result += "\n";
3618 }
3619 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003620}
3621
Steve Naroff621edce2009-04-29 16:37:50 +00003622
Mike Stump1eb44332009-09-09 15:08:12 +00003623/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003624/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003625void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003626 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003627 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003628 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003629 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003630 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003631 CDecl = CDecl->getNextClassCategory())
3632 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3633 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003634
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003635 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003636 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003637 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003638
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003639 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003640 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003641 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003642
3643 // If any of our property implementations have associated getters or
3644 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003645 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3646 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003647 Prop != PropEnd; ++Prop) {
3648 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3649 continue;
3650 if (!(*Prop)->getPropertyIvarDecl())
3651 continue;
3652 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3653 if (!PD)
3654 continue;
3655 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3656 InstanceMethods.push_back(Getter);
3657 if (PD->isReadOnly())
3658 continue;
3659 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3660 InstanceMethods.push_back(Setter);
3661 }
3662 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003663 true, "CATEGORY_", FullCategoryName.c_str(),
3664 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003665
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003666 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003667 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003668 false, "CATEGORY_", FullCategoryName.c_str(),
3669 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003670
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003671 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003672 // Null CDecl is case of a category implementation with no category interface
3673 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003674 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003675 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003676 /* struct _objc_category {
3677 char *category_name;
3678 char *class_name;
3679 struct _objc_method_list *instance_methods;
3680 struct _objc_method_list *class_methods;
3681 struct _objc_protocol_list *protocols;
3682 // Objective-C 1.0 extensions
3683 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003684 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003685 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003686 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003687 */
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003689 static bool objc_category = false;
3690 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003691 Result += "\nstruct _objc_category {\n";
3692 Result += "\tchar *category_name;\n";
3693 Result += "\tchar *class_name;\n";
3694 Result += "\tstruct _objc_method_list *instance_methods;\n";
3695 Result += "\tstruct _objc_method_list *class_methods;\n";
3696 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003697 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003698 Result += "\tstruct _objc_property_list *instance_properties;\n";
3699 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003700 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003701 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003702 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3703 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003704 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003705 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003706 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003707 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003708 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003709
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003710 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003711 Result += "\t, (struct _objc_method_list *)"
3712 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3713 Result += FullCategoryName;
3714 Result += "\n";
3715 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003716 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003717 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003718 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003719 Result += "\t, (struct _objc_method_list *)"
3720 "&_OBJC_CATEGORY_CLASS_METHODS_";
3721 Result += FullCategoryName;
3722 Result += "\n";
3723 }
3724 else
3725 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003726
Chris Lattnercafeb352009-02-20 18:18:36 +00003727 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003728 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003729 Result += FullCategoryName;
3730 Result += "\n";
3731 }
3732 else
3733 Result += "\t, 0\n";
3734 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003735}
3736
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003737/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3738/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003739void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003740 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003741 if (ivar->isBitField()) {
3742 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3743 // place all bitfields at offset 0.
3744 Result += "0";
3745 } else {
3746 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003747 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003748 if (LangOpts.Microsoft)
3749 Result += "_IMPL";
3750 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003751 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003752 Result += ")";
3753 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003754}
3755
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003756//===----------------------------------------------------------------------===//
3757// Meta Data Emission
3758//===----------------------------------------------------------------------===//
3759
Steve Naroffb29b4272008-04-14 22:03:09 +00003760void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003761 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003762 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003763
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003764 // Explicitly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003765 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003766 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003767 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003768 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003769 }
Mike Stump1eb44332009-09-09 15:08:12 +00003770
Chris Lattnerbe6df082007-12-12 07:56:42 +00003771 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003772 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003773 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003774 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003775 if (NumIvars > 0) {
3776 static bool objc_ivar = false;
3777 if (!objc_ivar) {
3778 /* struct _objc_ivar {
3779 char *ivar_name;
3780 char *ivar_type;
3781 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003782 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003783 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003784 Result += "\nstruct _objc_ivar {\n";
3785 Result += "\tchar *ivar_name;\n";
3786 Result += "\tchar *ivar_type;\n";
3787 Result += "\tint ivar_offset;\n";
3788 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003789
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003790 objc_ivar = true;
3791 }
3792
Steve Naroff946a6932008-03-11 00:12:29 +00003793 /* struct {
3794 int ivar_count;
3795 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003796 };
Steve Naroff946a6932008-03-11 00:12:29 +00003797 */
Mike Stump1eb44332009-09-09 15:08:12 +00003798 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003799 Result += "\tint ivar_count;\n";
3800 Result += "\tstruct _objc_ivar ivar_list[";
3801 Result += utostr(NumIvars);
3802 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003803 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003804 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003805 "{\n\t";
3806 Result += utostr(NumIvars);
3807 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003808
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003809 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003810 SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003811 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003812 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003813 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003814 IV != IVEnd; ++IV)
3815 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003816 IVI = IDecl->ivar_begin();
3817 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003818 } else {
3819 IVI = CDecl->ivar_begin();
3820 IVE = CDecl->ivar_end();
3821 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003822 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003823 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003824 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003825 std::string TmpString, StrEncoding;
3826 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3827 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003828 Result += StrEncoding;
3829 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003830 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003831 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003832 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003833 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003834 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003835 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003836 std::string TmpString, StrEncoding;
3837 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3838 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003839 Result += StrEncoding;
3840 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003841 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003842 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003843 }
Mike Stump1eb44332009-09-09 15:08:12 +00003844
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003845 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003846 }
Mike Stump1eb44332009-09-09 15:08:12 +00003847
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003848 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003849 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003850 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003851
3852 // If any of our property implementations have associated getters or
3853 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003854 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3855 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003856 Prop != PropEnd; ++Prop) {
3857 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3858 continue;
3859 if (!(*Prop)->getPropertyIvarDecl())
3860 continue;
3861 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3862 if (!PD)
3863 continue;
3864 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003865 if (!Getter->isDefined())
3866 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003867 if (PD->isReadOnly())
3868 continue;
3869 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003870 if (!Setter->isDefined())
3871 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003872 }
3873 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003874 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003875
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003876 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003877 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003878 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003879
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003880 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003881 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003882 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003883
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003884 // Declaration of class/meta-class metadata
3885 /* struct _objc_class {
3886 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003887 const char *super_class_name;
3888 char *name;
3889 long version;
3890 long info;
3891 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003892 struct _objc_ivar_list *ivars;
3893 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003894 struct objc_cache *cache;
3895 struct objc_protocol_list *protocols;
3896 const char *ivar_layout;
3897 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003898 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003899 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003900 static bool objc_class = false;
3901 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003902 Result += "\nstruct _objc_class {\n";
3903 Result += "\tstruct _objc_class *isa;\n";
3904 Result += "\tconst char *super_class_name;\n";
3905 Result += "\tchar *name;\n";
3906 Result += "\tlong version;\n";
3907 Result += "\tlong info;\n";
3908 Result += "\tlong instance_size;\n";
3909 Result += "\tstruct _objc_ivar_list *ivars;\n";
3910 Result += "\tstruct _objc_method_list *methods;\n";
3911 Result += "\tstruct objc_cache *cache;\n";
3912 Result += "\tstruct _objc_protocol_list *protocols;\n";
3913 Result += "\tconst char *ivar_layout;\n";
3914 Result += "\tstruct _objc_class_ext *ext;\n";
3915 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003916 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003917 }
Mike Stump1eb44332009-09-09 15:08:12 +00003918
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003919 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003920 ObjCInterfaceDecl *RootClass = 0;
3921 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003922 while (SuperClass) {
3923 RootClass = SuperClass;
3924 SuperClass = SuperClass->getSuperClass();
3925 }
3926 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003927
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003928 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003929 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003930 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003931 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003932 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003933 Result += "\"";
3934
3935 if (SuperClass) {
3936 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003937 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003938 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003939 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003940 Result += "\"";
3941 }
3942 else {
3943 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003944 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003945 Result += "\"";
3946 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003947 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003948 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003949 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003950 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003951 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003952 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003953 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003954 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003955 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003956 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003957 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003958 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003959 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003960 Result += ",0,0\n";
3961 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003962 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003963 Result += "\t,0,0,0,0\n";
3964 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003965
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003966 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003967 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003968 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003969 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003970 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003971 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003972 if (SuperClass) {
3973 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003974 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003975 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003976 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003977 Result += "\"";
3978 }
3979 else {
3980 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003981 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003982 Result += "\"";
3983 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003984 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003985 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003986 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003987 Result += ",0";
3988 else {
3989 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003990 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003991 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003992 if (LangOpts.Microsoft)
3993 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003994 Result += ")";
3995 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003996 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003997 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003998 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003999 Result += "\n\t";
4000 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004001 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004002 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004003 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00004004 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004005 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004006 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004007 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004008 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004009 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00004010 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004011 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004012 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004013 Result += ", 0,0\n";
4014 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004015 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004016 Result += ",0,0,0\n";
4017 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004018}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004019
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004020/// RewriteImplementations - This routine rewrites all method implementations
4021/// and emits meta-data.
4022
Steve Narofface66252008-11-13 20:07:04 +00004023void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004024 int ClsDefCount = ClassImplementation.size();
4025 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004026
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004027 // Rewrite implemented methods
4028 for (int i = 0; i < ClsDefCount; i++)
4029 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004030
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004031 for (int i = 0; i < CatDefCount; i++)
4032 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004033}
Mike Stump1eb44332009-09-09 15:08:12 +00004034
Steve Narofface66252008-11-13 20:07:04 +00004035void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4036 int ClsDefCount = ClassImplementation.size();
4037 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004038
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004039 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004040 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004041 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004042
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004043 // For each implemented category, write out all its meta data.
4044 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004045 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004046
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004047 // Write objc_symtab metadata
4048 /*
4049 struct _objc_symtab
4050 {
4051 long sel_ref_cnt;
4052 SEL *refs;
4053 short cls_def_cnt;
4054 short cat_def_cnt;
4055 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004056 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004057 */
Mike Stump1eb44332009-09-09 15:08:12 +00004058
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004059 Result += "\nstruct _objc_symtab {\n";
4060 Result += "\tlong sel_ref_cnt;\n";
4061 Result += "\tSEL *refs;\n";
4062 Result += "\tshort cls_def_cnt;\n";
4063 Result += "\tshort cat_def_cnt;\n";
4064 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4065 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004066
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004067 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004068 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004069 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004070 + ", " + utostr(CatDefCount) + "\n";
4071 for (int i = 0; i < ClsDefCount; i++) {
4072 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004073 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004074 Result += "\n";
4075 }
Mike Stump1eb44332009-09-09 15:08:12 +00004076
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004077 for (int i = 0; i < CatDefCount; i++) {
4078 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004079 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004080 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004081 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004082 Result += "\n";
4083 }
Mike Stump1eb44332009-09-09 15:08:12 +00004084
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004085 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004086
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004087 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004088
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004089 /*
4090 struct _objc_module {
4091 long version;
4092 long size;
4093 const char *name;
4094 struct _objc_symtab *symtab;
4095 }
4096 */
Mike Stump1eb44332009-09-09 15:08:12 +00004097
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004098 Result += "\nstruct _objc_module {\n";
4099 Result += "\tlong version;\n";
4100 Result += "\tlong size;\n";
4101 Result += "\tconst char *name;\n";
4102 Result += "\tstruct _objc_symtab *symtab;\n";
4103 Result += "};\n\n";
4104 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004105 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004106 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004107 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004108 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004109
4110 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004111 if (ProtocolExprDecls.size()) {
4112 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4113 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004114 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004115 E = ProtocolExprDecls.end(); I != E; ++I) {
4116 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4117 Result += (*I)->getNameAsString();
4118 Result += " = &_OBJC_PROTOCOL_";
4119 Result += (*I)->getNameAsString();
4120 Result += ";\n";
4121 }
4122 Result += "#pragma data_seg(pop)\n\n";
4123 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004124 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004125 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004126 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4127 Result += "&_OBJC_MODULES;\n";
4128 Result += "#pragma data_seg(pop)\n\n";
4129 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004130}
Chris Lattner311ff022007-10-16 22:36:42 +00004131
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004132void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4133 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004134 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004135 assert(BlockByRefDeclNo.count(VD) &&
4136 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004137 if (def)
4138 ResultStr += "struct ";
4139 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004140 "_" + utostr(BlockByRefDeclNo[VD]) ;
4141}
4142
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004143static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4144 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4145 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4146 return false;
4147}
4148
Steve Naroff54055232008-10-27 17:20:55 +00004149std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004150 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004151 std::string Tag) {
4152 const FunctionType *AFT = CE->getFunctionType();
4153 QualType RT = AFT->getResultType();
4154 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004155 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004156 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004157
Steve Naroff54055232008-10-27 17:20:55 +00004158 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004159
Douglas Gregor72564e72009-02-26 23:50:07 +00004160 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004161 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004162 // block (to reference imported block decl refs).
4163 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004164 } else if (BD->param_empty()) {
4165 S += "(" + StructRef + " *__cself)";
4166 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004167 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004168 assert(FT && "SynthesizeBlockFunc: No function proto");
4169 S += '(';
4170 // first add the implicit argument.
4171 S += StructRef + " *__cself, ";
4172 std::string ParamStr;
4173 for (BlockDecl::param_iterator AI = BD->param_begin(),
4174 E = BD->param_end(); AI != E; ++AI) {
4175 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004176 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004177 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004178 if (convertBlockPointerToFunctionPointer(QT))
4179 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004180 else
4181 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004182 S += ParamStr;
4183 }
4184 if (FT->isVariadic()) {
4185 if (!BD->param_empty()) S += ", ";
4186 S += "...";
4187 }
4188 S += ')';
4189 }
4190 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004191
Steve Naroff54055232008-10-27 17:20:55 +00004192 // Create local declarations to avoid rewriting all closure decl ref exprs.
4193 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004194 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004195 E = BlockByRefDecls.end(); I != E; ++I) {
4196 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004197 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004198 std::string TypeString;
4199 RewriteByRefString(TypeString, Name, (*I));
4200 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004201 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004202 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004203 }
Steve Naroff54055232008-10-27 17:20:55 +00004204 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004205 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004206 E = BlockByCopyDecls.end(); I != E; ++I) {
4207 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004208 // Handle nested closure invocation. For example:
4209 //
4210 // void (^myImportedClosure)(void);
4211 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004212 //
Steve Naroff54055232008-10-27 17:20:55 +00004213 // void (^anotherClosure)(void);
4214 // anotherClosure = ^(void) {
4215 // myImportedClosure(); // import and invoke the closure
4216 // };
4217 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004218 if (isTopLevelBlockPointerType((*I)->getType())) {
4219 RewriteBlockPointerTypeVariable(S, (*I));
4220 S += " = (";
4221 RewriteBlockPointerType(S, (*I)->getType());
4222 S += ")";
4223 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4224 }
4225 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004226 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004227 QualType QT = (*I)->getType();
4228 if (HasLocalVariableExternalStorage(*I))
4229 QT = Context->getPointerType(QT);
4230 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004231 S += Name + " = __cself->" +
4232 (*I)->getNameAsString() + "; // bound by copy\n";
4233 }
Steve Naroff54055232008-10-27 17:20:55 +00004234 }
4235 std::string RewrittenStr = RewrittenBlockExprs[CE];
4236 const char *cstr = RewrittenStr.c_str();
4237 while (*cstr++ != '{') ;
4238 S += cstr;
4239 S += "\n";
4240 return S;
4241}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004242
Steve Naroff54055232008-10-27 17:20:55 +00004243std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004244 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004245 std::string Tag) {
4246 std::string StructRef = "struct " + Tag;
4247 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004248
Steve Naroff54055232008-10-27 17:20:55 +00004249 S += funcName;
4250 S += "_block_copy_" + utostr(i);
4251 S += "(" + StructRef;
4252 S += "*dst, " + StructRef;
4253 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004254 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004255 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004256 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004257 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004258 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004259 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004260 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004261 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004262 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004263 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004264 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004265 S += "}\n";
4266
Steve Naroff54055232008-10-27 17:20:55 +00004267 S += "\nstatic void __";
4268 S += funcName;
4269 S += "_block_dispose_" + utostr(i);
4270 S += "(" + StructRef;
4271 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004272 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004273 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004274 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004275 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004276 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004277 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004278 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004279 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004280 }
Mike Stump1eb44332009-09-09 15:08:12 +00004281 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004282 return S;
4283}
4284
Steve Naroff01aec112009-12-06 21:14:13 +00004285std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4286 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004287 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004288 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004289
Steve Naroff54055232008-10-27 17:20:55 +00004290 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004291 S += " struct " + Desc;
4292 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004293
Steve Naroff01aec112009-12-06 21:14:13 +00004294 Constructor += "(void *fp, "; // Invoke function pointer.
4295 Constructor += "struct " + Desc; // Descriptor pointer.
4296 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004297
Steve Naroff54055232008-10-27 17:20:55 +00004298 if (BlockDeclRefs.size()) {
4299 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004300 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004301 E = BlockByCopyDecls.end(); I != E; ++I) {
4302 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004303 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004304 std::string ArgName = "_" + FieldName;
4305 // Handle nested closure invocation. For example:
4306 //
4307 // void (^myImportedBlock)(void);
4308 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004309 //
Steve Naroff54055232008-10-27 17:20:55 +00004310 // void (^anotherBlock)(void);
4311 // anotherBlock = ^(void) {
4312 // myImportedBlock(); // import and invoke the closure
4313 // };
4314 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004315 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004316 S += "struct __block_impl *";
4317 Constructor += ", void *" + ArgName;
4318 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004319 QualType QT = (*I)->getType();
4320 if (HasLocalVariableExternalStorage(*I))
4321 QT = Context->getPointerType(QT);
4322 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4323 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004324 Constructor += ", " + ArgName;
4325 }
4326 S += FieldName + ";\n";
4327 }
4328 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004329 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004330 E = BlockByRefDecls.end(); I != E; ++I) {
4331 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004332 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004333 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004334 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004335 std::string TypeString;
4336 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004337 TypeString += " *";
4338 FieldName = TypeString + FieldName;
4339 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004340 Constructor += ", " + ArgName;
4341 }
4342 S += FieldName + "; // by ref\n";
4343 }
4344 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004345 Constructor += ", int flags=0)";
4346 // Initialize all "by copy" arguments.
4347 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004348 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004349 E = BlockByCopyDecls.end(); I != E; ++I) {
4350 std::string Name = (*I)->getNameAsString();
4351 if (firsTime) {
4352 Constructor += " : ";
4353 firsTime = false;
4354 }
4355 else
4356 Constructor += ", ";
4357 if (isTopLevelBlockPointerType((*I)->getType()))
4358 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4359 else
4360 Constructor += Name + "(_" + Name + ")";
4361 }
4362 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004363 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004364 E = BlockByRefDecls.end(); I != E; ++I) {
4365 std::string Name = (*I)->getNameAsString();
4366 if (firsTime) {
4367 Constructor += " : ";
4368 firsTime = false;
4369 }
4370 else
4371 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004372 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004373 }
4374
4375 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004376 if (GlobalVarDecl)
4377 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4378 else
4379 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004380 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004381
Steve Naroff01aec112009-12-06 21:14:13 +00004382 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004383 } else {
4384 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004385 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004386 if (GlobalVarDecl)
4387 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4388 else
4389 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004390 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4391 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004392 }
4393 Constructor += " ";
4394 Constructor += "}\n";
4395 S += Constructor;
4396 S += "};\n";
4397 return S;
4398}
4399
Steve Naroff01aec112009-12-06 21:14:13 +00004400std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4401 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004402 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004403 unsigned hasCopy) {
4404 std::string S = "\nstatic struct " + DescTag;
4405
4406 S += " {\n unsigned long reserved;\n";
4407 S += " unsigned long Block_size;\n";
4408 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004409 S += " void (*copy)(struct ";
4410 S += ImplTag; S += "*, struct ";
4411 S += ImplTag; S += "*);\n";
4412
4413 S += " void (*dispose)(struct ";
4414 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004415 }
4416 S += "} ";
4417
4418 S += DescTag + "_DATA = { 0, sizeof(struct ";
4419 S += ImplTag + ")";
4420 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004421 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4422 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004423 }
4424 S += "};\n";
4425 return S;
4426}
4427
Steve Naroff54055232008-10-27 17:20:55 +00004428void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004429 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004430 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004431 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004432 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004433 bool RewriteSC = (GlobalVarDecl &&
4434 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004435 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004436 GlobalVarDecl->getType().getCVRQualifiers());
4437 if (RewriteSC) {
4438 std::string SC(" void __");
4439 SC += GlobalVarDecl->getNameAsString();
4440 SC += "() {}";
4441 InsertText(FunLocStart, SC);
4442 }
4443
Steve Naroff54055232008-10-27 17:20:55 +00004444 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004445 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4446 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004447 // Need to copy-in the inner copied-in variables not actually used in this
4448 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004449 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4450 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4451 ValueDecl *VD = Exp->getDecl();
4452 BlockDeclRefs.push_back(Exp);
4453 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4454 BlockByCopyDeclsPtrSet.insert(VD);
4455 BlockByCopyDecls.push_back(VD);
4456 }
4457 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4458 BlockByRefDeclsPtrSet.insert(VD);
4459 BlockByRefDecls.push_back(VD);
4460 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004461 // imported objects in the inner blocks not used in the outer
4462 // blocks must be copied/disposed in the outer block as well.
4463 if (Exp->isByRef() ||
4464 VD->getType()->isObjCObjectPointerType() ||
4465 VD->getType()->isBlockPointerType())
4466 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004467 }
Steve Naroff54055232008-10-27 17:20:55 +00004468
Daniel Dunbar4087f272010-08-17 22:39:59 +00004469 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4470 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004471
Steve Naroff01aec112009-12-06 21:14:13 +00004472 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004473
Benjamin Kramerd999b372010-02-14 14:14:16 +00004474 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004475
Steve Naroff01aec112009-12-06 21:14:13 +00004476 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004477
Benjamin Kramerd999b372010-02-14 14:14:16 +00004478 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004479
4480 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004481 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004482 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004483 }
Steve Naroff01aec112009-12-06 21:14:13 +00004484 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4485 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004486 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004487
Steve Naroff54055232008-10-27 17:20:55 +00004488 BlockDeclRefs.clear();
4489 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004490 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004491 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004492 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004493 ImportedBlockDecls.clear();
4494 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004495 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004496 // Must insert any 'const/volatile/static here. Since it has been
4497 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004498 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004499 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004500 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004501 if (GlobalVarDecl->getType().isConstQualified())
4502 SC += "const ";
4503 if (GlobalVarDecl->getType().isVolatileQualified())
4504 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004505 if (GlobalVarDecl->getType().isRestrictQualified())
4506 SC += "restrict ";
4507 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004508 }
4509
Steve Naroff54055232008-10-27 17:20:55 +00004510 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004511 InnerDeclRefsCount.clear();
4512 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004513 RewrittenBlockExprs.clear();
4514}
4515
4516void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4517 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00004518 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004519
Steve Naroff54055232008-10-27 17:20:55 +00004520 SynthesizeBlockLiterals(FunLocStart, FuncName);
4521}
4522
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004523static void BuildUniqueMethodName(std::string &Name,
4524 ObjCMethodDecl *MD) {
4525 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004526 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004527 Name += "__" + MD->getSelector().getAsString();
4528 // Convert colons to underscores.
4529 std::string::size_type loc = 0;
4530 while ((loc = Name.find(":", loc)) != std::string::npos)
4531 Name.replace(loc, 1, "_");
4532}
4533
Steve Naroff54055232008-10-27 17:20:55 +00004534void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004535 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4536 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004537 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004538 std::string FuncName;
4539 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004540 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004541}
4542
4543void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00004544 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00004545 if (*CI) {
4546 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4547 GetBlockDeclRefExprs(CBE->getBody());
4548 else
4549 GetBlockDeclRefExprs(*CI);
4550 }
4551 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004552 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004553 // FIXME: Handle enums.
4554 if (!isa<FunctionDecl>(CDRE->getDecl()))
4555 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004556 }
4557 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4558 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4559 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00004560 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4561 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004562 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004563 BlockDeclRefs.push_back(BDRE);
4564 }
4565
Steve Naroff54055232008-10-27 17:20:55 +00004566 return;
4567}
4568
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004569void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004570 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004571 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00004572 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004573 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004574 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4575 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004576 GetInnerBlockDeclRefExprs(CBE->getBody(),
4577 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004578 InnerContexts);
4579 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004580 else
4581 GetInnerBlockDeclRefExprs(*CI,
4582 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004583 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004584
4585 }
4586 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004587 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004588 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004589 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004590 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004591 }
4592 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4593 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4594 if (Var->isFunctionOrMethodVarDecl())
4595 ImportedLocalExternalDecls.insert(Var);
4596 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004597
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004598 return;
4599}
4600
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004601/// convertFunctionTypeOfBlocks - This routine converts a function type
4602/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00004603/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004604/// all block pointers to function pointers.
4605QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4606 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4607 // FTP will be null for closures that don't take arguments.
4608 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004609 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004610 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004611 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004612
4613 if (FTP) {
4614 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4615 E = FTP->arg_type_end(); I && (I != E); ++I) {
4616 QualType t = *I;
4617 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004618 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004619 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004620 ArgTypes.push_back(t);
4621 }
4622 }
4623 QualType FuncType;
4624 // FIXME. Does this work if block takes no argument but has a return type
4625 // which is of block type?
4626 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00004627 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004628 else FuncType = QualType(FT, 0);
4629 return FuncType;
4630}
4631
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004632Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004633 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004634 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004635
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004636 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004637 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004638 } else if (const BlockDeclRefExpr *CDRE =
4639 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004640 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004641 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004642 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004643 }
4644 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4645 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4646 }
4647 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4648 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4649 else if (const ConditionalOperator *CEXPR =
4650 dyn_cast<ConditionalOperator>(BlockExp)) {
4651 Expr *LHSExp = CEXPR->getLHS();
4652 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4653 Expr *RHSExp = CEXPR->getRHS();
4654 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4655 Expr *CONDExp = CEXPR->getCond();
4656 ConditionalOperator *CondExpr =
4657 new (Context) ConditionalOperator(CONDExp,
4658 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004659 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00004660 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004661 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004662 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4663 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004664 } else {
4665 assert(1 && "RewriteBlockClass: Bad type");
4666 }
4667 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004668 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004669 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004670 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004671 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004672
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004673 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004674 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004675 &Context->Idents.get("__block_impl"));
4676 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004677
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004678 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004679 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004680
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004681 // Push the block argument type.
4682 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004683 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004684 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004685 E = FTP->arg_type_end(); I && (I != E); ++I) {
4686 QualType t = *I;
4687 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004688 if (!convertBlockPointerToFunctionPointer(t))
4689 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004690 ArgTypes.push_back(t);
4691 }
Steve Naroff54055232008-10-27 17:20:55 +00004692 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004693 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00004694 QualType PtrToFuncCastType
4695 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004696
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004697 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004698
John McCall9d125032010-01-15 18:39:57 +00004699 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004700 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004701 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004702 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004703 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4704 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004705 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004706
Douglas Gregor44b43212008-12-11 16:49:14 +00004707 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004708 SourceLocation(),
4709 &Context->Idents.get("FuncPtr"),
4710 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004711 /*BitWidth=*/0, /*Mutable=*/true,
4712 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004713 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004714 FD->getType(), VK_LValue,
4715 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004716
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004717
John McCall9d125032010-01-15 18:39:57 +00004718 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004719 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004720 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004721
Chris Lattner5f9e2722011-07-23 10:55:15 +00004722 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004723 // Add the implicit argument.
4724 BlkExprs.push_back(BlkCast);
4725 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004726 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004727 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004728 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004729 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004730 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4731 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004732 Exp->getType(), VK_RValue,
4733 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004734 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004735}
4736
Steve Naroff621edce2009-04-29 16:37:50 +00004737// We need to return the rewritten expression to handle cases where the
4738// BlockDeclRefExpr is embedded in another expression being rewritten.
4739// For example:
4740//
4741// int main() {
4742// __block Foo *f;
4743// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004744//
Steve Naroff621edce2009-04-29 16:37:50 +00004745// void (^myblock)() = ^() {
4746// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4747// i = 77;
4748// };
4749//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004750Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004751 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004752 // for each DeclRefExp where BYREFVAR is name of the variable.
4753 ValueDecl *VD;
4754 bool isArrow = true;
4755 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4756 VD = BDRE->getDecl();
4757 else {
4758 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4759 isArrow = false;
4760 }
4761
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004762 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004763 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004764 &Context->Idents.get("__forwarding"),
4765 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004766 /*BitWidth=*/0, /*Mutable=*/true,
4767 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004768 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4769 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004770 FD->getType(), VK_LValue,
4771 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004772
Chris Lattner5f9e2722011-07-23 10:55:15 +00004773 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004774 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004775 &Context->Idents.get(Name),
4776 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004777 /*BitWidth=*/0, /*Mutable=*/true,
4778 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004779 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004780 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004781
4782
4783
Steve Naroffdf8570d2009-02-02 17:19:26 +00004784 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00004785 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4786 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004787 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004788 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004789 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004790}
4791
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004792// Rewrites the imported local variable V with external storage
4793// (static, extern, etc.) as *V
4794//
4795Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4796 ValueDecl *VD = DRE->getDecl();
4797 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4798 if (!ImportedLocalExternalDecls.count(Var))
4799 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004800 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4801 VK_LValue, OK_Ordinary,
4802 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004803 // Need parens to enforce precedence.
4804 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4805 Exp);
4806 ReplaceStmt(DRE, PE);
4807 return PE;
4808}
4809
Steve Naroffb2f9e512008-11-03 23:29:32 +00004810void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4811 SourceLocation LocStart = CE->getLParenLoc();
4812 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004813
4814 // Need to avoid trying to rewrite synthesized casts.
4815 if (LocStart.isInvalid())
4816 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004817 // Need to avoid trying to rewrite casts contained in macros.
4818 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4819 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004820
Steve Naroff54055232008-10-27 17:20:55 +00004821 const char *startBuf = SM->getCharacterData(LocStart);
4822 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004823 QualType QT = CE->getType();
4824 const Type* TypePtr = QT->getAs<Type>();
4825 if (isa<TypeOfExprType>(TypePtr)) {
4826 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4827 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4828 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004829 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004830 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004831 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004832 return;
4833 }
Steve Naroff54055232008-10-27 17:20:55 +00004834 // advance the location to startArgList.
4835 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004836
Steve Naroff54055232008-10-27 17:20:55 +00004837 while (*argPtr++ && (argPtr < endBuf)) {
4838 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004839 case '^':
4840 // Replace the '^' with '*'.
4841 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004842 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004843 break;
Steve Naroff54055232008-10-27 17:20:55 +00004844 }
4845 }
4846 return;
4847}
4848
4849void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4850 SourceLocation DeclLoc = FD->getLocation();
4851 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004852
Steve Naroff54055232008-10-27 17:20:55 +00004853 // We have 1 or more arguments that have closure pointers.
4854 const char *startBuf = SM->getCharacterData(DeclLoc);
4855 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004856
Steve Naroff54055232008-10-27 17:20:55 +00004857 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004858
Steve Naroff54055232008-10-27 17:20:55 +00004859 parenCount++;
4860 // advance the location to startArgList.
4861 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4862 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004863
Steve Naroff54055232008-10-27 17:20:55 +00004864 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004865
Steve Naroff54055232008-10-27 17:20:55 +00004866 while (*argPtr++ && parenCount) {
4867 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004868 case '^':
4869 // Replace the '^' with '*'.
4870 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004871 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004872 break;
4873 case '(':
4874 parenCount++;
4875 break;
4876 case ')':
4877 parenCount--;
4878 break;
Steve Naroff54055232008-10-27 17:20:55 +00004879 }
4880 }
4881 return;
4882}
4883
4884bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004885 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004886 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004887 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004888 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004889 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004890 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004891 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004892 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004893 }
4894 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004895 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004896 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004897 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004898 return true;
4899 }
4900 return false;
4901}
4902
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004903bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4904 const FunctionProtoType *FTP;
4905 const PointerType *PT = QT->getAs<PointerType>();
4906 if (PT) {
4907 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4908 } else {
4909 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4910 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4911 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4912 }
4913 if (FTP) {
4914 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004915 E = FTP->arg_type_end(); I != E; ++I) {
4916 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004917 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004918 if ((*I)->isObjCObjectPointerType() &&
4919 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4920 return true;
4921 }
4922
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004923 }
4924 return false;
4925}
4926
Ted Kremenek8189cde2009-02-07 01:47:29 +00004927void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4928 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004929 const char *argPtr = strchr(Name, '(');
4930 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004931
Steve Naroff54055232008-10-27 17:20:55 +00004932 LParen = argPtr; // output the start.
4933 argPtr++; // skip past the left paren.
4934 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004935
Steve Naroff54055232008-10-27 17:20:55 +00004936 while (*argPtr && parenCount) {
4937 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004938 case '(': parenCount++; break;
4939 case ')': parenCount--; break;
4940 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004941 }
4942 if (parenCount) argPtr++;
4943 }
4944 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4945 RParen = argPtr; // output the end
4946}
4947
4948void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4949 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4950 RewriteBlockPointerFunctionArgs(FD);
4951 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004952 }
Steve Naroff54055232008-10-27 17:20:55 +00004953 // Handle Variables and Typedefs.
4954 SourceLocation DeclLoc = ND->getLocation();
4955 QualType DeclT;
4956 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4957 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00004958 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00004959 DeclT = TDD->getUnderlyingType();
4960 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4961 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004962 else
Steve Naroff54055232008-10-27 17:20:55 +00004963 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004964
Steve Naroff54055232008-10-27 17:20:55 +00004965 const char *startBuf = SM->getCharacterData(DeclLoc);
4966 const char *endBuf = startBuf;
4967 // scan backward (from the decl location) for the end of the previous decl.
4968 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4969 startBuf--;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004970 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4971 std::string buf;
4972 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004973 // *startBuf != '^' if we are dealing with a pointer to function that
4974 // may take block argument types (which will be handled below).
4975 if (*startBuf == '^') {
4976 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004977 buf = '*';
4978 startBuf++;
4979 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004980 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004981 while (*startBuf != ')') {
4982 buf += *startBuf;
4983 startBuf++;
4984 OrigLength++;
4985 }
4986 buf += ')';
4987 OrigLength++;
4988
4989 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4990 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004991 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004992 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004993 DeclLoc = ND->getLocation();
4994 startBuf = SM->getCharacterData(DeclLoc);
4995 const char *argListBegin, *argListEnd;
4996 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4997 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004998 if (*argListBegin == '^')
4999 buf += '*';
5000 else if (*argListBegin == '<') {
5001 buf += "/*";
5002 buf += *argListBegin++;
5003 OrigLength++;;
5004 while (*argListBegin != '>') {
5005 buf += *argListBegin++;
5006 OrigLength++;
5007 }
5008 buf += *argListBegin;
5009 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005010 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005011 else
5012 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005013 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005014 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005015 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005016 buf += ')';
5017 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005018 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005019 ReplaceText(Start, OrigLength, buf);
5020
Steve Naroff54055232008-10-27 17:20:55 +00005021 return;
5022}
5023
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005024
5025/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5026/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5027/// struct Block_byref_id_object *src) {
5028/// _Block_object_assign (&_dest->object, _src->object,
5029/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5030/// [|BLOCK_FIELD_IS_WEAK]) // object
5031/// _Block_object_assign(&_dest->object, _src->object,
5032/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5033/// [|BLOCK_FIELD_IS_WEAK]) // block
5034/// }
5035/// And:
5036/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5037/// _Block_object_dispose(_src->object,
5038/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5039/// [|BLOCK_FIELD_IS_WEAK]) // object
5040/// _Block_object_dispose(_src->object,
5041/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5042/// [|BLOCK_FIELD_IS_WEAK]) // block
5043/// }
5044
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005045std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5046 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005047 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005048 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005049 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005050 CopyDestroyCache.insert(flag);
5051 S = "static void __Block_byref_id_object_copy_";
5052 S += utostr(flag);
5053 S += "(void *dst, void *src) {\n";
5054
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005055 // offset into the object pointer is computed as:
5056 // void * + void* + int + int + void* + void *
5057 unsigned IntSize =
5058 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5059 unsigned VoidPtrSize =
5060 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5061
Ken Dyck0c4e5d62011-04-30 16:08:27 +00005062 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005063 S += " _Block_object_assign((char*)dst + ";
5064 S += utostr(offset);
5065 S += ", *(void * *) ((char*)src + ";
5066 S += utostr(offset);
5067 S += "), ";
5068 S += utostr(flag);
5069 S += ");\n}\n";
5070
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005071 S += "static void __Block_byref_id_object_dispose_";
5072 S += utostr(flag);
5073 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005074 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5075 S += utostr(offset);
5076 S += "), ";
5077 S += utostr(flag);
5078 S += ");\n}\n";
5079 return S;
5080}
5081
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005082/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5083/// the declaration into:
5084/// struct __Block_byref_ND {
5085/// void *__isa; // NULL for everything except __weak pointers
5086/// struct __Block_byref_ND *__forwarding;
5087/// int32_t __flags;
5088/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005089/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5090/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005091/// typex ND;
5092/// };
5093///
5094/// It then replaces declaration of ND variable with:
5095/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5096/// __size=sizeof(struct __Block_byref_ND),
5097/// ND=initializer-if-any};
5098///
5099///
5100void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005101 // Insert declaration for the function in which block literal is
5102 // used.
5103 if (CurFunctionDeclToDeclareForBlock)
5104 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005105 int flag = 0;
5106 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005107 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005108 if (DeclLoc.isInvalid())
5109 // If type location is missing, it is because of missing type (a warning).
5110 // Use variable's location which is good for this case.
5111 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005112 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005113 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00005114 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005115 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005116 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005117 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005118 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005119 ByrefType += " {\n";
5120 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005121 RewriteByRefString(ByrefType, Name, ND);
5122 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005123 ByrefType += " int __flags;\n";
5124 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005125 // Add void *__Block_byref_id_object_copy;
5126 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005127 QualType Ty = ND->getType();
5128 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5129 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005130 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5131 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005132 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005133
5134 QualType T = Ty;
5135 (void)convertBlockPointerToFunctionPointer(T);
5136 T.getAsStringInternal(Name, Context->PrintingPolicy);
5137
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005138 ByrefType += " " + Name + ";\n";
5139 ByrefType += "};\n";
5140 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005141 SourceLocation FunLocStart;
5142 if (CurFunctionDef)
5143 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5144 else {
5145 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5146 FunLocStart = CurMethodDef->getLocStart();
5147 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005148 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005149 if (Ty.isObjCGCWeak()) {
5150 flag |= BLOCK_FIELD_IS_WEAK;
5151 isa = 1;
5152 }
5153
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005154 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005155 flag = BLOCK_BYREF_CALLER;
5156 QualType Ty = ND->getType();
5157 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5158 if (Ty->isBlockPointerType())
5159 flag |= BLOCK_FIELD_IS_BLOCK;
5160 else
5161 flag |= BLOCK_FIELD_IS_OBJECT;
5162 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005163 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005164 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005165 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005166
5167 // struct __Block_byref_ND ND =
5168 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5169 // initializer-if-any};
5170 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005171 unsigned flags = 0;
5172 if (HasCopyAndDispose)
5173 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005174 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005175 ByrefType.clear();
5176 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005177 std::string ForwardingCastType("(");
5178 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005179 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005180 ByrefType += " " + Name + " = {(void*)";
5181 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005182 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005183 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005184 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005185 ByrefType += "sizeof(";
5186 RewriteByRefString(ByrefType, Name, ND);
5187 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005188 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005189 ByrefType += ", __Block_byref_id_object_copy_";
5190 ByrefType += utostr(flag);
5191 ByrefType += ", __Block_byref_id_object_dispose_";
5192 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005193 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005194 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005195 unsigned nameSize = Name.size();
5196 // for block or function pointer declaration. Name is aleady
5197 // part of the declaration.
5198 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5199 nameSize = 1;
5200 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005201 }
5202 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005203 SourceLocation startLoc;
5204 Expr *E = ND->getInit();
5205 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5206 startLoc = ECE->getLParenLoc();
5207 else
5208 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00005209 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005210 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005211 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005212 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005213 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005214 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005215 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005216 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005217 ByrefType += "sizeof(";
5218 RewriteByRefString(ByrefType, Name, ND);
5219 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005220 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005221 ByrefType += "__Block_byref_id_object_copy_";
5222 ByrefType += utostr(flag);
5223 ByrefType += ", __Block_byref_id_object_dispose_";
5224 ByrefType += utostr(flag);
5225 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005226 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005227 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005228
5229 // Complete the newly synthesized compound expression by inserting a right
5230 // curly brace before the end of the declaration.
5231 // FIXME: This approach avoids rewriting the initializer expression. It
5232 // also assumes there is only one declarator. For example, the following
5233 // isn't currently supported by this routine (in general):
5234 //
5235 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5236 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005237 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5238 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005239 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5240 SourceLocation semiLoc =
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005241 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005242
Benjamin Kramerd999b372010-02-14 14:14:16 +00005243 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005244 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005245 return;
5246}
5247
Mike Stump1eb44332009-09-09 15:08:12 +00005248void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005249 // Add initializers for any closure decl refs.
5250 GetBlockDeclRefExprs(Exp->getBody());
5251 if (BlockDeclRefs.size()) {
5252 // Unique all "by copy" declarations.
5253 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005254 if (!BlockDeclRefs[i]->isByRef()) {
5255 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5256 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5257 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5258 }
5259 }
Steve Naroff54055232008-10-27 17:20:55 +00005260 // Unique all "by ref" declarations.
5261 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5262 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005263 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5264 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5265 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5266 }
Steve Naroff54055232008-10-27 17:20:55 +00005267 }
5268 // Find any imported blocks...they will need special attention.
5269 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005270 if (BlockDeclRefs[i]->isByRef() ||
5271 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005272 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005273 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005274 }
5275}
5276
Chris Lattner5f9e2722011-07-23 10:55:15 +00005277FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005278 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005279 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005280 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5281 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00005282 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005283}
5284
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005285Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005286 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005287 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00005288 Blocks.push_back(Exp);
5289
5290 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005291
5292 // Add inner imported variables now used in current block.
5293 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005294 if (!InnerBlockDeclRefs.empty()) {
5295 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5296 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5297 ValueDecl *VD = Exp->getDecl();
5298 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005299 // We need to save the copied-in variables in nested
5300 // blocks because it is needed at the end for some of the API generations.
5301 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005302 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5303 BlockDeclRefs.push_back(Exp);
5304 BlockByCopyDeclsPtrSet.insert(VD);
5305 BlockByCopyDecls.push_back(VD);
5306 }
5307 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5308 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5309 BlockDeclRefs.push_back(Exp);
5310 BlockByRefDeclsPtrSet.insert(VD);
5311 BlockByRefDecls.push_back(VD);
5312 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005313 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005314 // Find any imported blocks...they will need special attention.
5315 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5316 if (InnerBlockDeclRefs[i]->isByRef() ||
5317 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5318 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5319 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005320 }
5321 InnerDeclRefsCount.push_back(countOfInnerDecls);
5322
Steve Narofffa15fd92008-10-28 20:29:00 +00005323 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005324
Steve Narofffa15fd92008-10-28 20:29:00 +00005325 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005326 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005327 else if (CurMethodDef)
5328 BuildUniqueMethodName(FuncName, CurMethodDef);
5329 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005330 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005331
Steve Narofffa15fd92008-10-28 20:29:00 +00005332 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005333
Steve Narofffa15fd92008-10-28 20:29:00 +00005334 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5335 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005336
Steve Narofffa15fd92008-10-28 20:29:00 +00005337 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005338 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5339 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005340
5341 FunctionDecl *FD;
5342 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005343
Steve Narofffa15fd92008-10-28 20:29:00 +00005344 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005345 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005346 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5347 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005348
Chris Lattner5f9e2722011-07-23 10:55:15 +00005349 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005350
Steve Narofffdc03722008-10-29 21:23:59 +00005351 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005352 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005353 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005354 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005355 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005356 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005357 InitExprs.push_back(castExpr);
5358
Steve Naroff01aec112009-12-06 21:14:13 +00005359 // Initialize the block descriptor.
5360 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005361
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005362 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5363 SourceLocation(), SourceLocation(),
5364 &Context->Idents.get(DescData.c_str()),
5365 Context->VoidPtrTy, 0,
5366 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005367 UnaryOperator *DescRefExpr =
5368 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5369 Context->VoidPtrTy,
5370 VK_LValue,
5371 SourceLocation()),
5372 UO_AddrOf,
5373 Context->getPointerType(Context->VoidPtrTy),
5374 VK_RValue, OK_Ordinary,
5375 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005376 InitExprs.push_back(DescRefExpr);
5377
Steve Narofffa15fd92008-10-28 20:29:00 +00005378 // Add initializers for any closure decl refs.
5379 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005380 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005381 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005382 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005383 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005384 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005385 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005386 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005387 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5388 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005389 if (HasLocalVariableExternalStorage(*I)) {
5390 QualType QT = (*I)->getType();
5391 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005392 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5393 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005394 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005395 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005396 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005397 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5398 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005399 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005400 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005401 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005402 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005403 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5404 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005405 if (HasLocalVariableExternalStorage(*I)) {
5406 QualType QT = (*I)->getType();
5407 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005408 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5409 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005410 }
5411
Steve Narofffa15fd92008-10-28 20:29:00 +00005412 }
Mike Stump1eb44332009-09-09 15:08:12 +00005413 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005414 }
5415 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005416 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005417 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005418 ValueDecl *ND = (*I);
5419 std::string Name(ND->getNameAsString());
5420 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005421 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005422 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5423 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005424 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005425 SourceLocation(), SourceLocation(),
5426 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005427 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5428 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5429
Daniel Dunbar4087f272010-08-17 22:39:59 +00005430 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005431 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5432 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005433 bool isNestedCapturedVar = false;
5434 if (block)
5435 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5436 ce = block->capture_end(); ci != ce; ++ci) {
5437 const VarDecl *variable = ci->getVariable();
5438 if (variable == ND && ci->isNested()) {
5439 assert (ci->isByRef() &&
5440 "SynthBlockInitExpr - captured block variable is not byref");
5441 isNestedCapturedVar = true;
5442 break;
5443 }
5444 }
5445 // captured nested byref variable has its address passed. Do not take
5446 // its address again.
5447 if (!isNestedCapturedVar)
5448 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005449 Context->getPointerType(Exp->getType()),
5450 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005451 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005452 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005453 }
5454 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005455 if (ImportedBlockDecls.size()) {
5456 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5457 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005458 unsigned IntSize =
5459 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005460 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5461 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005462 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005463 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005464 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005465 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005466 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005467 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005468 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005469 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005470 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005471 BlockDeclRefs.clear();
5472 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005473 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005474 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005475 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005476 ImportedBlockDecls.clear();
5477 return NewRep;
5478}
5479
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005480bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5481 if (const ObjCForCollectionStmt * CS =
5482 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5483 return CS->getElement() == DS;
5484 return false;
5485}
5486
Steve Narofffa15fd92008-10-28 20:29:00 +00005487//===----------------------------------------------------------------------===//
5488// Function Body / Expression rewriting
5489//===----------------------------------------------------------------------===//
5490
Steve Naroffc77a6362008-12-04 16:24:46 +00005491// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5492// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5493// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5494// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5495// Since the rewriter isn't capable of rewriting rewritten code, it's important
5496// we get this right.
5497void RewriteObjC::CollectPropertySetters(Stmt *S) {
5498 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005499 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffc77a6362008-12-04 16:24:46 +00005500 if (*CI)
5501 CollectPropertySetters(*CI);
5502
5503 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5504 if (BinOp->isAssignmentOp()) {
John McCall12f78a62010-12-02 01:19:52 +00005505 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5506 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005507 }
5508 }
5509}
5510
Steve Narofffa15fd92008-10-28 20:29:00 +00005511Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005512 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005513 isa<DoStmt>(S) || isa<ForStmt>(S))
5514 Stmts.push_back(S);
5515 else if (isa<ObjCForCollectionStmt>(S)) {
5516 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005517 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005518 }
Mike Stump1eb44332009-09-09 15:08:12 +00005519
Steve Narofffa15fd92008-10-28 20:29:00 +00005520 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005521
Steve Narofffa15fd92008-10-28 20:29:00 +00005522 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005523 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00005524 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005525 Stmt *newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005526 Stmt *ChildStmt = (*CI);
5527 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(ChildStmt)) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005528 Expr *OldBase = IvarRefExpr->getBase();
5529 bool replaced = false;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005530 newStmt = RewriteObjCNestedIvarRefExpr(ChildStmt, replaced);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005531 if (replaced) {
5532 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5533 ReplaceStmt(OldBase, IRE->getBase());
5534 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005535 ReplaceStmt(ChildStmt, newStmt);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005536 }
5537 }
5538 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005539 newStmt = RewriteFunctionBodyOrGlobalInitializer(ChildStmt);
5540 if (newStmt) {
5541 if (Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(ChildStmt))
5542 if (PropSetters[PropOrImplicitRefExpr] == S) {
5543 S = newStmt;
5544 newStmt = 0;
5545 }
5546 if (newStmt)
5547 *CI = newStmt;
5548 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005549 // If dealing with an assignment with LHS being a property reference
5550 // expression, the entire assignment tree is rewritten into a property
5551 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5552 // RHS again.
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005553 if (Expr *Exp = dyn_cast<Expr>(ChildStmt))
John McCall12f78a62010-12-02 01:19:52 +00005554 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005555 if (PropSetters[Exp]) {
5556 ++CI;
5557 continue;
5558 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005559 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005560 }
Mike Stump1eb44332009-09-09 15:08:12 +00005561
Steve Narofffa15fd92008-10-28 20:29:00 +00005562 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005563 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005564 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5565 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005566 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005567 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005568 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005569 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005570 Stmt *SaveCurrentBody = CurrentBody;
5571 CurrentBody = BE->getBody();
Fariborz Jahanian36178092011-04-08 23:48:29 +00005572 CollectPropertySetters(CurrentBody);
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005573 PropParentMap = 0;
Steve Narofffa15fd92008-10-28 20:29:00 +00005574 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005575 CurrentBody = SaveCurrentBody;
5576 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005577 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005578 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005579 std::string Str = Rewrite.ConvertToString(BE->getBody());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005580 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005581
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005582 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5583
Steve Narofffa15fd92008-10-28 20:29:00 +00005584 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005585 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005586 return blockTranscribed;
5587 }
5588 // Handle specific things.
5589 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5590 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005591
John McCall12f78a62010-12-02 01:19:52 +00005592 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005593 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5594 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5595
5596 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005597 if (BinOp) {
5598 // Because the rewriter doesn't allow us to rewrite rewritten code,
5599 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005600 DisableReplaceStmt = true;
5601 // Save the source range. Even if we disable the replacement, the
5602 // rewritten node will have been inserted into the tree. If the synthesized
5603 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005604 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005605 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5606 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005607 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005608 // Need to rewrite the ivar access expression if need be.
5609 if (isa<ObjCIvarRefExpr>(newStmt)) {
5610 bool replaced = false;
5611 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5612 }
5613
Steve Naroffb619d952008-12-09 12:56:34 +00005614 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005615 //
5616 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5617 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5618 // to see the original expression). Consider this example:
5619 //
5620 // Foo *obj1, *obj2;
5621 //
5622 // obj1.i = [obj2 rrrr];
5623 //
5624 // 'BinOp' for the previous expression looks like:
5625 //
5626 // (BinaryOperator 0x231ccf0 'int' '='
5627 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5628 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5629 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5630 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5631 //
5632 // 'newStmt' represents the rewritten message expression. For example:
5633 //
5634 // (CallExpr 0x231d300 'id':'struct objc_object *'
5635 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5636 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5637 // (CStyleCastExpr 0x231d220 'void *'
5638 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5639 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005640 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005641 // can be used as the setter argument. ReplaceStmt() will still 'see'
5642 // the original RHS (since we haven't altered BinOp).
5643 //
Mike Stump1eb44332009-09-09 15:08:12 +00005644 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005645 // node. As a result, we now leak the original AST nodes.
5646 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005647 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005648 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005649 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005650 }
5651 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005652
Steve Narofffa15fd92008-10-28 20:29:00 +00005653 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5654 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005655
Steve Narofffa15fd92008-10-28 20:29:00 +00005656 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5657 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005658
Steve Narofffa15fd92008-10-28 20:29:00 +00005659 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005660#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005661 // Before we rewrite it, put the original message expression in a comment.
5662 SourceLocation startLoc = MessExpr->getLocStart();
5663 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005664
Steve Narofffa15fd92008-10-28 20:29:00 +00005665 const char *startBuf = SM->getCharacterData(startLoc);
5666 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005667
Steve Narofffa15fd92008-10-28 20:29:00 +00005668 std::string messString;
5669 messString += "// ";
5670 messString.append(startBuf, endBuf-startBuf+1);
5671 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005672
5673 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005674 // InsertText(clang::SourceLocation, char const*, unsigned int).
5675 // InsertText(startLoc, messString.c_str(), messString.size());
5676 // Tried this, but it didn't work either...
5677 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005678#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005679 return RewriteMessageExpr(MessExpr);
5680 }
Mike Stump1eb44332009-09-09 15:08:12 +00005681
Steve Narofffa15fd92008-10-28 20:29:00 +00005682 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5683 return RewriteObjCTryStmt(StmtTry);
5684
5685 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5686 return RewriteObjCSynchronizedStmt(StmtTry);
5687
5688 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5689 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005690
Steve Narofffa15fd92008-10-28 20:29:00 +00005691 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5692 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005693
5694 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005695 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005696 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005697 OrigStmtRange.getEnd());
5698 if (BreakStmt *StmtBreakStmt =
5699 dyn_cast<BreakStmt>(S))
5700 return RewriteBreakStmt(StmtBreakStmt);
5701 if (ContinueStmt *StmtContinueStmt =
5702 dyn_cast<ContinueStmt>(S))
5703 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005704
5705 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005706 // and cast exprs.
5707 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5708 // FIXME: What we're doing here is modifying the type-specifier that
5709 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005710 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005711 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5712 // the context of an ObjCForCollectionStmt. For example:
5713 // NSArray *someArray;
5714 // for (id <FooProtocol> index in someArray) ;
5715 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5716 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005717 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005718 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005719
Steve Narofffa15fd92008-10-28 20:29:00 +00005720 // Blocks rewrite rules.
5721 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5722 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005723 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005724 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005725 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005726 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005727 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005728 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005729 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005730 if (VD->hasAttr<BlocksAttr>()) {
5731 static unsigned uniqueByrefDeclCount = 0;
5732 assert(!BlockByRefDeclNo.count(ND) &&
5733 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5734 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005735 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005736 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005737 else
5738 RewriteTypeOfDecl(VD);
5739 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005740 }
Richard Smith162e1c12011-04-15 14:24:37 +00005741 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005742 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005743 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005744 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005745 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5746 }
5747 }
5748 }
Mike Stump1eb44332009-09-09 15:08:12 +00005749
Steve Narofffa15fd92008-10-28 20:29:00 +00005750 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5751 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005752
5753 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005754 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5755 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005756 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5757 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005758 && "Statement stack mismatch");
5759 Stmts.pop_back();
5760 }
5761 // Handle blocks rewriting.
5762 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5763 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005764 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005765 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005766 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5767 ValueDecl *VD = DRE->getDecl();
5768 if (VD->hasAttr<BlocksAttr>())
5769 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005770 if (HasLocalVariableExternalStorage(VD))
5771 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005772 }
5773
Steve Narofffa15fd92008-10-28 20:29:00 +00005774 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005775 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005776 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005777 ReplaceStmt(S, BlockCall);
5778 return BlockCall;
5779 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005780 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005781 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005782 RewriteCastExpr(CE);
5783 }
5784#if 0
5785 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005786 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5787 ICE->getSubExpr(),
5788 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005789 // Get the new text.
5790 std::string SStr;
5791 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005792 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005793 const std::string &Str = Buf.str();
5794
5795 printf("CAST = %s\n", &Str[0]);
5796 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5797 delete S;
5798 return Replacement;
5799 }
5800#endif
5801 // Return this stmt unmodified.
5802 return S;
5803}
5804
Steve Naroff3d7e7862009-12-05 15:55:59 +00005805void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5806 for (RecordDecl::field_iterator i = RD->field_begin(),
5807 e = RD->field_end(); i != e; ++i) {
5808 FieldDecl *FD = *i;
5809 if (isTopLevelBlockPointerType(FD->getType()))
5810 RewriteBlockPointerDecl(FD);
5811 if (FD->getType()->isObjCQualifiedIdType() ||
5812 FD->getType()->isObjCQualifiedInterfaceType())
5813 RewriteObjCQualifiedInterfaceTypes(FD);
5814 }
5815}
5816
Steve Narofffa15fd92008-10-28 20:29:00 +00005817/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5818/// main file of the input.
5819void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5820 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005821 if (FD->isOverloadedOperator())
5822 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005823
Steve Narofffa15fd92008-10-28 20:29:00 +00005824 // Since function prototypes don't have ParmDecl's, we check the function
5825 // prototype. This enables us to rewrite function declarations and
5826 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005827 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005828
Sebastian Redld3a413d2009-04-26 20:35:05 +00005829 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005830 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005831 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005832 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005833 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005834 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005835 Body =
5836 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5837 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005838 CurrentBody = 0;
5839 if (PropParentMap) {
5840 delete PropParentMap;
5841 PropParentMap = 0;
5842 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005843 // This synthesizes and inserts the block "impl" struct, invoke function,
5844 // and any copy/dispose helper functions.
5845 InsertBlockLiteralsWithinFunction(FD);
5846 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005847 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005848 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005849 return;
5850 }
5851 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005852 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005853 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005854 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005855 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005856 Body =
5857 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5858 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005859 CurrentBody = 0;
5860 if (PropParentMap) {
5861 delete PropParentMap;
5862 PropParentMap = 0;
5863 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005864 InsertBlockLiteralsWithinMethod(MD);
5865 CurMethodDef = 0;
5866 }
5867 }
5868 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5869 ClassImplementation.push_back(CI);
5870 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5871 CategoryImplementation.push_back(CI);
5872 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5873 RewriteForwardClassDecl(CD);
5874 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5875 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005876 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005877 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005878 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005879 CheckFunctionPointerDecl(VD->getType(), VD);
5880 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005881 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005882 RewriteCastExpr(CE);
5883 }
5884 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005885 } else if (VD->getType()->isRecordType()) {
5886 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5887 if (RD->isDefinition())
5888 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005889 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005890 if (VD->getInit()) {
5891 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005892 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005893 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005894 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005895 CurrentBody = 0;
5896 if (PropParentMap) {
5897 delete PropParentMap;
5898 PropParentMap = 0;
5899 }
Mike Stump1eb44332009-09-09 15:08:12 +00005900 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005901 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005902 GlobalVarDecl = 0;
5903
5904 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005905 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005906 RewriteCastExpr(CE);
5907 }
5908 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005909 return;
5910 }
Richard Smith162e1c12011-04-15 14:24:37 +00005911 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005912 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005913 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005914 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005915 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5916 return;
5917 }
5918 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005919 if (RD->isDefinition())
5920 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005921 return;
5922 }
5923 // Nothing yet.
5924}
5925
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005926void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005927 if (Diags.hasErrorOccurred())
5928 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005929
Steve Narofffa15fd92008-10-28 20:29:00 +00005930 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005931
Steve Naroff621edce2009-04-29 16:37:50 +00005932 // Here's a great place to add any extra declarations that may be needed.
5933 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005934 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005935 E = ProtocolExprDecls.end(); I != E; ++I)
5936 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5937
Benjamin Kramerd999b372010-02-14 14:14:16 +00005938 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005939 if (ClassImplementation.size() || CategoryImplementation.size())
5940 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005941
Steve Narofffa15fd92008-10-28 20:29:00 +00005942 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5943 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005944 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005945 Rewrite.getRewriteBufferFor(MainFileID)) {
5946 //printf("Changed:\n");
5947 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5948 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005949 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005950 }
Steve Narofface66252008-11-13 20:07:04 +00005951
Steve Naroff621edce2009-04-29 16:37:50 +00005952 if (ClassImplementation.size() || CategoryImplementation.size() ||
5953 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005954 // Rewrite Objective-c meta data*
5955 std::string ResultStr;
5956 SynthesizeMetaDataIntoBuffer(ResultStr);
5957 // Emit metadata.
5958 *OutFile << ResultStr;
5959 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005960 OutFile->flush();
5961}