blob: a32b434a95c9cc8e284cc11b3ffcbfcec8d36c8b [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 {
36 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
37 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 */
41 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
42 helpers */
43 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
44 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
Ted Kremeneka526c5c2008-01-07 19:49:32 +000070 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 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;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000076 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::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;
Eli Friedman66d6f042009-05-18 22:20:00 +0000116 llvm::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.
124 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000125 llvm::SmallVector<int, 32> InnerDeclRefsCount;
126 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
127
Steve Naroff54055232008-10-27 17:20:55 +0000128 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Steve Naroff54055232008-10-27 17:20:55 +0000130 // Block related declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000131 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 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);
Eli Friedman66d6f042009-05-18 22:20:00 +0000169 RewriteObjC(std::string inFile, llvm::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
Benjamin Kramerd999b372010-02-14 14:14:16 +0000222 void InsertText(SourceLocation Loc, llvm::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,
Benjamin Kramerd999b372010-02-14 14:14:16 +0000233 llvm::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,
255 ValueDecl *VD);
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);
Mike Stump1eb44332009-09-09 15:08:12 +0000301 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000302 Expr **args, unsigned nargs,
303 SourceLocation StartLoc=SourceLocation(),
304 SourceLocation EndLoc=SourceLocation());
305 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
306 SourceLocation StartLoc=SourceLocation(),
307 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000308 Stmt *RewriteBreakStmt(BreakStmt *S);
309 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000310 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Steve Naroff09b266e2007-10-30 23:14:51 +0000312 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000313 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000314 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000315 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000316 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000317 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000318 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000319 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000320 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000321 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Chris Lattnerf04da132007-10-24 17:06:59 +0000323 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000324 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000325 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000327 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000328 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Douglas Gregor653f1b12009-04-23 01:02:12 +0000330 template<typename MethodIterator>
331 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
332 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000333 bool IsInstanceMethod,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000334 llvm::StringRef prefix,
335 llvm::StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +0000336 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Steve Naroff621edce2009-04-29 16:37:50 +0000338 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000339 llvm::StringRef prefix,
340 llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000341 std::string &Result);
342 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000343 llvm::StringRef prefix,
344 llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000345 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000346 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000347 std::string &Result);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000348 void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000349 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000350 void RewriteImplementations();
351 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Steve Naroff54055232008-10-27 17:20:55 +0000353 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000354 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000355 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Steve Naroff54055232008-10-27 17:20:55 +0000357 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
358 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000359
360 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000361 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000362 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000363 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000364 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000365 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000366 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000367
368 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000369 llvm::StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000370 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000371 llvm::StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000372 std::string SynthesizeBlockImpl(BlockExpr *CE,
373 std::string Tag, std::string Desc);
374 std::string SynthesizeBlockDescriptor(std::string DescTag,
375 std::string ImplTag,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000376 int i, llvm::StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000377 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000378 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000379 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000380 llvm::StringRef FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000381 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Steve Naroff54055232008-10-27 17:20:55 +0000383 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000384 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000385 void GetInnerBlockDeclRefExprs(Stmt *S,
386 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000387 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Steve Naroff54055232008-10-27 17:20:55 +0000389 // We avoid calling Type::isBlockPointerType(), since it operates on the
390 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000391 bool isTopLevelBlockPointerType(QualType T) {
392 return isa<BlockPointerType>(T);
393 }
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000395 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
396 /// to a function pointer type and upon success, returns true; false
397 /// otherwise.
398 bool convertBlockPointerToFunctionPointer(QualType &T) {
399 if (isTopLevelBlockPointerType(T)) {
400 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
401 T = Context->getPointerType(BPT->getPointeeType());
402 return true;
403 }
404 return false;
405 }
406
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000407 void convertToUnqualifiedObjCType(QualType &T) {
408 if (T->isObjCQualifiedIdType())
409 T = Context->getObjCIdType();
410 else if (T->isObjCQualifiedClassType())
411 T = Context->getObjCClassType();
412 else if (T->isObjCObjectPointerType() &&
413 T->getPointeeType()->isObjCQualifiedInterfaceType())
414 T = Context->getObjCIdType();
415 }
416
Steve Naroff54055232008-10-27 17:20:55 +0000417 // FIXME: This predicate seems like it would be useful to add to ASTContext.
418 bool isObjCType(QualType T) {
419 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
420 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Steve Naroff54055232008-10-27 17:20:55 +0000422 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Steve Naroff54055232008-10-27 17:20:55 +0000424 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
425 OCT == Context->getCanonicalType(Context->getObjCClassType()))
426 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Ted Kremenek6217b802009-07-29 21:53:49 +0000428 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000429 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000430 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000431 return true;
432 }
433 return false;
434 }
435 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000436 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000437 void GetExtentOfArgList(const char *Name, const char *&LParen,
438 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000439 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Daniel Dunbar4087f272010-08-17 22:39:59 +0000441 FunctionDecl *SynthBlockInitFunctionDecl(llvm::StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000442 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
443 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Steve Naroff621edce2009-04-29 16:37:50 +0000445 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000446 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000447 if (From[i] == '"')
448 To += "\\\"";
449 else
450 To += From[i];
451 }
452 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000453 };
John McCall9d125032010-01-15 18:39:57 +0000454
455 // Helper function: create a CStyleCastExpr with trivial type source info.
456 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000457 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000458 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf871d0c2010-08-07 06:22:56 +0000459 return CStyleCastExpr::Create(*Ctx, Ty, Kind, E, 0, TInfo,
460 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000461 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000462}
463
Mike Stump1eb44332009-09-09 15:08:12 +0000464void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
465 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000466 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000467 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000468 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000469 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000470 // All the args are checked/rewritten. Don't call twice!
471 RewriteBlockPointerDecl(D);
472 break;
473 }
474 }
475}
476
477void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000478 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000479 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000480 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000481}
482
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000483static bool IsHeaderFile(const std::string &Filename) {
484 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000486 if (DotPos == std::string::npos) {
487 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000488 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000489 }
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000491 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
492 // C header: .h
493 // C++ header: .hh or .H;
494 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000495}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000496
Eli Friedman66d6f042009-05-18 22:20:00 +0000497RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000498 Diagnostic &D, const LangOptions &LOpts,
499 bool silenceMacroWarn)
500 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
501 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000502 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000503 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000504 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000505 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000506 "rewriter doesn't support user-specified control flow semantics "
507 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000508}
509
Eli Friedmanbce831b2009-05-18 22:29:17 +0000510ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
511 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000512 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000513 const LangOptions &LOpts,
514 bool SilenceRewriteMacroWarning) {
515 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000516}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000517
Steve Naroffb29b4272008-04-14 22:03:09 +0000518void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000519 Context = &context;
520 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000521 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000522 MsgSendFunctionDecl = 0;
523 MsgSendSuperFunctionDecl = 0;
524 MsgSendStretFunctionDecl = 0;
525 MsgSendSuperStretFunctionDecl = 0;
526 MsgSendFpretFunctionDecl = 0;
527 GetClassFunctionDecl = 0;
528 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000529 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000530 SelGetUidFunctionDecl = 0;
531 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000532 ConstantStringClassReference = 0;
533 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000534 CurMethodDef = 0;
535 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000536 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000537 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000538 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000539 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000540 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000541 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000542 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000543 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000544 PropParentMap = 0;
545 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000546 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000547 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000549 // Get the ID and start/end of the main file.
550 MainFileID = SM->getMainFileID();
551 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
552 MainFileStart = MainBuf->getBufferStart();
553 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Chris Lattner2c78b872009-04-14 23:22:57 +0000555 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000557 // declaring objc_selector outside the parameter list removes a silly
558 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000559 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000560 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000561 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000562 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000563 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000564 if (LangOpts.Microsoft) {
565 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000566 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
567 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000568 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000569 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000570 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000571 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
572 Preamble += "typedef struct objc_object Protocol;\n";
573 Preamble += "#define _REWRITER_typedef_Protocol\n";
574 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000575 if (LangOpts.Microsoft) {
576 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
577 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
578 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000579 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000580 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000581 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000582 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000583 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000584 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000585 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000586 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000587 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000588 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000589 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000590 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000591 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000592 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
593 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000594 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000595 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000596 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
597 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
598 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
599 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
600 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000601 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000602 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000603 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
604 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
605 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000606 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
607 Preamble += "struct __objcFastEnumerationState {\n\t";
608 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000609 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000610 Preamble += "unsigned long *mutationsPtr;\n\t";
611 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000612 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000613 Preamble += "#define __FASTENUMERATIONSTATE\n";
614 Preamble += "#endif\n";
615 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
616 Preamble += "struct __NSConstantStringImpl {\n";
617 Preamble += " int *isa;\n";
618 Preamble += " int flags;\n";
619 Preamble += " char *str;\n";
620 Preamble += " long length;\n";
621 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000622 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
623 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
624 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000625 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000626 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000627 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
628 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000629 // Blocks preamble.
630 Preamble += "#ifndef BLOCK_IMPL\n";
631 Preamble += "#define BLOCK_IMPL\n";
632 Preamble += "struct __block_impl {\n";
633 Preamble += " void *isa;\n";
634 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000635 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000636 Preamble += " void *FuncPtr;\n";
637 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000638 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000639 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000640 Preamble += "extern \"C\" __declspec(dllexport) "
641 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000642 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
643 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
644 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
645 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000646 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
647 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000648 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
649 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
650 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000651 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000652 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000653 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
654 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000655 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000656 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000657 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000658 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000659 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000660 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000661 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000662 Preamble += "#define __weak\n";
663 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000664 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
665 // as this avoids warning in any 64bit/32bit compilation model.
666 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000667}
668
669
Chris Lattnerf04da132007-10-24 17:06:59 +0000670//===----------------------------------------------------------------------===//
671// Top Level Driver Code
672//===----------------------------------------------------------------------===//
673
Chris Lattner682bf922009-03-29 16:50:03 +0000674void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000675 if (Diags.hasErrorOccurred())
676 return;
677
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000678 // Two cases: either the decl could be in the main file, or it could be in a
679 // #included file. If the former, rewrite it now. If the later, check to see
680 // if we rewrote the #include/#import.
681 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000682 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000684 // If this is for a builtin, ignore it.
685 if (Loc.isInvalid()) return;
686
Steve Naroffebf2b562007-10-23 23:50:29 +0000687 // Look for built-in declarations that we need to refer during the rewrite.
688 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000689 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000690 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000691 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000692 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000693 ConstantStringClassReference = FVD;
694 return;
695 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000696 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000697 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000698 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000699 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000700 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000701 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000702 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000703 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000704 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000705 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
706 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000707 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
708 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000709 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000710 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000711 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000712 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000713 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000714 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000715}
716
Chris Lattnerf04da132007-10-24 17:06:59 +0000717//===----------------------------------------------------------------------===//
718// Syntactic (non-AST) Rewriting Code
719//===----------------------------------------------------------------------===//
720
Steve Naroffb29b4272008-04-14 22:03:09 +0000721void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000722 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000723 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
724 const char *MainBufStart = MainBuf.begin();
725 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000726 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000728 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000729 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
730 if (*BufPtr == '#') {
731 if (++BufPtr == MainBufEnd)
732 return;
733 while (*BufPtr == ' ' || *BufPtr == '\t')
734 if (++BufPtr == MainBufEnd)
735 return;
736 if (!strncmp(BufPtr, "import", ImportLen)) {
737 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000738 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000739 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000740 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000741 BufPtr += ImportLen;
742 }
743 }
744 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000745}
746
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000747static std::string getIvarAccessString(ObjCIvarDecl *OID) {
748 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000749 std::string S;
750 S = "((struct ";
751 S += ClassDecl->getIdentifier()->getName();
752 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000753 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000754 return S;
755}
756
Steve Naroffa0876e82008-12-02 17:36:43 +0000757void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
758 ObjCImplementationDecl *IMD,
759 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000760 static bool objcGetPropertyDefined = false;
761 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000762 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000763 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000764 const char *startBuf = SM->getCharacterData(startLoc);
765 assert((*startBuf == '@') && "bogus @synthesize location");
766 const char *semiBuf = strchr(startBuf, ';');
767 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000768 SourceLocation onePastSemiLoc =
769 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000770
771 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
772 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Steve Naroffeb0646c2008-12-02 15:48:25 +0000774 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000775 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000776 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000778 if (!OID)
779 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000780 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000781 if (!PD->getGetterMethodDecl()->isDefined()) {
782 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
783 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
784 ObjCPropertyDecl::OBJC_PR_copy));
785 std::string Getr;
786 if (GenGetProperty && !objcGetPropertyDefined) {
787 objcGetPropertyDefined = true;
788 // FIXME. Is this attribute correct in all cases?
789 Getr = "\nextern \"C\" __declspec(dllimport) "
790 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000791 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000792 RewriteObjCMethodDecl(OID->getContainingInterface(),
793 PD->getGetterMethodDecl(), Getr);
794 Getr += "{ ";
795 // Synthesize an explicit cast to gain access to the ivar.
796 // See objc-act.c:objc_synthesize_new_getter() for details.
797 if (GenGetProperty) {
798 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
799 Getr += "typedef ";
800 const FunctionType *FPRetType = 0;
801 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
802 FPRetType);
803 Getr += " _TYPE";
804 if (FPRetType) {
805 Getr += ")"; // close the precedence "scope" for "*".
806
807 // Now, emit the argument types (if any).
808 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
809 Getr += "(";
810 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
811 if (i) Getr += ", ";
812 std::string ParamStr = FT->getArgType(i).getAsString(
813 Context->PrintingPolicy);
814 Getr += ParamStr;
815 }
816 if (FT->isVariadic()) {
817 if (FT->getNumArgs()) Getr += ", ";
818 Getr += "...";
819 }
820 Getr += ")";
821 } else
822 Getr += "()";
823 }
824 Getr += ";\n";
825 Getr += "return (_TYPE)";
826 Getr += "objc_getProperty(self, _cmd, ";
827 SynthesizeIvarOffsetComputation(OID, Getr);
828 Getr += ", 1)";
829 }
830 else
831 Getr += "return " + getIvarAccessString(OID);
832 Getr += "; }";
833 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000834 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000835
836 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000837 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Steve Naroffeb0646c2008-12-02 15:48:25 +0000839 // Generate the 'setter' function.
840 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000841 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
842 ObjCPropertyDecl::OBJC_PR_copy);
843 if (GenSetProperty && !objcSetPropertyDefined) {
844 objcSetPropertyDefined = true;
845 // FIXME. Is this attribute correct in all cases?
846 Setr = "\nextern \"C\" __declspec(dllimport) "
847 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
848 }
849
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000850 RewriteObjCMethodDecl(OID->getContainingInterface(),
851 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000852 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000853 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000854 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000855 if (GenSetProperty) {
856 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000857 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000858 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000859 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000860 Setr += ", ";
861 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
862 Setr += "0, ";
863 else
864 Setr += "1, ";
865 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
866 Setr += "1)";
867 else
868 Setr += "0)";
869 }
870 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000871 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000872 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000873 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000874 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000875 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000876}
Chris Lattner8a12c272007-10-11 18:38:32 +0000877
Steve Naroffb29b4272008-04-14 22:03:09 +0000878void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000879 // Get the start location and compute the semi location.
880 SourceLocation startLoc = ClassDecl->getLocation();
881 const char *startBuf = SM->getCharacterData(startLoc);
882 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Chris Lattnerf04da132007-10-24 17:06:59 +0000884 // Translate to typedef's that forward reference structs with the same name
885 // as the class. As a convenience, we include the original declaration
886 // as a comment.
887 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000888 typedefString += "// @class ";
889 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
890 I != E; ++I) {
891 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
892 typedefString += ForwardDecl->getNameAsString();
893 if (I+1 != E)
894 typedefString += ", ";
895 else
896 typedefString += ";\n";
897 }
898
Chris Lattner67956052009-02-20 18:04:31 +0000899 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
900 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000901 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000902 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000903 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000904 typedefString += "\n";
905 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000906 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000907 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000908 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000909 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000910 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000911 }
Mike Stump1eb44332009-09-09 15:08:12 +0000912
Steve Naroff934f2762007-10-24 22:48:43 +0000913 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000914 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000915}
916
Steve Naroffb29b4272008-04-14 22:03:09 +0000917void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000918 // When method is a synthesized one, such as a getter/setter there is
919 // nothing to rewrite.
920 if (Method->isSynthesized())
921 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000922 SourceLocation LocStart = Method->getLocStart();
923 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000924
Chris Lattner30fc9332009-02-04 01:06:56 +0000925 if (SM->getInstantiationLineNumber(LocEnd) >
926 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000927 InsertText(LocStart, "#if 0\n");
928 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000929 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000930 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000931 }
932}
933
Mike Stump1eb44332009-09-09 15:08:12 +0000934void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000935 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Benjamin Kramerd999b372010-02-14 14:14:16 +0000937 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000938 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000939}
940
Steve Naroffb29b4272008-04-14 22:03:09 +0000941void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000942 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Steve Naroff423cb562007-10-30 13:30:57 +0000944 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000945 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000947 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
948 E = CatDecl->prop_end(); I != E; ++I)
949 RewriteProperty(*I);
950
Mike Stump1eb44332009-09-09 15:08:12 +0000951 for (ObjCCategoryDecl::instmeth_iterator
952 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000953 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000954 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000955 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000956 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000957 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000958 RewriteMethodDeclaration(*I);
959
Steve Naroff423cb562007-10-30 13:30:57 +0000960 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000961 ReplaceText(CatDecl->getAtEndRange().getBegin(),
962 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000963}
964
Steve Naroffb29b4272008-04-14 22:03:09 +0000965void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000966 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Steve Naroff752d6ef2007-10-30 16:42:30 +0000968 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000969 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000970
971 for (ObjCProtocolDecl::instmeth_iterator
972 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000973 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000974 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000975 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000976 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000977 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000978 RewriteMethodDeclaration(*I);
979
Fariborz Jahanian07acdf42010-09-24 18:36:58 +0000980 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
981 E = PDecl->prop_end(); I != E; ++I)
982 RewriteProperty(*I);
983
Steve Naroff752d6ef2007-10-30 16:42:30 +0000984 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000985 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000986 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000987
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000988 // Must comment out @optional/@required
989 const char *startBuf = SM->getCharacterData(LocStart);
990 const char *endBuf = SM->getCharacterData(LocEnd);
991 for (const char *p = startBuf; p < endBuf; p++) {
992 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000993 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000994 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000996 }
997 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000998 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000999 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001001 }
1002 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001003}
1004
Steve Naroffb29b4272008-04-14 22:03:09 +00001005void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001006 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001007 if (LocStart.isInvalid())
1008 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001009 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001010 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001011}
1012
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001013void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1014 const FunctionType *&FPRetType) {
1015 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001016 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001017 else if (T->isFunctionPointerType() ||
1018 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001019 // needs special handling, since pointer-to-functions have special
1020 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001021 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001022 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001023 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001024 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001025 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001026 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001027 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001028 ResultStr += FPRetType->getResultType().getAsString(
1029 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001030 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001031 }
1032 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001033 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001034}
1035
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001036void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1037 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001038 std::string &ResultStr) {
1039 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1040 const FunctionType *FPRetType = 0;
1041 ResultStr += "\nstatic ";
1042 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001043 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001045 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001046 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001048 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001049 NameStr += "_I_";
1050 else
1051 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001053 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001054 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001055
1056 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001057 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001058 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001059 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001060 }
Mike Stump1eb44332009-09-09 15:08:12 +00001061 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001062 {
1063 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001064 int len = selString.size();
1065 for (int i = 0; i < len; i++)
1066 if (selString[i] == ':')
1067 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001068 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001069 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001070 // Remember this name for metadata emission
1071 MethodInternalNames[OMD] = NameStr;
1072 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001074 // Rewrite arguments
1075 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001076
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001077 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001078 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001079 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001080 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001081 if (!LangOpts.Microsoft) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001082 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001083 ResultStr += "struct ";
1084 }
1085 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001086 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001087 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001088 }
1089 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001090 ResultStr += Context->getObjCClassType().getAsString(
1091 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001093 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001094 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001095 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001097 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001098 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1099 E = OMD->param_end(); PI != E; ++PI) {
1100 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001101 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001102 if (PDecl->getType()->isObjCQualifiedIdType()) {
1103 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001104 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001105 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001106 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001107 QualType QT = PDecl->getType();
1108 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1109 if (convertBlockPointerToFunctionPointer(QT))
1110 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1111 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001112 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001113 ResultStr += Name;
1114 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001115 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001116 if (OMD->isVariadic())
1117 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001118 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Steve Naroff76e429d2008-07-16 14:40:40 +00001120 if (FPRetType) {
1121 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Steve Naroff76e429d2008-07-16 14:40:40 +00001123 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001124 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001125 ResultStr += "(";
1126 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1127 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001128 std::string ParamStr = FT->getArgType(i).getAsString(
1129 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001130 ResultStr += ParamStr;
1131 }
1132 if (FT->isVariadic()) {
1133 if (FT->getNumArgs()) ResultStr += ", ";
1134 ResultStr += "...";
1135 }
1136 ResultStr += ")";
1137 } else {
1138 ResultStr += "()";
1139 }
1140 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001141}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001142void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001143 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1144 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001146 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001148 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001149 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1150 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001151 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001152 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001153 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001154 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001155 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001156 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001157
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001158 const char *startBuf = SM->getCharacterData(LocStart);
1159 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001160 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001161 }
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001163 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001164 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1165 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001166 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001167 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001168 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001169 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001170 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001171 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001173 const char *startBuf = SM->getCharacterData(LocStart);
1174 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001175 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001176 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001177 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001178 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001179 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001180 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001181 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001182 }
1183
Benjamin Kramerd999b372010-02-14 14:14:16 +00001184 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001185}
1186
Steve Naroffb29b4272008-04-14 22:03:09 +00001187void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001188 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001189 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001190 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001191 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001192 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001193 ResultStr += "\n";
1194 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001195 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001196 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001197 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001198 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001199 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001200 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001201 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001202 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001203 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001204
1205 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001206 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001207 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001208 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001209 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001210 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001211 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001212 for (ObjCInterfaceDecl::classmeth_iterator
1213 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001214 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001215 RewriteMethodDeclaration(*I);
1216
Steve Naroff2feac5e2007-10-30 03:43:13 +00001217 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001218 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1219 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001220}
1221
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001222Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001223 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001224 ObjCMethodDecl *OMD = 0;
1225 QualType Ty;
1226 Selector Sel;
Duncan Sands54bd4572010-10-20 08:21:16 +00001227 Stmt *Receiver = 0;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001228 bool Super = false;
1229 QualType SuperTy;
1230 SourceLocation SuperLocation;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001231 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001232 // This allows us to reuse all the fun and games in SynthMessageExpr().
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001233 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
1234 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1235 OMD = PDecl->getSetterMethodDecl();
1236 Ty = PDecl->getType();
1237 Sel = PDecl->getSetterName();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001238 Super = PropRefExpr->isSuperReceiver();
1239 if (!Super)
1240 Receiver = PropRefExpr->getBase();
1241 else {
1242 SuperTy = PropRefExpr->getSuperType();
1243 SuperLocation = PropRefExpr->getSuperLocation();
1244 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001245 }
1246 else if (ObjCImplicitSetterGetterRefExpr *ImplicitRefExpr =
1247 dyn_cast<ObjCImplicitSetterGetterRefExpr>(BinOp->getLHS())) {
1248 OMD = ImplicitRefExpr->getSetterMethod();
1249 Sel = OMD->getSelector();
1250 Ty = ImplicitRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001251 Super = ImplicitRefExpr->isSuperReceiver();
1252 if (!Super)
1253 Receiver = ImplicitRefExpr->getBase();
1254 else {
1255 SuperTy = ImplicitRefExpr->getSuperType();
1256 SuperLocation = ImplicitRefExpr->getSuperLocation();
1257 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001258 }
1259
1260 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Steve Naroffc77a6362008-12-04 16:24:46 +00001261 llvm::SmallVector<Expr *, 1> ExprVec;
1262 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001264 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001265 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001266 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001267 Ty.getNonReferenceType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001268 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001269 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001270 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001271 SuperTy,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001272 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001273 &ExprVec[0], 1,
1274 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001275 else {
1276 // FIXME. Refactor this into common code with that in
1277 // RewritePropertyOrImplicitGetter
1278 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1279 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1280 if (PropGetters[Exp])
1281 // This allows us to handle chain/nested property/implicit getters.
1282 Receiver = PropGetters[Exp];
1283
Douglas Gregor04badcf2010-04-21 00:45:42 +00001284 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001285 Ty.getNonReferenceType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001286 /*FIXME: */SourceLocation(),
1287 cast<Expr>(Receiver),
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001288 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001289 &ExprVec[0], 1,
1290 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001291 }
Steve Naroffc77a6362008-12-04 16:24:46 +00001292 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Steve Naroffc77a6362008-12-04 16:24:46 +00001294 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001295 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001296 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001297 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1298 // to things that stay around.
1299 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001300 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001301}
1302
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001303Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1304 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001305 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001306 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001307 ObjCMethodDecl *OMD = 0;
1308 QualType Ty;
1309 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001310 bool Super = false;
1311 QualType SuperTy;
1312 SourceLocation SuperLocation;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001313 if (ObjCPropertyRefExpr *PropRefExpr =
1314 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
1315 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1316 OMD = PDecl->getGetterMethodDecl();
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001317 Ty = PDecl->getType();
1318 Sel = PDecl->getGetterName();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001319 Super = PropRefExpr->isSuperReceiver();
1320 if (!Super)
1321 Receiver = PropRefExpr->getBase();
1322 else {
1323 SuperTy = PropRefExpr->getSuperType();
1324 SuperLocation = PropRefExpr->getSuperLocation();
1325 }
Steve Naroff8599e7a2008-12-08 16:43:47 +00001326 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001327 else if (ObjCImplicitSetterGetterRefExpr *ImplicitRefExpr =
1328 dyn_cast<ObjCImplicitSetterGetterRefExpr>(PropOrGetterRefExpr)) {
1329 OMD = ImplicitRefExpr->getGetterMethod();
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001330 Sel = OMD->getSelector();
1331 Ty = ImplicitRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001332 Super = ImplicitRefExpr->isSuperReceiver();
1333 if (!Super)
1334 Receiver = ImplicitRefExpr->getBase();
1335 else {
1336 SuperTy = ImplicitRefExpr->getSuperType();
1337 SuperLocation = ImplicitRefExpr->getSuperLocation();
1338 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001339 }
1340
1341 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1342
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001343 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001344 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001345 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001346 Ty.getNonReferenceType(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001347 /*FIXME?*/SourceLocation(),
1348 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001349 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001350 SuperTy,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001351 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001352 0, 0,
1353 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001354 else {
1355 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1356 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1357 if (PropGetters[Exp])
1358 // This allows us to handle chain/nested property/implicit getters.
1359 Receiver = PropGetters[Exp];
Douglas Gregor04badcf2010-04-21 00:45:42 +00001360 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001361 Ty.getNonReferenceType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001362 /*FIXME:*/SourceLocation(),
1363 cast<Expr>(Receiver),
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001364 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001365 0, 0,
1366 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001367 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001368
Steve Naroff4c3580e2008-12-04 23:50:32 +00001369 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001370
1371 if (!PropParentMap)
1372 PropParentMap = new ParentMap(CurrentBody);
1373
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001374 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
1375 if (Parent && (isa<ObjCPropertyRefExpr>(Parent) ||
1376 isa<ObjCImplicitSetterGetterRefExpr>(Parent))) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001377 // We stash away the ReplacingStmt since actually doing the
1378 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001379 PropGetters[PropOrGetterRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001380 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1381 // to things that stay around.
1382 Context->Deallocate(MsgExpr);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001383 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001384 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001385 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001386 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001387 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1388 // to things that stay around.
1389 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001390 return ReplacingStmt;
1391 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001392}
1393
Mike Stump1eb44332009-09-09 15:08:12 +00001394Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001395 SourceLocation OrigStart,
1396 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001397 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001398 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001399 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001400 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001401 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001402 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001403 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001404 // lookup which class implements the instance variable.
1405 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001406 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001407 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001408 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001409
Steve Narofff0757612008-05-08 17:52:16 +00001410 // Synthesize an explicit cast to gain access to the ivar.
1411 std::string RecName = clsDeclared->getIdentifier()->getName();
1412 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001413 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001414 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001415 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001416 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1417 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001418 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001419 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001420 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001421 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001422 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1423 IV->getBase()->getLocEnd(),
1424 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001425 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001426 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001427 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001428 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1429 IV->getLocation(),
1430 D->getType());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001431 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001432 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001433 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001434 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001435 // Cannot delete IV->getBase(), since PE points to it.
1436 // Replace the old base with the cast. This is important when doing
1437 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001438 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001439 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001440 }
Steve Naroff84472a82008-04-18 21:55:08 +00001441 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001442 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Steve Naroff9f525972008-05-06 23:20:07 +00001444 // Explicit ivar refs need to have a cast inserted.
1445 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001446 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001447 ObjCInterfaceType *iFaceDecl =
1448 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001449 // lookup which class implements the instance variable.
1450 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001451 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001452 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001453 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001454
Steve Naroff9f525972008-05-06 23:20:07 +00001455 // Synthesize an explicit cast to gain access to the ivar.
1456 std::string RecName = clsDeclared->getIdentifier()->getName();
1457 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001458 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001459 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001460 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001461 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1462 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001463 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001464 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001465 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001466 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001467 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001468 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001469 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001470 // Cannot delete IV->getBase(), since PE points to it.
1471 // Replace the old base with the cast. This is important when doing
1472 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001473 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001474 return IV;
1475 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001476 }
Steve Naroff84472a82008-04-18 21:55:08 +00001477 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001478}
1479
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001480Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1481 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1482 CI != E; ++CI) {
1483 if (*CI) {
1484 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1485 if (newStmt)
1486 *CI = newStmt;
1487 }
1488 }
1489 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1490 SourceRange OrigStmtRange = S->getSourceRange();
1491 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1492 replaced);
1493 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001494 }
1495 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1496 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1497 return newStmt;
1498 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001499 return S;
1500}
1501
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001502/// SynthCountByEnumWithState - To print:
1503/// ((unsigned int (*)
1504/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001505/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001506/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001507/// "countByEnumeratingWithState:objects:count:"),
1508/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001509/// (id *)items, (unsigned int)16)
1510///
Steve Naroffb29b4272008-04-14 22:03:09 +00001511void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001512 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1513 "id *, unsigned int))(void *)objc_msgSend)";
1514 buf += "\n\t\t";
1515 buf += "((id)l_collection,\n\t\t";
1516 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1517 buf += "\n\t\t";
1518 buf += "&enumState, "
1519 "(id *)items, (unsigned int)16)";
1520}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001521
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001522/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1523/// statement to exit to its outer synthesized loop.
1524///
Steve Naroffb29b4272008-04-14 22:03:09 +00001525Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001526 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1527 return S;
1528 // replace break with goto __break_label
1529 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001531 SourceLocation startLoc = S->getLocStart();
1532 buf = "goto __break_label_";
1533 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001534 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001535
1536 return 0;
1537}
1538
1539/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1540/// statement to continue with its inner synthesized loop.
1541///
Steve Naroffb29b4272008-04-14 22:03:09 +00001542Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001543 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1544 return S;
1545 // replace continue with goto __continue_label
1546 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001548 SourceLocation startLoc = S->getLocStart();
1549 buf = "goto __continue_label_";
1550 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001551 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001553 return 0;
1554}
1555
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001556/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001557/// It rewrites:
1558/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001560/// Into:
1561/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001562/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001563/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001564/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001565/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001566/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001567/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001568/// if (limit) {
1569/// unsigned long startMutations = *enumState.mutationsPtr;
1570/// do {
1571/// unsigned long counter = 0;
1572/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001573/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001574/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001575/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001576/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001577/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001578/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001579/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001580/// objects:items count:16]);
1581/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001582/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001583/// }
1584/// else
1585/// elem = nil;
1586/// }
1587///
Steve Naroffb29b4272008-04-14 22:03:09 +00001588Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001589 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001590 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001591 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001592 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001593 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001594 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001596 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001597 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar4087f272010-08-17 22:39:59 +00001598 llvm::StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001599 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001600 std::string buf;
1601 buf = "\n{\n\t";
1602 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1603 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001604 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001605 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001606 if (ElementType->isObjCQualifiedIdType() ||
1607 ElementType->isObjCQualifiedInterfaceType())
1608 // Simply use 'id' for all qualified types.
1609 elementTypeAsString = "id";
1610 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001611 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001612 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001613 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001614 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001615 buf += elementName;
1616 buf += ";\n\t";
1617 }
Chris Lattner06767512008-04-08 05:52:18 +00001618 else {
1619 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001620 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001621 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1622 if (VD->getType()->isObjCQualifiedIdType() ||
1623 VD->getType()->isObjCQualifiedInterfaceType())
1624 // Simply use 'id' for all qualified types.
1625 elementTypeAsString = "id";
1626 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001627 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001628 }
Mike Stump1eb44332009-09-09 15:08:12 +00001629
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001630 // struct __objcFastEnumerationState enumState = { 0 };
1631 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1632 // id items[16];
1633 buf += "id items[16];\n\t";
1634 // id l_collection = (id)
1635 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001636 // Find start location of 'collection' the hard way!
1637 const char *startCollectionBuf = startBuf;
1638 startCollectionBuf += 3; // skip 'for'
1639 startCollectionBuf = strchr(startCollectionBuf, '(');
1640 startCollectionBuf++; // skip '('
1641 // find 'in' and skip it.
1642 while (*startCollectionBuf != ' ' ||
1643 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1644 (*(startCollectionBuf+3) != ' ' &&
1645 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1646 startCollectionBuf++;
1647 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001648
1649 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001650 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001651 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001652 SourceLocation rightParenLoc = S->getRParenLoc();
1653 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1654 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001655 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001656
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001657 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1658 // objects:items count:16];
1659 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001660 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001661 // ((unsigned int (*)
1662 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001663 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001664 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001665 // "countByEnumeratingWithState:objects:count:"),
1666 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001667 // (id *)items, (unsigned int)16);
1668 buf += "unsigned long limit =\n\t\t";
1669 SynthCountByEnumWithState(buf);
1670 buf += ";\n\t";
1671 /// if (limit) {
1672 /// unsigned long startMutations = *enumState.mutationsPtr;
1673 /// do {
1674 /// unsigned long counter = 0;
1675 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001676 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001677 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001678 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001679 buf += "if (limit) {\n\t";
1680 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1681 buf += "do {\n\t\t";
1682 buf += "unsigned long counter = 0;\n\t\t";
1683 buf += "do {\n\t\t\t";
1684 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1685 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1686 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001687 buf += " = (";
1688 buf += elementTypeAsString;
1689 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001690 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001691 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001693 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001694 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001695 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001696 /// objects:items count:16]);
1697 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001698 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001699 /// }
1700 /// else
1701 /// elem = nil;
1702 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001703 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001704 buf = ";\n\t";
1705 buf += "__continue_label_";
1706 buf += utostr(ObjCBcLabelNo.back());
1707 buf += ": ;";
1708 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001709 buf += "} while (counter < limit);\n\t";
1710 buf += "} while (limit = ";
1711 SynthCountByEnumWithState(buf);
1712 buf += ");\n\t";
1713 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001714 buf += " = ((";
1715 buf += elementTypeAsString;
1716 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001717 buf += "__break_label_";
1718 buf += utostr(ObjCBcLabelNo.back());
1719 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001720 buf += "}\n\t";
1721 buf += "else\n\t\t";
1722 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001723 buf += " = ((";
1724 buf += elementTypeAsString;
1725 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001726 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001728 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001729 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001730 if (isa<CompoundStmt>(S->getBody())) {
1731 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001732 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001733 } else {
1734 /* Need to treat single statements specially. For example:
1735 *
1736 * for (A *a in b) if (stuff()) break;
1737 * for (A *a in b) xxxyy;
1738 *
1739 * The following code simply scans ahead to the semi to find the actual end.
1740 */
1741 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1742 const char *semiBuf = strchr(stmtBuf, ';');
1743 assert(semiBuf && "Can't find ';'");
1744 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001745 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001746 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001747 Stmts.pop_back();
1748 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001749 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001750}
1751
Mike Stump1eb44332009-09-09 15:08:12 +00001752/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001753/// This routine rewrites @synchronized(expr) stmt;
1754/// into:
1755/// objc_sync_enter(expr);
1756/// @try stmt @finally { objc_sync_exit(expr); }
1757///
Steve Naroffb29b4272008-04-14 22:03:09 +00001758Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001759 // Get the start location and compute the semi location.
1760 SourceLocation startLoc = S->getLocStart();
1761 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001762
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001763 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001764
1765 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001766 buf = "objc_sync_enter((id)";
1767 const char *lparenBuf = startBuf;
1768 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001769 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001770 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1771 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001772 // been rewritten! (which implies the SourceLocation's are invalid).
1773 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001774 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001775 while (*endBuf != ')') endBuf--;
1776 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001777 buf = ");\n";
1778 // declare a new scope with two variables, _stack and _rethrow.
1779 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1780 buf += "int buf[18/*32-bit i386*/];\n";
1781 buf += "char *pointers[4];} _stack;\n";
1782 buf += "id volatile _rethrow = 0;\n";
1783 buf += "objc_exception_try_enter(&_stack);\n";
1784 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001785 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001786 startLoc = S->getSynchBody()->getLocEnd();
1787 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Steve Naroffc7089f12008-08-19 13:04:19 +00001789 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001790 SourceLocation lastCurlyLoc = startLoc;
1791 buf = "}\nelse {\n";
1792 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001793 buf += "}\n";
1794 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001795 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001796
1797 std::string syncBuf;
1798 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001799 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00001800 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001801 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001802 std::string syncExprBufS;
1803 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001804 syncExpr->printPretty(syncExprBuf, *Context, 0,
1805 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001806 syncBuf += syncExprBuf.str();
1807 syncBuf += ");";
1808
1809 buf += syncBuf;
1810 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001811 buf += "}\n";
1812 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Benjamin Kramerd999b372010-02-14 14:14:16 +00001814 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001815
1816 bool hasReturns = false;
1817 HasReturnStmts(S->getSynchBody(), hasReturns);
1818 if (hasReturns)
1819 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1820
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001821 return 0;
1822}
1823
Steve Naroffb85e77a2009-12-05 21:43:12 +00001824void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1825{
Steve Naroff8c565152008-12-05 17:03:39 +00001826 // Perform a bottom up traversal of all children.
1827 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1828 CI != E; ++CI)
1829 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001830 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001831
Steve Naroffb85e77a2009-12-05 21:43:12 +00001832 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001833 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001834 TryFinallyContainsReturnDiag);
1835 }
1836 return;
1837}
1838
Steve Naroffb85e77a2009-12-05 21:43:12 +00001839void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1840{
1841 // Perform a bottom up traversal of all children.
1842 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1843 CI != E; ++CI)
1844 if (*CI)
1845 HasReturnStmts(*CI, hasReturns);
1846
1847 if (isa<ReturnStmt>(S))
1848 hasReturns = true;
1849 return;
1850}
1851
1852void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1853 // Perform a bottom up traversal of all children.
1854 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1855 CI != E; ++CI)
1856 if (*CI) {
1857 RewriteTryReturnStmts(*CI);
1858 }
1859 if (isa<ReturnStmt>(S)) {
1860 SourceLocation startLoc = S->getLocStart();
1861 const char *startBuf = SM->getCharacterData(startLoc);
1862
1863 const char *semiBuf = strchr(startBuf, ';');
1864 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1865 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1866
1867 std::string buf;
1868 buf = "{ objc_exception_try_exit(&_stack); return";
1869
Benjamin Kramerd999b372010-02-14 14:14:16 +00001870 ReplaceText(startLoc, 6, buf);
1871 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001872 }
1873 return;
1874}
1875
1876void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1877 // Perform a bottom up traversal of all children.
1878 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1879 CI != E; ++CI)
1880 if (*CI) {
1881 RewriteSyncReturnStmts(*CI, syncExitBuf);
1882 }
1883 if (isa<ReturnStmt>(S)) {
1884 SourceLocation startLoc = S->getLocStart();
1885 const char *startBuf = SM->getCharacterData(startLoc);
1886
1887 const char *semiBuf = strchr(startBuf, ';');
1888 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1889 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1890
1891 std::string buf;
1892 buf = "{ objc_exception_try_exit(&_stack);";
1893 buf += syncExitBuf;
1894 buf += " return";
1895
Benjamin Kramerd999b372010-02-14 14:14:16 +00001896 ReplaceText(startLoc, 6, buf);
1897 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001898 }
1899 return;
1900}
1901
Steve Naroffb29b4272008-04-14 22:03:09 +00001902Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001903 // Get the start location and compute the semi location.
1904 SourceLocation startLoc = S->getLocStart();
1905 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Steve Naroff75730982007-11-07 04:08:17 +00001907 assert((*startBuf == '@') && "bogus @try location");
1908
1909 std::string buf;
1910 // declare a new scope with two variables, _stack and _rethrow.
1911 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1912 buf += "int buf[18/*32-bit i386*/];\n";
1913 buf += "char *pointers[4];} _stack;\n";
1914 buf += "id volatile _rethrow = 0;\n";
1915 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001916 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001917
Benjamin Kramerd999b372010-02-14 14:14:16 +00001918 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Steve Naroff75730982007-11-07 04:08:17 +00001920 startLoc = S->getTryBody()->getLocEnd();
1921 startBuf = SM->getCharacterData(startLoc);
1922
1923 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001924
Steve Naroff75730982007-11-07 04:08:17 +00001925 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001926 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001927 startLoc = startLoc.getFileLocWithOffset(1);
1928 buf = " /* @catch begin */ else {\n";
1929 buf += " id _caught = objc_exception_extract(&_stack);\n";
1930 buf += " objc_exception_try_enter (&_stack);\n";
1931 buf += " if (_setjmp(_stack.buf))\n";
1932 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1933 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Benjamin Kramerd999b372010-02-14 14:14:16 +00001935 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001936 } else { /* no catch list */
1937 buf = "}\nelse {\n";
1938 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1939 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001940 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001941 }
Steve Naroff75730982007-11-07 04:08:17 +00001942 bool sawIdTypedCatch = false;
1943 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001944 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1945 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001946 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001947
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001948 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001949 buf = "if ("; // we are generating code for the first catch clause
1950 else
1951 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001952 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001953 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Steve Naroff75730982007-11-07 04:08:17 +00001955 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Steve Naroff75730982007-11-07 04:08:17 +00001957 const char *lParenLoc = strchr(startBuf, '(');
1958
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001959 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001960 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001961 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001962 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1963 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001964 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001965 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001966 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Steve Naroffe12e6922008-02-01 20:02:07 +00001968 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001969 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001970 } else if (catchDecl) {
1971 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001972 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001973 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001974 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001975 sawIdTypedCatch = true;
John McCall506b57e2010-05-17 21:00:27 +00001976 } else if (const ObjCObjectPointerType *Ptr =
1977 t->getAs<ObjCObjectPointerType>()) {
1978 // Should be a pointer to a class.
1979 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1980 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001981 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001982 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001983 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001984 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001985 }
1986 }
1987 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001988 lastCatchBody = Catch->getCatchBody();
1989 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001990 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1991 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1992 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1993 assert((*rParenBuf == ')') && "bogus @catch paren location");
1994 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Mike Stump1eb44332009-09-09 15:08:12 +00001996 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001997 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001998 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001999 } else {
Steve Naroff75730982007-11-07 04:08:17 +00002000 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002001 }
Steve Naroff75730982007-11-07 04:08:17 +00002002 }
2003 // Complete the catch list...
2004 if (lastCatchBody) {
2005 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002006 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2007 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Steve Naroff378f47a2008-09-11 15:29:03 +00002009 // Insert the last (implicit) else clause *before* the right curly brace.
2010 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2011 buf = "} /* last catch end */\n";
2012 buf += "else {\n";
2013 buf += " _rethrow = _caught;\n";
2014 buf += " objc_exception_try_exit(&_stack);\n";
2015 buf += "} } /* @catch end */\n";
2016 if (!S->getFinallyStmt())
2017 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002018 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Steve Naroff75730982007-11-07 04:08:17 +00002020 // Set lastCurlyLoc
2021 lastCurlyLoc = lastCatchBody->getLocEnd();
2022 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002023 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002024 startLoc = finalStmt->getLocStart();
2025 startBuf = SM->getCharacterData(startLoc);
2026 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Benjamin Kramerd999b372010-02-14 14:14:16 +00002028 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Steve Naroff75730982007-11-07 04:08:17 +00002030 Stmt *body = finalStmt->getFinallyBody();
2031 SourceLocation startLoc = body->getLocStart();
2032 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002033 assert(*SM->getCharacterData(startLoc) == '{' &&
2034 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002035 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002036 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Steve Naroff75730982007-11-07 04:08:17 +00002038 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002039 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00002040 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002041 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002042
Steve Naroff75730982007-11-07 04:08:17 +00002043 // Set lastCurlyLoc
2044 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Steve Naroff8c565152008-12-05 17:03:39 +00002046 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002047 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002048 } else { /* no finally clause - make sure we synthesize an implicit one */
2049 buf = "{ /* implicit finally clause */\n";
2050 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2051 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2052 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002053 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002054
2055 // Now check for any return/continue/go statements within the @try.
2056 // The implicit finally clause won't called if the @try contains any
2057 // jump statements.
2058 bool hasReturns = false;
2059 HasReturnStmts(S->getTryBody(), hasReturns);
2060 if (hasReturns)
2061 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002062 }
2063 // Now emit the final closing curly brace...
2064 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002065 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002066 return 0;
2067}
2068
Mike Stump1eb44332009-09-09 15:08:12 +00002069// This can't be done with ReplaceStmt(S, ThrowExpr), since
2070// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002071// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002072Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002073 // Get the start location and compute the semi location.
2074 SourceLocation startLoc = S->getLocStart();
2075 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Steve Naroff2bd03922007-11-07 15:32:26 +00002077 assert((*startBuf == '@') && "bogus @throw location");
2078
2079 std::string buf;
2080 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002081 if (S->getThrowExpr())
2082 buf = "objc_exception_throw(";
2083 else // add an implicit argument
2084 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002086 // handle "@ throw" correctly.
2087 const char *wBuf = strchr(startBuf, 'w');
2088 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002089 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Steve Naroff2bd03922007-11-07 15:32:26 +00002091 const char *semiBuf = strchr(startBuf, ';');
2092 assert((*semiBuf == ';') && "@throw: can't find ';'");
2093 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002094 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002095 return 0;
2096}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002097
Steve Naroffb29b4272008-04-14 22:03:09 +00002098Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002099 // Create a new string expression.
2100 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002101 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002102 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00002103 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2104 StrEncoding.length(), false,StrType,
2105 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002106 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Chris Lattner07506182007-11-30 22:53:43 +00002108 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002109 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002110 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002111}
2112
Steve Naroffb29b4272008-04-14 22:03:09 +00002113Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002114 if (!SelGetUidFunctionDecl)
2115 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002116 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2117 // Create a call to sel_registerName("selName").
2118 llvm::SmallVector<Expr*, 8> SelExprs;
2119 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002120 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002121 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002122 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002123 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002124 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2125 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002126 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002127 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002128 return SelExp;
2129}
2130
Steve Naroffb29b4272008-04-14 22:03:09 +00002131CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002132 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2133 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002134 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002135 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Steve Naroffebf2b562007-10-23 23:50:29 +00002137 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002138 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002139
Steve Naroffebf2b562007-10-23 23:50:29 +00002140 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002141 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002142 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002143 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002144 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002145
John McCall183700f2009-09-21 23:43:11 +00002146 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002148 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002149 new (Context) CallExpr(*Context, ICE, args, nargs,
2150 FT->getCallResultType(*Context), EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002151 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002152}
2153
Steve Naroffd5255f52007-11-01 13:24:47 +00002154static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2155 const char *&startRef, const char *&endRef) {
2156 while (startBuf < endBuf) {
2157 if (*startBuf == '<')
2158 startRef = startBuf; // mark the start.
2159 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002160 if (startRef && *startRef == '<') {
2161 endRef = startBuf; // mark the end.
2162 return true;
2163 }
2164 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002165 }
2166 startBuf++;
2167 }
2168 return false;
2169}
2170
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002171static void scanToNextArgument(const char *&argRef) {
2172 int angle = 0;
2173 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2174 if (*argRef == '<')
2175 angle++;
2176 else if (*argRef == '>')
2177 angle--;
2178 argRef++;
2179 }
2180 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2181}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002182
Steve Naroffb29b4272008-04-14 22:03:09 +00002183bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002184 if (T->isObjCQualifiedIdType())
2185 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002186 if (const PointerType *PT = T->getAs<PointerType>()) {
2187 if (PT->getPointeeType()->isObjCQualifiedIdType())
2188 return true;
2189 }
2190 if (T->isObjCObjectPointerType()) {
2191 T = T->getPointeeType();
2192 return T->isObjCQualifiedInterfaceType();
2193 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002194 if (T->isArrayType()) {
2195 QualType ElemTy = Context->getBaseElementType(T);
2196 return needToScanForQualifiers(ElemTy);
2197 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002198 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002199}
2200
Steve Naroff4f95b752008-07-29 18:15:38 +00002201void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2202 QualType Type = E->getType();
2203 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002204 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Steve Naroffcda658e2008-11-19 21:15:47 +00002206 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2207 Loc = ECE->getLParenLoc();
2208 EndLoc = ECE->getRParenLoc();
2209 } else {
2210 Loc = E->getLocStart();
2211 EndLoc = E->getLocEnd();
2212 }
2213 // This will defend against trying to rewrite synthesized expressions.
2214 if (Loc.isInvalid() || EndLoc.isInvalid())
2215 return;
2216
Steve Naroff4f95b752008-07-29 18:15:38 +00002217 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002218 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002219 const char *startRef = 0, *endRef = 0;
2220 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2221 // Get the locations of the startRef, endRef.
2222 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2223 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2224 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002225 InsertText(LessLoc, "/*");
2226 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002227 }
2228 }
2229}
2230
Steve Naroffb29b4272008-04-14 22:03:09 +00002231void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002232 SourceLocation Loc;
2233 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002234 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002235 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2236 Loc = VD->getLocation();
2237 Type = VD->getType();
2238 }
2239 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2240 Loc = FD->getLocation();
2241 // Check for ObjC 'id' and class types that have been adorned with protocol
2242 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002243 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002244 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002245 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002246 if (!proto)
2247 return;
2248 Type = proto->getResultType();
2249 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002250 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2251 Loc = FD->getLocation();
2252 Type = FD->getType();
2253 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002254 else
2255 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002256
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002257 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002258 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002259
Steve Naroffd5255f52007-11-01 13:24:47 +00002260 const char *endBuf = SM->getCharacterData(Loc);
2261 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002262 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002263 startBuf--; // scan backward (from the decl location) for return type.
2264 const char *startRef = 0, *endRef = 0;
2265 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2266 // Get the locations of the startRef, endRef.
2267 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2268 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2269 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002270 InsertText(LessLoc, "/*");
2271 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002272 }
2273 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002274 if (!proto)
2275 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002276 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002277 const char *startBuf = SM->getCharacterData(Loc);
2278 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002279 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2280 if (needToScanForQualifiers(proto->getArgType(i))) {
2281 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002282
Steve Naroffd5255f52007-11-01 13:24:47 +00002283 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002284 // scan forward (from the decl location) for argument types.
2285 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002286 const char *startRef = 0, *endRef = 0;
2287 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2288 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002289 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002290 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002291 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002292 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002293 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002294 InsertText(LessLoc, "/*");
2295 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002296 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002297 startBuf = ++endBuf;
2298 }
2299 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002300 // If the function name is derived from a macro expansion, then the
2301 // argument buffer will not follow the name. Need to speak with Chris.
2302 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002303 startBuf++; // scan forward (from the decl location) for argument types.
2304 startBuf++;
2305 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002306 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002307}
2308
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002309void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2310 QualType QT = ND->getType();
2311 const Type* TypePtr = QT->getAs<Type>();
2312 if (!isa<TypeOfExprType>(TypePtr))
2313 return;
2314 while (isa<TypeOfExprType>(TypePtr)) {
2315 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2316 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2317 TypePtr = QT->getAs<Type>();
2318 }
2319 // FIXME. This will not work for multiple declarators; as in:
2320 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002321 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002322 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2323 const char *startBuf = SM->getCharacterData(DeclLoc);
2324 if (ND->getInit()) {
2325 std::string Name(ND->getNameAsString());
2326 TypeAsString += " " + Name + " = ";
2327 Expr *E = ND->getInit();
2328 SourceLocation startLoc;
2329 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2330 startLoc = ECE->getLParenLoc();
2331 else
2332 startLoc = E->getLocStart();
2333 startLoc = SM->getInstantiationLoc(startLoc);
2334 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002335 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002336 }
2337 else {
2338 SourceLocation X = ND->getLocEnd();
2339 X = SM->getInstantiationLoc(X);
2340 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002341 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002342 }
2343}
2344
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002345// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002346void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002347 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2348 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002349 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002350 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002351 &ArgTys[0], ArgTys.size(),
2352 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002353 false, false, 0, 0,
2354 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002355 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002356 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002357 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002358 SC_Extern,
2359 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002360}
2361
Steve Naroffb29b4272008-04-14 22:03:09 +00002362void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002363 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002364 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002365 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002366 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002367 return;
2368 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002369 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002370}
2371
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002372void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2373 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002374 const char *argPtr = TypeString.c_str();
2375 if (!strchr(argPtr, '^')) {
2376 Str += TypeString;
2377 return;
2378 }
2379 while (*argPtr) {
2380 Str += (*argPtr == '^' ? '*' : *argPtr);
2381 argPtr++;
2382 }
2383}
2384
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002385// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002386void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2387 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002388 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002389 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002390 const char *argPtr = TypeString.c_str();
2391 int paren = 0;
2392 while (*argPtr) {
2393 switch (*argPtr) {
2394 case '(':
2395 Str += *argPtr;
2396 paren++;
2397 break;
2398 case ')':
2399 Str += *argPtr;
2400 paren--;
2401 break;
2402 case '^':
2403 Str += '*';
2404 if (paren == 1)
2405 Str += VD->getNameAsString();
2406 break;
2407 default:
2408 Str += *argPtr;
2409 break;
2410 }
2411 argPtr++;
2412 }
2413}
2414
2415
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002416void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2417 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2418 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2419 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2420 if (!proto)
2421 return;
2422 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002423 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002424 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002425 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002426 FdStr += "(";
2427 unsigned numArgs = proto->getNumArgs();
2428 for (unsigned i = 0; i < numArgs; i++) {
2429 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002430 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002431 if (i+1 < numArgs)
2432 FdStr += ", ";
2433 }
2434 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002435 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002436 CurFunctionDeclToDeclareForBlock = 0;
2437}
2438
Steve Naroffc0a123c2008-03-11 17:37:02 +00002439// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002440void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002441 if (SuperContructorFunctionDecl)
2442 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002443 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002444 llvm::SmallVector<QualType, 16> ArgTys;
2445 QualType argT = Context->getObjCIdType();
2446 assert(!argT.isNull() && "Can't find 'id' type");
2447 ArgTys.push_back(argT);
2448 ArgTys.push_back(argT);
2449 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2450 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002451 false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002452 false, false, 0, 0,
2453 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002454 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002455 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002456 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002457 SC_Extern,
2458 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002459}
2460
Steve Naroff09b266e2007-10-30 23:14:51 +00002461// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002462void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002463 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2464 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002465 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002466 assert(!argT.isNull() && "Can't find 'id' type");
2467 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002468 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002469 assert(!argT.isNull() && "Can't find 'SEL' type");
2470 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002471 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002472 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002473 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002474 false, false, 0, 0,
2475 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002476 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002477 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002478 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002479 SC_Extern,
2480 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002481}
2482
Steve Naroff874e2322007-11-15 10:28:18 +00002483// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002484void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002485 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2486 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002487 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002488 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002489 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002490 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2491 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2492 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002493 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002494 assert(!argT.isNull() && "Can't find 'SEL' type");
2495 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002496 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002497 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002498 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002499 false, false, 0, 0,
2500 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002501 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002502 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002503 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002504 SC_Extern,
2505 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002506}
2507
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002508// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002509void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002510 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2511 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002512 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002513 assert(!argT.isNull() && "Can't find 'id' type");
2514 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002515 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002516 assert(!argT.isNull() && "Can't find 'SEL' type");
2517 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002518 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002519 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002520 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002521 false, false, 0, 0,
2522 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002523 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002524 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002525 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002526 SC_Extern,
2527 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002528}
2529
Mike Stump1eb44332009-09-09 15:08:12 +00002530// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002531// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002532void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002533 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002534 &Context->Idents.get("objc_msgSendSuper_stret");
2535 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002536 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002537 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002538 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002539 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2540 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2541 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002542 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002543 assert(!argT.isNull() && "Can't find 'SEL' type");
2544 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002545 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002546 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002547 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002548 false, false, 0, 0,
2549 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002550 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002551 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002552 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002553 SC_Extern,
2554 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002555}
2556
Steve Naroff1284db82008-05-08 22:02:18 +00002557// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002558void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002559 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2560 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002561 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002562 assert(!argT.isNull() && "Can't find 'id' type");
2563 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002564 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002565 assert(!argT.isNull() && "Can't find 'SEL' type");
2566 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002567 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002568 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002569 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002570 false, false, 0, 0,
2571 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002572 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002573 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002574 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002575 SC_Extern,
2576 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002577}
2578
Steve Naroff09b266e2007-10-30 23:14:51 +00002579// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002580void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002581 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2582 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002583 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002584 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002585 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002586 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002587 false, false, 0, 0,
2588 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002589 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002590 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002591 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002592 SC_Extern,
2593 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002594}
2595
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002596// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2597void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2598 IdentifierInfo *getSuperClassIdent =
2599 &Context->Idents.get("class_getSuperclass");
2600 llvm::SmallVector<QualType, 16> ArgTys;
2601 ArgTys.push_back(Context->getObjCClassType());
2602 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2603 &ArgTys[0], ArgTys.size(),
2604 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002605 false, false, 0, 0,
2606 FunctionType::ExtInfo());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002607 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002608 SourceLocation(),
2609 getSuperClassIdent,
2610 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002611 SC_Extern,
2612 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002613 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002614}
2615
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002616// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002617void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002618 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2619 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002620 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002621 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002622 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002623 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002624 false, false, 0, 0,
2625 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002626 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002627 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002628 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002629 SC_Extern,
2630 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002631}
2632
Steve Naroffb29b4272008-04-14 22:03:09 +00002633Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002634 QualType strType = getConstantStringStructType();
2635
2636 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002637
2638 std::string tmpName = InFileName;
2639 unsigned i;
2640 for (i=0; i < tmpName.length(); i++) {
2641 char c = tmpName.at(i);
2642 // replace any non alphanumeric characters with '_'.
2643 if (!isalpha(c) && (c < '0' || c > '9'))
2644 tmpName[i] = '_';
2645 }
2646 S += tmpName;
2647 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002648 S += utostr(NumObjCStringLiterals++);
2649
Steve Naroffba92b2e2008-03-27 22:29:16 +00002650 Preamble += "static __NSConstantStringImpl " + S;
2651 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2652 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002653 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002654 std::string prettyBufS;
2655 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002656 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2657 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002658 Preamble += prettyBuf.str();
2659 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002660 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002661
2662 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002663 &Context->Idents.get(S), strType, 0,
John McCalld931b082010-08-26 03:08:43 +00002664 SC_Static, SC_None);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002665 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002666 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002667 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002668 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002669 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002670 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00002671 CK_BitCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002672 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002673 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002674 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002675}
2676
Steve Naroff874e2322007-11-15 10:28:18 +00002677// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002678QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002679 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002680 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002681 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002682 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002683 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002684
Steve Naroff874e2322007-11-15 10:28:18 +00002685 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002686 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002687 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002688 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002689
Steve Naroff874e2322007-11-15 10:28:18 +00002690 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002691 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002692 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2693 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002694 FieldTypes[i], 0,
2695 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002696 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002697 }
Mike Stump1eb44332009-09-09 15:08:12 +00002698
Douglas Gregor838db382010-02-11 01:19:42 +00002699 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002700 }
2701 return Context->getTagDeclType(SuperStructDecl);
2702}
2703
Steve Naroffb29b4272008-04-14 22:03:09 +00002704QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002705 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002706 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002707 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002708 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002709 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002710
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002711 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002712 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002713 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002714 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002715 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002716 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002717 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002718 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002719
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002720 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002721 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002722 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2723 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002724 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002725 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002726 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002727 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002728 }
2729
Douglas Gregor838db382010-02-11 01:19:42 +00002730 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002731 }
2732 return Context->getTagDeclType(ConstantStringDecl);
2733}
2734
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002735Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2736 SourceLocation StartLoc,
2737 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002738 if (!SelGetUidFunctionDecl)
2739 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002740 if (!MsgSendFunctionDecl)
2741 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002742 if (!MsgSendSuperFunctionDecl)
2743 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002744 if (!MsgSendStretFunctionDecl)
2745 SynthMsgSendStretFunctionDecl();
2746 if (!MsgSendSuperStretFunctionDecl)
2747 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002748 if (!MsgSendFpretFunctionDecl)
2749 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002750 if (!GetClassFunctionDecl)
2751 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002752 if (!GetSuperClassFunctionDecl)
2753 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002754 if (!GetMetaClassFunctionDecl)
2755 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002756
Steve Naroff874e2322007-11-15 10:28:18 +00002757 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002758 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2759 // May need to use objc_msgSend_stret() as well.
2760 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002761 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2762 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002763 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002764 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002765 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002766 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002767 }
Mike Stump1eb44332009-09-09 15:08:12 +00002768
Steve Naroff934f2762007-10-24 22:48:43 +00002769 // Synthesize a call to objc_msgSend().
2770 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002771 switch (Exp->getReceiverKind()) {
2772 case ObjCMessageExpr::SuperClass: {
2773 MsgSendFlavor = MsgSendSuperFunctionDecl;
2774 if (MsgSendStretFlavor)
2775 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2776 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002777
Douglas Gregor04badcf2010-04-21 00:45:42 +00002778 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002779
Douglas Gregor04badcf2010-04-21 00:45:42 +00002780 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002781
Douglas Gregor04badcf2010-04-21 00:45:42 +00002782 // set the receiver to self, the first argument to all methods.
2783 InitExprs.push_back(
2784 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002785 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002786 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2787 Context->getObjCIdType(),
2788 SourceLocation()))
2789 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002790
Douglas Gregor04badcf2010-04-21 00:45:42 +00002791 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2792 llvm::SmallVector<Expr*, 8> ClsExprs;
2793 QualType argType = Context->getPointerType(Context->CharTy);
2794 ClsExprs.push_back(StringLiteral::Create(*Context,
2795 ClassDecl->getIdentifier()->getNameStart(),
2796 ClassDecl->getIdentifier()->getLength(),
2797 false, argType, SourceLocation()));
2798 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2799 &ClsExprs[0],
2800 ClsExprs.size(),
2801 StartLoc,
2802 EndLoc);
2803 // (Class)objc_getClass("CurrentClass")
2804 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2805 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002806 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002807 ClsExprs.clear();
2808 ClsExprs.push_back(ArgExpr);
2809 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2810 &ClsExprs[0], ClsExprs.size(),
2811 StartLoc, EndLoc);
2812
2813 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2814 // To turn off a warning, type-cast to 'id'
2815 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2816 NoTypeInfoCStyleCastExpr(Context,
2817 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002818 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002819 // struct objc_super
2820 QualType superType = getSuperStructType();
2821 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002822
Douglas Gregor04badcf2010-04-21 00:45:42 +00002823 if (LangOpts.Microsoft) {
2824 SynthSuperContructorFunctionDecl();
2825 // Simulate a contructor call...
2826 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2827 superType, SourceLocation());
2828 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2829 InitExprs.size(),
2830 superType, SourceLocation());
2831 // The code for super is a little tricky to prevent collision with
2832 // the structure definition in the header. The rewriter has it's own
2833 // internal definition (__rw_objc_super) that is uses. This is why
2834 // we need the cast below. For example:
2835 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2836 //
John McCall2de56d12010-08-25 11:45:40 +00002837 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002838 Context->getPointerType(SuperRep->getType()),
2839 SourceLocation());
2840 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2841 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002842 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002843 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002844 // (struct objc_super) { <exprs from above> }
2845 InitListExpr *ILE =
2846 new (Context) InitListExpr(*Context, SourceLocation(),
2847 &InitExprs[0], InitExprs.size(),
2848 SourceLocation());
2849 TypeSourceInfo *superTInfo
2850 = Context->getTrivialTypeSourceInfo(superType);
2851 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2852 superType, ILE, false);
2853 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002854 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002855 Context->getPointerType(SuperRep->getType()),
2856 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002857 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002858 MsgExprs.push_back(SuperRep);
2859 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002860 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002861
2862 case ObjCMessageExpr::Class: {
2863 llvm::SmallVector<Expr*, 8> ClsExprs;
2864 QualType argType = Context->getPointerType(Context->CharTy);
2865 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002866 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002867 IdentifierInfo *clsName = Class->getIdentifier();
2868 ClsExprs.push_back(StringLiteral::Create(*Context,
2869 clsName->getNameStart(),
2870 clsName->getLength(),
2871 false, argType,
2872 SourceLocation()));
2873 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2874 &ClsExprs[0],
2875 ClsExprs.size(),
2876 StartLoc, EndLoc);
2877 MsgExprs.push_back(Cls);
2878 break;
2879 }
2880
2881 case ObjCMessageExpr::SuperInstance:{
2882 MsgSendFlavor = MsgSendSuperFunctionDecl;
2883 if (MsgSendStretFlavor)
2884 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2885 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2886 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2887 llvm::SmallVector<Expr*, 4> InitExprs;
2888
2889 InitExprs.push_back(
2890 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002891 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002892 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2893 Context->getObjCIdType(),
2894 SourceLocation()))
2895 ); // set the 'receiver'.
2896
2897 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2898 llvm::SmallVector<Expr*, 8> ClsExprs;
2899 QualType argType = Context->getPointerType(Context->CharTy);
2900 ClsExprs.push_back(StringLiteral::Create(*Context,
2901 ClassDecl->getIdentifier()->getNameStart(),
2902 ClassDecl->getIdentifier()->getLength(),
2903 false, argType, SourceLocation()));
2904 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2905 &ClsExprs[0],
2906 ClsExprs.size(),
2907 StartLoc, EndLoc);
2908 // (Class)objc_getClass("CurrentClass")
2909 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2910 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002911 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002912 ClsExprs.clear();
2913 ClsExprs.push_back(ArgExpr);
2914 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2915 &ClsExprs[0], ClsExprs.size(),
2916 StartLoc, EndLoc);
2917
2918 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2919 // To turn off a warning, type-cast to 'id'
2920 InitExprs.push_back(
2921 // set 'super class', using class_getSuperclass().
2922 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002923 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002924 // struct objc_super
2925 QualType superType = getSuperStructType();
2926 Expr *SuperRep;
2927
2928 if (LangOpts.Microsoft) {
2929 SynthSuperContructorFunctionDecl();
2930 // Simulate a contructor call...
2931 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2932 superType, SourceLocation());
2933 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2934 InitExprs.size(),
2935 superType, SourceLocation());
2936 // The code for super is a little tricky to prevent collision with
2937 // the structure definition in the header. The rewriter has it's own
2938 // internal definition (__rw_objc_super) that is uses. This is why
2939 // we need the cast below. For example:
2940 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2941 //
John McCall2de56d12010-08-25 11:45:40 +00002942 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002943 Context->getPointerType(SuperRep->getType()),
2944 SourceLocation());
2945 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2946 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002947 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002948 } else {
2949 // (struct objc_super) { <exprs from above> }
2950 InitListExpr *ILE =
2951 new (Context) InitListExpr(*Context, SourceLocation(),
2952 &InitExprs[0], InitExprs.size(),
2953 SourceLocation());
2954 TypeSourceInfo *superTInfo
2955 = Context->getTrivialTypeSourceInfo(superType);
2956 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2957 superType, ILE, false);
2958 }
2959 MsgExprs.push_back(SuperRep);
2960 break;
2961 }
2962
2963 case ObjCMessageExpr::Instance: {
2964 // Remove all type-casts because it may contain objc-style types; e.g.
2965 // Foo<Proto> *.
2966 Expr *recExpr = Exp->getInstanceReceiver();
2967 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2968 recExpr = CE->getSubExpr();
2969 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002970 CK_BitCast, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002971 MsgExprs.push_back(recExpr);
2972 break;
2973 }
2974 }
2975
Steve Naroffbeaf2992007-11-03 11:27:19 +00002976 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002977 llvm::SmallVector<Expr*, 8> SelExprs;
2978 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002979 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002980 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002981 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002982 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002983 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002984 &SelExprs[0], SelExprs.size(),
2985 StartLoc,
2986 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002987 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002988
Steve Naroff934f2762007-10-24 22:48:43 +00002989 // Now push any user supplied arguments.
2990 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002991 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002992 // Make all implicit casts explicit...ICE comes in handy:-)
2993 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2994 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002995 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002996 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002997 : ICE->getType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002998 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002999 (void)convertBlockPointerToFunctionPointer(type);
John McCalla5bbc502010-11-15 09:46:46 +00003000 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003001 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003002 }
3003 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003004 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003005 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003006 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003007 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00003008 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00003009 CK_BitCast, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003010 }
Mike Stump1eb44332009-09-09 15:08:12 +00003011 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003012 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003013 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3014 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003015 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003016 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003017 }
Steve Naroffab972d32007-11-04 22:37:50 +00003018 // Generate the funky cast.
3019 CastExpr *cast;
3020 llvm::SmallVector<QualType, 8> ArgTypes;
3021 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003022
Steve Naroffab972d32007-11-04 22:37:50 +00003023 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003024 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3025 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3026 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003027 ArgTypes.push_back(Context->getObjCIdType());
3028 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003029 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003030 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003031 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3032 E = OMD->param_end(); PI != E; ++PI) {
3033 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003034 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003035 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003036 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003037 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003038 ArgTypes.push_back(t);
3039 }
Chris Lattner89951a82009-02-20 18:43:26 +00003040 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3041 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003042 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003043 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003044 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003045 }
3046 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003047 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003048
Steve Naroffab972d32007-11-04 22:37:50 +00003049 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003050 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003051 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003052
Mike Stump1eb44332009-09-09 15:08:12 +00003053 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003054 // If we don't do this cast, we get the following bizarre warning/note:
3055 // xx.m:13: warning: function called through a non-compatible type
3056 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003057 cast = NoTypeInfoCStyleCastExpr(Context,
3058 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003059 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003060
Steve Naroffab972d32007-11-04 22:37:50 +00003061 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003062 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003063 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00003064 // If we don't have a method decl, force a variadic cast.
Douglas Gregorce056bc2010-02-21 22:15:06 +00003065 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003066 false, false, 0, 0,
3067 FunctionType::ExtInfo());
Steve Naroffab972d32007-11-04 22:37:50 +00003068 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003069 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003070 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003071
3072 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003073 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003074
John McCall183700f2009-09-21 23:43:11 +00003075 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003076 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003077 MsgExprs.size(),
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003078 FT->getResultType(), EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003079 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003080 if (MsgSendStretFlavor) {
3081 // We have the method which returns a struct/union. Must also generate
3082 // call to objc_msgSend_stret and hang both varieties on a conditional
3083 // expression which dictate which one to envoke depending on size of
3084 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003085
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003086 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003087 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003088 SourceLocation());
3089 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003090 cast = NoTypeInfoCStyleCastExpr(Context,
3091 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003092 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003093 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003094 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003095 &ArgTypes[0], ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00003096 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003097 false, false, 0, 0,
3098 FunctionType::ExtInfo());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003099 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003100 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003101 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003102
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003103 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003104 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003105
John McCall183700f2009-09-21 23:43:11 +00003106 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003107 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003108 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00003109 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003110
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003111 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00003112 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00003113 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00003114 Context->getSizeType(),
3115 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003116 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3117 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3118 // For X86 it is more complicated and some kind of target specific routine
3119 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003120 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003121 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003122 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3123 llvm::APInt(IntSize, 8),
3124 Context->IntTy,
3125 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003126 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
John McCall2de56d12010-08-25 11:45:40 +00003127 BO_LE,
Mike Stump1eb44332009-09-09 15:08:12 +00003128 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003129 SourceLocation());
3130 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003131 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003132 new (Context) ConditionalOperator(lessThanExpr,
3133 SourceLocation(), CE,
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003134 SourceLocation(), STCE, (Expr*)0,
3135 returnType);
3136 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3137 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003138 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003139 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003140 return ReplacingStmt;
3141}
3142
Steve Naroffb29b4272008-04-14 22:03:09 +00003143Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003144 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3145 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003146
Steve Naroff934f2762007-10-24 22:48:43 +00003147 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003148 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003149
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003150 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003151 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003152}
3153
Steve Naroff621edce2009-04-29 16:37:50 +00003154// typedef struct objc_object Protocol;
3155QualType RewriteObjC::getProtocolType() {
3156 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003157 TypeSourceInfo *TInfo
3158 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003159 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003160 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003161 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003162 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003163 }
3164 return Context->getTypeDeclType(ProtocolTypeDecl);
3165}
3166
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003167/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003168/// a synthesized/forward data reference (to the protocol's metadata).
3169/// The forward references (and metadata) are generated in
3170/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003171Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003172 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3173 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003174 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00003175 ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003176 SC_Extern, SC_None);
Steve Naroff621edce2009-04-29 16:37:50 +00003177 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003178 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003179 Context->getPointerType(DRE->getType()),
3180 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003181 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003182 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003183 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003184 ReplaceStmt(Exp, castExpr);
3185 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003186 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003187 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003188
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003189}
3190
Mike Stump1eb44332009-09-09 15:08:12 +00003191bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003192 const char *endBuf) {
3193 while (startBuf < endBuf) {
3194 if (*startBuf == '#') {
3195 // Skip whitespace.
3196 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3197 ;
3198 if (!strncmp(startBuf, "if", strlen("if")) ||
3199 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3200 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3201 !strncmp(startBuf, "define", strlen("define")) ||
3202 !strncmp(startBuf, "undef", strlen("undef")) ||
3203 !strncmp(startBuf, "else", strlen("else")) ||
3204 !strncmp(startBuf, "elif", strlen("elif")) ||
3205 !strncmp(startBuf, "endif", strlen("endif")) ||
3206 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3207 !strncmp(startBuf, "include", strlen("include")) ||
3208 !strncmp(startBuf, "import", strlen("import")) ||
3209 !strncmp(startBuf, "include_next", strlen("include_next")))
3210 return true;
3211 }
3212 startBuf++;
3213 }
3214 return false;
3215}
3216
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003217/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003218/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003219void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003220 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003221 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003222 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003223 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003224 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003225 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003226 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003227 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003228 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003229 SourceLocation LocStart = CDecl->getLocStart();
3230 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003231
Steve Narofffea763e82007-11-14 19:25:57 +00003232 const char *startBuf = SM->getCharacterData(LocStart);
3233 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003234
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003235 // If no ivars and no root or if its root, directly or indirectly,
3236 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003237 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3238 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003239 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003240 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003241 return;
3242 }
Mike Stump1eb44332009-09-09 15:08:12 +00003243
3244 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003245 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003246 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003247 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003248 if (LangOpts.Microsoft)
3249 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003250
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003251 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003252 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003253 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003254 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003255 // If the buffer contains preprocessor directives, we do more fine-grained
3256 // rewrites. This is intended to fix code that looks like (which occurs in
3257 // NSURL.h, for example):
3258 //
3259 // #ifdef XYZ
3260 // @interface Foo : NSObject
3261 // #else
3262 // @interface FooBar : NSObject
3263 // #endif
3264 // {
3265 // int i;
3266 // }
3267 // @end
3268 //
3269 // This clause is segregated to avoid breaking the common case.
3270 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003271 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003272 CDecl->getClassLoc();
3273 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003274 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003275
Chris Lattnercafeb352009-02-20 18:18:36 +00003276 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003277 // advance to the end of the referenced protocols.
3278 while (endHeader < cursor && *endHeader != '>') endHeader++;
3279 endHeader++;
3280 }
3281 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003282 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003283 } else {
3284 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003285 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003286 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003287 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003288 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003289 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003290 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003291 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003292 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003293
Steve Narofffea763e82007-11-14 19:25:57 +00003294 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003295 SourceLocation OnePastCurly =
3296 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003297 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003298 }
3299 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003300
Steve Narofffea763e82007-11-14 19:25:57 +00003301 // Now comment out any visibility specifiers.
3302 while (cursor < endBuf) {
3303 if (*cursor == '@') {
3304 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003305 // Skip whitespace.
3306 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3307 /*scan*/;
3308
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003309 // FIXME: presence of @public, etc. inside comment results in
3310 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003311 if (!strncmp(cursor, "public", strlen("public")) ||
3312 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003313 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003314 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003315 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003316 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003317 // FIXME: If there are cases where '<' is used in ivar declaration part
3318 // of user code, then scan the ivar list and use needToScanForQualifiers
3319 // for type checking.
3320 else if (*cursor == '<') {
3321 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003322 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003323 cursor = strchr(cursor, '>');
3324 cursor++;
3325 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003326 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003327 } else if (*cursor == '^') { // rewrite block specifier.
3328 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003329 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003330 }
Steve Narofffea763e82007-11-14 19:25:57 +00003331 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003332 }
Steve Narofffea763e82007-11-14 19:25:57 +00003333 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003334 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003335 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003336 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003337 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003338 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003339 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003340 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003341 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003342 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003343 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003344 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003345 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003346 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003347}
3348
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003349// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003350/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003351template<typename MethodIterator>
3352void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3353 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003354 bool IsInstanceMethod,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003355 llvm::StringRef prefix,
3356 llvm::StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003357 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003358 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003359
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003360 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003361 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003362 SEL _cmd;
3363 char *method_types;
3364 void *_imp;
3365 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003366 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003367 Result += "\nstruct _objc_method {\n";
3368 Result += "\tSEL _cmd;\n";
3369 Result += "\tchar *method_types;\n";
3370 Result += "\tvoid *_imp;\n";
3371 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003372
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003373 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003374 }
Mike Stump1eb44332009-09-09 15:08:12 +00003375
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003376 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003377
Steve Naroff946a6932008-03-11 00:12:29 +00003378 /* struct {
3379 struct _objc_method_list *next_method;
3380 int method_count;
3381 struct _objc_method method_list[];
3382 }
3383 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003384 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003385 Result += "\nstatic struct {\n";
3386 Result += "\tstruct _objc_method_list *next_method;\n";
3387 Result += "\tint method_count;\n";
3388 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003389 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003390 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003391 Result += prefix;
3392 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3393 Result += "_METHODS_";
3394 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003395 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003396 Result += IsInstanceMethod ? "inst" : "cls";
3397 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003398 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003399
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003400 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003401 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003402 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003403 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003404 Result += "\", \"";
3405 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003406 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003407 Result += MethodInternalNames[*MethodBegin];
3408 Result += "}\n";
3409 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3410 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003411 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003412 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003413 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003414 Result += "\", \"";
3415 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003416 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003417 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003418 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003419 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003420 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003421}
3422
Steve Naroff621edce2009-04-29 16:37:50 +00003423/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003424void RewriteObjC::
Daniel Dunbar4087f272010-08-17 22:39:59 +00003425RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3426 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003427 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003428
3429 // Output struct protocol_methods holder of method selector and type.
3430 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3431 /* struct protocol_methods {
3432 SEL _cmd;
3433 char *method_types;
3434 }
3435 */
3436 Result += "\nstruct _protocol_methods {\n";
3437 Result += "\tstruct objc_selector *_cmd;\n";
3438 Result += "\tchar *method_types;\n";
3439 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003440
Steve Naroff621edce2009-04-29 16:37:50 +00003441 objc_protocol_methods = true;
3442 }
3443 // Do not synthesize the protocol more than once.
3444 if (ObjCSynthesizedProtocols.count(PDecl))
3445 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003446
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003447 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3448 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3449 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003450 /* struct _objc_protocol_method_list {
3451 int protocol_method_count;
3452 struct protocol_methods protocols[];
3453 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003454 */
Steve Naroff621edce2009-04-29 16:37:50 +00003455 Result += "\nstatic struct {\n";
3456 Result += "\tint protocol_method_count;\n";
3457 Result += "\tstruct _protocol_methods protocol_methods[";
3458 Result += utostr(NumMethods);
3459 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3460 Result += PDecl->getNameAsString();
3461 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3462 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003463
Steve Naroff621edce2009-04-29 16:37:50 +00003464 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003465 for (ObjCProtocolDecl::instmeth_iterator
3466 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003467 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003468 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003469 Result += "\t ,{{(struct objc_selector *)\"";
3470 else
3471 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003472 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003473 std::string MethodTypeString;
3474 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3475 Result += "\", \"";
3476 Result += MethodTypeString;
3477 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003478 }
Steve Naroff621edce2009-04-29 16:37:50 +00003479 Result += "\t }\n};\n";
3480 }
Mike Stump1eb44332009-09-09 15:08:12 +00003481
Steve Naroff621edce2009-04-29 16:37:50 +00003482 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003483 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3484 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003485 if (NumMethods > 0) {
3486 /* struct _objc_protocol_method_list {
3487 int protocol_method_count;
3488 struct protocol_methods protocols[];
3489 }
3490 */
3491 Result += "\nstatic struct {\n";
3492 Result += "\tint protocol_method_count;\n";
3493 Result += "\tstruct _protocol_methods protocol_methods[";
3494 Result += utostr(NumMethods);
3495 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3496 Result += PDecl->getNameAsString();
3497 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3498 "{\n\t";
3499 Result += utostr(NumMethods);
3500 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003501
Steve Naroff621edce2009-04-29 16:37:50 +00003502 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003503 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003504 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003505 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003506 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003507 Result += "\t ,{{(struct objc_selector *)\"";
3508 else
3509 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003510 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003511 std::string MethodTypeString;
3512 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3513 Result += "\", \"";
3514 Result += MethodTypeString;
3515 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003516 }
Steve Naroff621edce2009-04-29 16:37:50 +00003517 Result += "\t }\n};\n";
3518 }
3519
3520 // Output:
3521 /* struct _objc_protocol {
3522 // Objective-C 1.0 extensions
3523 struct _objc_protocol_extension *isa;
3524 char *protocol_name;
3525 struct _objc_protocol **protocol_list;
3526 struct _objc_protocol_method_list *instance_methods;
3527 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003528 };
Steve Naroff621edce2009-04-29 16:37:50 +00003529 */
3530 static bool objc_protocol = false;
3531 if (!objc_protocol) {
3532 Result += "\nstruct _objc_protocol {\n";
3533 Result += "\tstruct _objc_protocol_extension *isa;\n";
3534 Result += "\tchar *protocol_name;\n";
3535 Result += "\tstruct _objc_protocol **protocol_list;\n";
3536 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3537 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003538 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003539
Steve Naroff621edce2009-04-29 16:37:50 +00003540 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003541 }
Mike Stump1eb44332009-09-09 15:08:12 +00003542
Steve Naroff621edce2009-04-29 16:37:50 +00003543 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3544 Result += PDecl->getNameAsString();
3545 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3546 "{\n\t0, \"";
3547 Result += PDecl->getNameAsString();
3548 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003549 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003550 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3551 Result += PDecl->getNameAsString();
3552 Result += ", ";
3553 }
3554 else
3555 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003556 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003557 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3558 Result += PDecl->getNameAsString();
3559 Result += "\n";
3560 }
3561 else
3562 Result += "0\n";
3563 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003564
Steve Naroff621edce2009-04-29 16:37:50 +00003565 // Mark this protocol as having been generated.
3566 if (!ObjCSynthesizedProtocols.insert(PDecl))
3567 assert(false && "protocol already synthesized");
3568
3569}
3570
3571void RewriteObjC::
3572RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003573 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003574 std::string &Result) {
3575 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003576
Steve Naroff621edce2009-04-29 16:37:50 +00003577 for (unsigned i = 0; i != Protocols.size(); i++)
3578 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3579
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003580 // Output the top lovel protocol meta-data for the class.
3581 /* struct _objc_protocol_list {
3582 struct _objc_protocol_list *next;
3583 int protocol_count;
3584 struct _objc_protocol *class_protocols[];
3585 }
3586 */
3587 Result += "\nstatic struct {\n";
3588 Result += "\tstruct _objc_protocol_list *next;\n";
3589 Result += "\tint protocol_count;\n";
3590 Result += "\tstruct _objc_protocol *class_protocols[";
3591 Result += utostr(Protocols.size());
3592 Result += "];\n} _OBJC_";
3593 Result += prefix;
3594 Result += "_PROTOCOLS_";
3595 Result += ClassName;
3596 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3597 "{\n\t0, ";
3598 Result += utostr(Protocols.size());
3599 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003600
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003601 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003602 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003603 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003604
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003605 for (unsigned i = 1; i != Protocols.size(); i++) {
3606 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003607 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003608 Result += "\n";
3609 }
3610 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003611}
3612
Steve Naroff621edce2009-04-29 16:37:50 +00003613
Mike Stump1eb44332009-09-09 15:08:12 +00003614/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003615/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003616void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003617 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003618 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003619 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003620 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003621 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003622 CDecl = CDecl->getNextClassCategory())
3623 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3624 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003625
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003626 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003627 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003628 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003629
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003630 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003631 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003632 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003633
3634 // If any of our property implementations have associated getters or
3635 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003636 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3637 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003638 Prop != PropEnd; ++Prop) {
3639 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3640 continue;
3641 if (!(*Prop)->getPropertyIvarDecl())
3642 continue;
3643 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3644 if (!PD)
3645 continue;
3646 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3647 InstanceMethods.push_back(Getter);
3648 if (PD->isReadOnly())
3649 continue;
3650 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3651 InstanceMethods.push_back(Setter);
3652 }
3653 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003654 true, "CATEGORY_", FullCategoryName.c_str(),
3655 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003656
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003657 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003658 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003659 false, "CATEGORY_", FullCategoryName.c_str(),
3660 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003661
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003662 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003663 // Null CDecl is case of a category implementation with no category interface
3664 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003665 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003666 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003667 /* struct _objc_category {
3668 char *category_name;
3669 char *class_name;
3670 struct _objc_method_list *instance_methods;
3671 struct _objc_method_list *class_methods;
3672 struct _objc_protocol_list *protocols;
3673 // Objective-C 1.0 extensions
3674 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003675 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003676 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003677 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003678 */
Mike Stump1eb44332009-09-09 15:08:12 +00003679
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003680 static bool objc_category = false;
3681 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003682 Result += "\nstruct _objc_category {\n";
3683 Result += "\tchar *category_name;\n";
3684 Result += "\tchar *class_name;\n";
3685 Result += "\tstruct _objc_method_list *instance_methods;\n";
3686 Result += "\tstruct _objc_method_list *class_methods;\n";
3687 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003688 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003689 Result += "\tstruct _objc_property_list *instance_properties;\n";
3690 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003691 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003692 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003693 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3694 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003695 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003696 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003697 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003698 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003699 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003700
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003701 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003702 Result += "\t, (struct _objc_method_list *)"
3703 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3704 Result += FullCategoryName;
3705 Result += "\n";
3706 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003707 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003708 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003709 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003710 Result += "\t, (struct _objc_method_list *)"
3711 "&_OBJC_CATEGORY_CLASS_METHODS_";
3712 Result += FullCategoryName;
3713 Result += "\n";
3714 }
3715 else
3716 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003717
Chris Lattnercafeb352009-02-20 18:18:36 +00003718 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003719 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003720 Result += FullCategoryName;
3721 Result += "\n";
3722 }
3723 else
3724 Result += "\t, 0\n";
3725 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003726}
3727
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003728/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3729/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003730void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003731 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003732 if (ivar->isBitField()) {
3733 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3734 // place all bitfields at offset 0.
3735 Result += "0";
3736 } else {
3737 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003738 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003739 if (LangOpts.Microsoft)
3740 Result += "_IMPL";
3741 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003742 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003743 Result += ")";
3744 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003745}
3746
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003747//===----------------------------------------------------------------------===//
3748// Meta Data Emission
3749//===----------------------------------------------------------------------===//
3750
Steve Naroffb29b4272008-04-14 22:03:09 +00003751void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003752 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003753 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003754
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003755 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003756 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003757 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003758 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003759 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003760 }
Mike Stump1eb44332009-09-09 15:08:12 +00003761
Chris Lattnerbe6df082007-12-12 07:56:42 +00003762 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003763 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003764 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003765 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003766 if (NumIvars > 0) {
3767 static bool objc_ivar = false;
3768 if (!objc_ivar) {
3769 /* struct _objc_ivar {
3770 char *ivar_name;
3771 char *ivar_type;
3772 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003773 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003774 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003775 Result += "\nstruct _objc_ivar {\n";
3776 Result += "\tchar *ivar_name;\n";
3777 Result += "\tchar *ivar_type;\n";
3778 Result += "\tint ivar_offset;\n";
3779 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003780
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003781 objc_ivar = true;
3782 }
3783
Steve Naroff946a6932008-03-11 00:12:29 +00003784 /* struct {
3785 int ivar_count;
3786 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003787 };
Steve Naroff946a6932008-03-11 00:12:29 +00003788 */
Mike Stump1eb44332009-09-09 15:08:12 +00003789 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003790 Result += "\tint ivar_count;\n";
3791 Result += "\tstruct _objc_ivar ivar_list[";
3792 Result += utostr(NumIvars);
3793 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003794 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003795 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003796 "{\n\t";
3797 Result += utostr(NumIvars);
3798 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003799
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003800 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003801 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003802 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003803 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003804 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003805 IV != IVEnd; ++IV)
3806 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003807 IVI = IDecl->ivar_begin();
3808 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003809 } else {
3810 IVI = CDecl->ivar_begin();
3811 IVE = CDecl->ivar_end();
3812 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003813 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003814 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003815 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003816 std::string TmpString, StrEncoding;
3817 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3818 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003819 Result += StrEncoding;
3820 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003821 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003822 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003823 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003824 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003825 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003826 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003827 std::string TmpString, StrEncoding;
3828 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3829 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003830 Result += StrEncoding;
3831 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003832 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003833 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003834 }
Mike Stump1eb44332009-09-09 15:08:12 +00003835
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003836 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003837 }
Mike Stump1eb44332009-09-09 15:08:12 +00003838
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003839 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003840 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003841 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003842
3843 // If any of our property implementations have associated getters or
3844 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003845 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3846 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003847 Prop != PropEnd; ++Prop) {
3848 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3849 continue;
3850 if (!(*Prop)->getPropertyIvarDecl())
3851 continue;
3852 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3853 if (!PD)
3854 continue;
3855 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003856 if (!Getter->isDefined())
3857 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003858 if (PD->isReadOnly())
3859 continue;
3860 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003861 if (!Setter->isDefined())
3862 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003863 }
3864 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003865 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003866
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003867 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003868 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003869 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003870
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003871 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003872 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003873 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003874
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003875 // Declaration of class/meta-class metadata
3876 /* struct _objc_class {
3877 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003878 const char *super_class_name;
3879 char *name;
3880 long version;
3881 long info;
3882 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003883 struct _objc_ivar_list *ivars;
3884 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003885 struct objc_cache *cache;
3886 struct objc_protocol_list *protocols;
3887 const char *ivar_layout;
3888 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003889 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003890 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003891 static bool objc_class = false;
3892 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003893 Result += "\nstruct _objc_class {\n";
3894 Result += "\tstruct _objc_class *isa;\n";
3895 Result += "\tconst char *super_class_name;\n";
3896 Result += "\tchar *name;\n";
3897 Result += "\tlong version;\n";
3898 Result += "\tlong info;\n";
3899 Result += "\tlong instance_size;\n";
3900 Result += "\tstruct _objc_ivar_list *ivars;\n";
3901 Result += "\tstruct _objc_method_list *methods;\n";
3902 Result += "\tstruct objc_cache *cache;\n";
3903 Result += "\tstruct _objc_protocol_list *protocols;\n";
3904 Result += "\tconst char *ivar_layout;\n";
3905 Result += "\tstruct _objc_class_ext *ext;\n";
3906 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003907 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003908 }
Mike Stump1eb44332009-09-09 15:08:12 +00003909
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003910 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003911 ObjCInterfaceDecl *RootClass = 0;
3912 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003913 while (SuperClass) {
3914 RootClass = SuperClass;
3915 SuperClass = SuperClass->getSuperClass();
3916 }
3917 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003918
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003919 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003920 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003921 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003922 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003923 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003924 Result += "\"";
3925
3926 if (SuperClass) {
3927 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003928 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003929 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003930 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003931 Result += "\"";
3932 }
3933 else {
3934 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003935 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003936 Result += "\"";
3937 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003938 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003939 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003940 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003941 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003942 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003943 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003944 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003945 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003946 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003947 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003948 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003949 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003950 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003951 Result += ",0,0\n";
3952 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003953 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003954 Result += "\t,0,0,0,0\n";
3955 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003956
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003957 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003958 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003959 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003960 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003961 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003962 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003963 if (SuperClass) {
3964 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003965 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003966 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003967 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003968 Result += "\"";
3969 }
3970 else {
3971 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003972 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003973 Result += "\"";
3974 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003975 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003976 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003977 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003978 Result += ",0";
3979 else {
3980 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003981 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003982 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003983 if (LangOpts.Microsoft)
3984 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003985 Result += ")";
3986 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003987 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003988 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003989 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003990 Result += "\n\t";
3991 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003992 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003993 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003994 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003995 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003996 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003997 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003998 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003999 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004000 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00004001 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004002 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004003 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004004 Result += ", 0,0\n";
4005 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004006 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004007 Result += ",0,0,0\n";
4008 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004009}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004010
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004011/// RewriteImplementations - This routine rewrites all method implementations
4012/// and emits meta-data.
4013
Steve Narofface66252008-11-13 20:07:04 +00004014void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004015 int ClsDefCount = ClassImplementation.size();
4016 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004018 // Rewrite implemented methods
4019 for (int i = 0; i < ClsDefCount; i++)
4020 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004021
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004022 for (int i = 0; i < CatDefCount; i++)
4023 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004024}
Mike Stump1eb44332009-09-09 15:08:12 +00004025
Steve Narofface66252008-11-13 20:07:04 +00004026void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4027 int ClsDefCount = ClassImplementation.size();
4028 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004029
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004030 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004031 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004032 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004033
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004034 // For each implemented category, write out all its meta data.
4035 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004036 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004037
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004038 // Write objc_symtab metadata
4039 /*
4040 struct _objc_symtab
4041 {
4042 long sel_ref_cnt;
4043 SEL *refs;
4044 short cls_def_cnt;
4045 short cat_def_cnt;
4046 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004047 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004048 */
Mike Stump1eb44332009-09-09 15:08:12 +00004049
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004050 Result += "\nstruct _objc_symtab {\n";
4051 Result += "\tlong sel_ref_cnt;\n";
4052 Result += "\tSEL *refs;\n";
4053 Result += "\tshort cls_def_cnt;\n";
4054 Result += "\tshort cat_def_cnt;\n";
4055 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4056 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004057
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004058 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004059 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004060 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004061 + ", " + utostr(CatDefCount) + "\n";
4062 for (int i = 0; i < ClsDefCount; i++) {
4063 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004064 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004065 Result += "\n";
4066 }
Mike Stump1eb44332009-09-09 15:08:12 +00004067
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004068 for (int i = 0; i < CatDefCount; i++) {
4069 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004070 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004071 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004072 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004073 Result += "\n";
4074 }
Mike Stump1eb44332009-09-09 15:08:12 +00004075
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004076 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004077
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004078 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004079
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004080 /*
4081 struct _objc_module {
4082 long version;
4083 long size;
4084 const char *name;
4085 struct _objc_symtab *symtab;
4086 }
4087 */
Mike Stump1eb44332009-09-09 15:08:12 +00004088
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004089 Result += "\nstruct _objc_module {\n";
4090 Result += "\tlong version;\n";
4091 Result += "\tlong size;\n";
4092 Result += "\tconst char *name;\n";
4093 Result += "\tstruct _objc_symtab *symtab;\n";
4094 Result += "};\n\n";
4095 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004096 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004097 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004098 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004099 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004100
4101 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004102 if (ProtocolExprDecls.size()) {
4103 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4104 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004105 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004106 E = ProtocolExprDecls.end(); I != E; ++I) {
4107 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4108 Result += (*I)->getNameAsString();
4109 Result += " = &_OBJC_PROTOCOL_";
4110 Result += (*I)->getNameAsString();
4111 Result += ";\n";
4112 }
4113 Result += "#pragma data_seg(pop)\n\n";
4114 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004115 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004116 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004117 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4118 Result += "&_OBJC_MODULES;\n";
4119 Result += "#pragma data_seg(pop)\n\n";
4120 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004121}
Chris Lattner311ff022007-10-16 22:36:42 +00004122
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004123void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4124 const std::string &Name,
4125 ValueDecl *VD) {
4126 assert(BlockByRefDeclNo.count(VD) &&
4127 "RewriteByRefString: ByRef decl missing");
4128 ResultStr += "struct __Block_byref_" + Name +
4129 "_" + utostr(BlockByRefDeclNo[VD]) ;
4130}
4131
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004132static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4133 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4134 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4135 return false;
4136}
4137
Steve Naroff54055232008-10-27 17:20:55 +00004138std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004139 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004140 std::string Tag) {
4141 const FunctionType *AFT = CE->getFunctionType();
4142 QualType RT = AFT->getResultType();
4143 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004144 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004145 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004146
Steve Naroff54055232008-10-27 17:20:55 +00004147 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004148
Douglas Gregor72564e72009-02-26 23:50:07 +00004149 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004150 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004151 // block (to reference imported block decl refs).
4152 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004153 } else if (BD->param_empty()) {
4154 S += "(" + StructRef + " *__cself)";
4155 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004156 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004157 assert(FT && "SynthesizeBlockFunc: No function proto");
4158 S += '(';
4159 // first add the implicit argument.
4160 S += StructRef + " *__cself, ";
4161 std::string ParamStr;
4162 for (BlockDecl::param_iterator AI = BD->param_begin(),
4163 E = BD->param_end(); AI != E; ++AI) {
4164 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004165 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004166 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004167 if (convertBlockPointerToFunctionPointer(QT))
4168 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004169 else
4170 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004171 S += ParamStr;
4172 }
4173 if (FT->isVariadic()) {
4174 if (!BD->param_empty()) S += ", ";
4175 S += "...";
4176 }
4177 S += ')';
4178 }
4179 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004180
Steve Naroff54055232008-10-27 17:20:55 +00004181 // Create local declarations to avoid rewriting all closure decl ref exprs.
4182 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004183 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004184 E = BlockByRefDecls.end(); I != E; ++I) {
4185 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004186 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004187 std::string TypeString;
4188 RewriteByRefString(TypeString, Name, (*I));
4189 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004190 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004191 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004192 }
Steve Naroff54055232008-10-27 17:20:55 +00004193 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004194 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004195 E = BlockByCopyDecls.end(); I != E; ++I) {
4196 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004197 // Handle nested closure invocation. For example:
4198 //
4199 // void (^myImportedClosure)(void);
4200 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004201 //
Steve Naroff54055232008-10-27 17:20:55 +00004202 // void (^anotherClosure)(void);
4203 // anotherClosure = ^(void) {
4204 // myImportedClosure(); // import and invoke the closure
4205 // };
4206 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004207 if (isTopLevelBlockPointerType((*I)->getType())) {
4208 RewriteBlockPointerTypeVariable(S, (*I));
4209 S += " = (";
4210 RewriteBlockPointerType(S, (*I)->getType());
4211 S += ")";
4212 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4213 }
4214 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004215 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004216 QualType QT = (*I)->getType();
4217 if (HasLocalVariableExternalStorage(*I))
4218 QT = Context->getPointerType(QT);
4219 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004220 S += Name + " = __cself->" +
4221 (*I)->getNameAsString() + "; // bound by copy\n";
4222 }
Steve Naroff54055232008-10-27 17:20:55 +00004223 }
4224 std::string RewrittenStr = RewrittenBlockExprs[CE];
4225 const char *cstr = RewrittenStr.c_str();
4226 while (*cstr++ != '{') ;
4227 S += cstr;
4228 S += "\n";
4229 return S;
4230}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004231
Steve Naroff54055232008-10-27 17:20:55 +00004232std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004233 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004234 std::string Tag) {
4235 std::string StructRef = "struct " + Tag;
4236 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004237
Steve Naroff54055232008-10-27 17:20:55 +00004238 S += funcName;
4239 S += "_block_copy_" + utostr(i);
4240 S += "(" + StructRef;
4241 S += "*dst, " + StructRef;
4242 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004243 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004244 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004245 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004246 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004247 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004248 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004249 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004250 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004251 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004252 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004253 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004254 S += "}\n";
4255
Steve Naroff54055232008-10-27 17:20:55 +00004256 S += "\nstatic void __";
4257 S += funcName;
4258 S += "_block_dispose_" + utostr(i);
4259 S += "(" + StructRef;
4260 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004261 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004262 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004263 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004264 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004265 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004266 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004267 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004268 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004269 }
Mike Stump1eb44332009-09-09 15:08:12 +00004270 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004271 return S;
4272}
4273
Steve Naroff01aec112009-12-06 21:14:13 +00004274std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4275 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004276 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004277 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004278
Steve Naroff54055232008-10-27 17:20:55 +00004279 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004280 S += " struct " + Desc;
4281 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004282
Steve Naroff01aec112009-12-06 21:14:13 +00004283 Constructor += "(void *fp, "; // Invoke function pointer.
4284 Constructor += "struct " + Desc; // Descriptor pointer.
4285 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004286
Steve Naroff54055232008-10-27 17:20:55 +00004287 if (BlockDeclRefs.size()) {
4288 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004289 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004290 E = BlockByCopyDecls.end(); I != E; ++I) {
4291 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004292 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004293 std::string ArgName = "_" + FieldName;
4294 // Handle nested closure invocation. For example:
4295 //
4296 // void (^myImportedBlock)(void);
4297 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004298 //
Steve Naroff54055232008-10-27 17:20:55 +00004299 // void (^anotherBlock)(void);
4300 // anotherBlock = ^(void) {
4301 // myImportedBlock(); // import and invoke the closure
4302 // };
4303 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004304 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004305 S += "struct __block_impl *";
4306 Constructor += ", void *" + ArgName;
4307 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004308 QualType QT = (*I)->getType();
4309 if (HasLocalVariableExternalStorage(*I))
4310 QT = Context->getPointerType(QT);
4311 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4312 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004313 Constructor += ", " + ArgName;
4314 }
4315 S += FieldName + ";\n";
4316 }
4317 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004318 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004319 E = BlockByRefDecls.end(); I != E; ++I) {
4320 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004321 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004322 std::string ArgName = "_" + FieldName;
4323 // Handle nested closure invocation. For example:
4324 //
4325 // void (^myImportedBlock)(void);
4326 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004327 //
Steve Naroff54055232008-10-27 17:20:55 +00004328 // void (^anotherBlock)(void);
4329 // anotherBlock = ^(void) {
4330 // myImportedBlock(); // import and invoke the closure
4331 // };
4332 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004333 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004334 S += "struct __block_impl *";
4335 Constructor += ", void *" + ArgName;
4336 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004337 std::string TypeString;
4338 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004339 TypeString += " *";
4340 FieldName = TypeString + FieldName;
4341 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004342 Constructor += ", " + ArgName;
4343 }
4344 S += FieldName + "; // by ref\n";
4345 }
4346 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004347 Constructor += ", int flags=0)";
4348 // Initialize all "by copy" arguments.
4349 bool firsTime = true;
4350 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4351 E = BlockByCopyDecls.end(); I != E; ++I) {
4352 std::string Name = (*I)->getNameAsString();
4353 if (firsTime) {
4354 Constructor += " : ";
4355 firsTime = false;
4356 }
4357 else
4358 Constructor += ", ";
4359 if (isTopLevelBlockPointerType((*I)->getType()))
4360 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4361 else
4362 Constructor += Name + "(_" + Name + ")";
4363 }
4364 // Initialize all "by ref" arguments.
4365 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4366 E = BlockByRefDecls.end(); I != E; ++I) {
4367 std::string Name = (*I)->getNameAsString();
4368 if (firsTime) {
4369 Constructor += " : ";
4370 firsTime = false;
4371 }
4372 else
4373 Constructor += ", ";
4374 if (isTopLevelBlockPointerType((*I)->getType()))
4375 Constructor += Name + "((struct __block_impl *)_"
4376 + Name + "->__forwarding)";
4377 else
4378 Constructor += Name + "(_" + Name + "->__forwarding)";
4379 }
4380
4381 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004382 if (GlobalVarDecl)
4383 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4384 else
4385 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004386 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004387
Steve Naroff01aec112009-12-06 21:14:13 +00004388 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004389 } else {
4390 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004391 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004392 if (GlobalVarDecl)
4393 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4394 else
4395 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004396 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4397 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004398 }
4399 Constructor += " ";
4400 Constructor += "}\n";
4401 S += Constructor;
4402 S += "};\n";
4403 return S;
4404}
4405
Steve Naroff01aec112009-12-06 21:14:13 +00004406std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4407 std::string ImplTag, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004408 llvm::StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004409 unsigned hasCopy) {
4410 std::string S = "\nstatic struct " + DescTag;
4411
4412 S += " {\n unsigned long reserved;\n";
4413 S += " unsigned long Block_size;\n";
4414 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004415 S += " void (*copy)(struct ";
4416 S += ImplTag; S += "*, struct ";
4417 S += ImplTag; S += "*);\n";
4418
4419 S += " void (*dispose)(struct ";
4420 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004421 }
4422 S += "} ";
4423
4424 S += DescTag + "_DATA = { 0, sizeof(struct ";
4425 S += ImplTag + ")";
4426 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004427 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4428 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004429 }
4430 S += "};\n";
4431 return S;
4432}
4433
Steve Naroff54055232008-10-27 17:20:55 +00004434void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004435 llvm::StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004436 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004437 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004438 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004439 bool RewriteSC = (GlobalVarDecl &&
4440 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004441 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004442 GlobalVarDecl->getType().getCVRQualifiers());
4443 if (RewriteSC) {
4444 std::string SC(" void __");
4445 SC += GlobalVarDecl->getNameAsString();
4446 SC += "() {}";
4447 InsertText(FunLocStart, SC);
4448 }
4449
Steve Naroff54055232008-10-27 17:20:55 +00004450 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004451 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4452 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004453 // Need to copy-in the inner copied-in variables not actually used in this
4454 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004455 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4456 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4457 ValueDecl *VD = Exp->getDecl();
4458 BlockDeclRefs.push_back(Exp);
4459 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4460 BlockByCopyDeclsPtrSet.insert(VD);
4461 BlockByCopyDecls.push_back(VD);
4462 }
4463 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4464 BlockByRefDeclsPtrSet.insert(VD);
4465 BlockByRefDecls.push_back(VD);
4466 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004467 // imported objects in the inner blocks not used in the outer
4468 // blocks must be copied/disposed in the outer block as well.
4469 if (Exp->isByRef() ||
4470 VD->getType()->isObjCObjectPointerType() ||
4471 VD->getType()->isBlockPointerType())
4472 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004473 }
Steve Naroff54055232008-10-27 17:20:55 +00004474
Daniel Dunbar4087f272010-08-17 22:39:59 +00004475 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4476 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004477
Steve Naroff01aec112009-12-06 21:14:13 +00004478 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004479
Benjamin Kramerd999b372010-02-14 14:14:16 +00004480 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004481
Steve Naroff01aec112009-12-06 21:14:13 +00004482 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004483
Benjamin Kramerd999b372010-02-14 14:14:16 +00004484 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004485
4486 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004487 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004488 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004489 }
Steve Naroff01aec112009-12-06 21:14:13 +00004490 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4491 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004492 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004493
Steve Naroff54055232008-10-27 17:20:55 +00004494 BlockDeclRefs.clear();
4495 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004496 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004497 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004498 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004499 ImportedBlockDecls.clear();
4500 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004501 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004502 // Must insert any 'const/volatile/static here. Since it has been
4503 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004504 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004505 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004506 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004507 if (GlobalVarDecl->getType().isConstQualified())
4508 SC += "const ";
4509 if (GlobalVarDecl->getType().isVolatileQualified())
4510 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004511 if (GlobalVarDecl->getType().isRestrictQualified())
4512 SC += "restrict ";
4513 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004514 }
4515
Steve Naroff54055232008-10-27 17:20:55 +00004516 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004517 InnerDeclRefsCount.clear();
4518 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004519 RewrittenBlockExprs.clear();
4520}
4521
4522void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4523 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004524 llvm::StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004525
Steve Naroff54055232008-10-27 17:20:55 +00004526 SynthesizeBlockLiterals(FunLocStart, FuncName);
4527}
4528
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004529static void BuildUniqueMethodName(std::string &Name,
4530 ObjCMethodDecl *MD) {
4531 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004532 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004533 Name += "__" + MD->getSelector().getAsString();
4534 // Convert colons to underscores.
4535 std::string::size_type loc = 0;
4536 while ((loc = Name.find(":", loc)) != std::string::npos)
4537 Name.replace(loc, 1, "_");
4538}
4539
Steve Naroff54055232008-10-27 17:20:55 +00004540void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004541 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4542 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004543 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004544 std::string FuncName;
4545 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004546 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004547}
4548
4549void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4550 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4551 CI != E; ++CI)
4552 if (*CI) {
4553 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4554 GetBlockDeclRefExprs(CBE->getBody());
4555 else
4556 GetBlockDeclRefExprs(*CI);
4557 }
4558 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004559 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004560 // FIXME: Handle enums.
4561 if (!isa<FunctionDecl>(CDRE->getDecl()))
4562 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004563 }
4564 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4565 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4566 BlockDeclRefExpr *BDRE =
4567 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4568 DRE->getLocation(), false);
4569 BlockDeclRefs.push_back(BDRE);
4570 }
4571
Steve Naroff54055232008-10-27 17:20:55 +00004572 return;
4573}
4574
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004575void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4576 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004577 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004578 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4579 CI != E; ++CI)
4580 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004581 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4582 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004583 GetInnerBlockDeclRefExprs(CBE->getBody(),
4584 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004585 InnerContexts);
4586 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004587 else
4588 GetInnerBlockDeclRefExprs(*CI,
4589 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004590 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004591
4592 }
4593 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004594 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004595 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004596 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004597 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004598 }
4599 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4600 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4601 if (Var->isFunctionOrMethodVarDecl())
4602 ImportedLocalExternalDecls.insert(Var);
4603 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004604
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004605 return;
4606}
4607
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004608/// convertFunctionTypeOfBlocks - This routine converts a function type
4609/// whose result type may be a block pointer or whose argument type(s)
4610/// might be block pointers to an equivalent funtion type replacing
4611/// all block pointers to function pointers.
4612QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4613 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4614 // FTP will be null for closures that don't take arguments.
4615 // Generate a funky cast.
4616 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004617 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004618 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004619
4620 if (FTP) {
4621 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4622 E = FTP->arg_type_end(); I && (I != E); ++I) {
4623 QualType t = *I;
4624 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004625 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004626 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004627 ArgTypes.push_back(t);
4628 }
4629 }
4630 QualType FuncType;
4631 // FIXME. Does this work if block takes no argument but has a return type
4632 // which is of block type?
4633 if (HasBlockType)
4634 FuncType = Context->getFunctionType(Res,
4635 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4636 false, false, 0, 0, FunctionType::ExtInfo());
4637 else FuncType = QualType(FT, 0);
4638 return FuncType;
4639}
4640
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004641Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004642 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004643 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004644
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004645 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004646 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004647 } else if (const BlockDeclRefExpr *CDRE =
4648 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004649 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004650 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004651 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004652 }
4653 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4654 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4655 }
4656 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4657 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4658 else if (const ConditionalOperator *CEXPR =
4659 dyn_cast<ConditionalOperator>(BlockExp)) {
4660 Expr *LHSExp = CEXPR->getLHS();
4661 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4662 Expr *RHSExp = CEXPR->getRHS();
4663 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4664 Expr *CONDExp = CEXPR->getCond();
4665 ConditionalOperator *CondExpr =
4666 new (Context) ConditionalOperator(CONDExp,
4667 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004668 SourceLocation(), cast<Expr>(RHSStmt),
4669 (Expr*)0,
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004670 Exp->getType());
4671 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004672 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4673 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004674 } else {
4675 assert(1 && "RewriteBlockClass: Bad type");
4676 }
4677 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004678 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004679 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004680 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004681 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004682
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004683 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004684 SourceLocation(),
4685 &Context->Idents.get("__block_impl"));
4686 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004687
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004688 // Generate a funky cast.
4689 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004690
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004691 // Push the block argument type.
4692 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004693 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004694 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004695 E = FTP->arg_type_end(); I && (I != E); ++I) {
4696 QualType t = *I;
4697 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004698 if (!convertBlockPointerToFunctionPointer(t))
4699 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004700 ArgTypes.push_back(t);
4701 }
Steve Naroff54055232008-10-27 17:20:55 +00004702 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004703 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004704 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004705 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4706 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00004707 FunctionType::ExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00004708
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004709 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004710
John McCall9d125032010-01-15 18:39:57 +00004711 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004712 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004713 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004714 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004715 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4716 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004717 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004718
Douglas Gregor44b43212008-12-11 16:49:14 +00004719 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004720 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004721 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004722 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4723 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004724
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004725
John McCall9d125032010-01-15 18:39:57 +00004726 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004727 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004728 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004729
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004730 llvm::SmallVector<Expr*, 8> BlkExprs;
4731 // Add the implicit argument.
4732 BlkExprs.push_back(BlkCast);
4733 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004734 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004735 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004736 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004737 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004738 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4739 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004740 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004741 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004742}
4743
Steve Naroff621edce2009-04-29 16:37:50 +00004744// We need to return the rewritten expression to handle cases where the
4745// BlockDeclRefExpr is embedded in another expression being rewritten.
4746// For example:
4747//
4748// int main() {
4749// __block Foo *f;
4750// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004751//
Steve Naroff621edce2009-04-29 16:37:50 +00004752// void (^myblock)() = ^() {
4753// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4754// i = 77;
4755// };
4756//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004757Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004758 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004759 // for each DeclRefExp where BYREFVAR is name of the variable.
4760 ValueDecl *VD;
4761 bool isArrow = true;
4762 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4763 VD = BDRE->getDecl();
4764 else {
4765 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4766 isArrow = false;
4767 }
4768
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004769 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4770 &Context->Idents.get("__forwarding"),
4771 Context->VoidPtrTy, 0,
4772 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004773 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4774 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004775 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004776
Daniel Dunbar4087f272010-08-17 22:39:59 +00004777 llvm::StringRef Name = VD->getName();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004778 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4779 &Context->Idents.get(Name),
4780 Context->VoidPtrTy, 0,
4781 /*BitWidth=*/0, /*Mutable=*/true);
4782 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004783 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004784
4785
4786
Steve Naroffdf8570d2009-02-02 17:19:26 +00004787 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004788 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4789 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004790 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004791 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004792}
4793
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004794// Rewrites the imported local variable V with external storage
4795// (static, extern, etc.) as *V
4796//
4797Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4798 ValueDecl *VD = DRE->getDecl();
4799 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4800 if (!ImportedLocalExternalDecls.count(Var))
4801 return DRE;
John McCall2de56d12010-08-25 11:45:40 +00004802 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref,
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004803 DRE->getType(), DRE->getLocation());
4804 // Need parens to enforce precedence.
4805 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4806 Exp);
4807 ReplaceStmt(DRE, PE);
4808 return PE;
4809}
4810
Steve Naroffb2f9e512008-11-03 23:29:32 +00004811void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4812 SourceLocation LocStart = CE->getLParenLoc();
4813 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004814
4815 // Need to avoid trying to rewrite synthesized casts.
4816 if (LocStart.isInvalid())
4817 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004818 // Need to avoid trying to rewrite casts contained in macros.
4819 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4820 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004821
Steve Naroff54055232008-10-27 17:20:55 +00004822 const char *startBuf = SM->getCharacterData(LocStart);
4823 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004824 QualType QT = CE->getType();
4825 const Type* TypePtr = QT->getAs<Type>();
4826 if (isa<TypeOfExprType>(TypePtr)) {
4827 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4828 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4829 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004830 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004831 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004832 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004833 return;
4834 }
Steve Naroff54055232008-10-27 17:20:55 +00004835 // advance the location to startArgList.
4836 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004837
Steve Naroff54055232008-10-27 17:20:55 +00004838 while (*argPtr++ && (argPtr < endBuf)) {
4839 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004840 case '^':
4841 // Replace the '^' with '*'.
4842 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004843 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004844 break;
Steve Naroff54055232008-10-27 17:20:55 +00004845 }
4846 }
4847 return;
4848}
4849
4850void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4851 SourceLocation DeclLoc = FD->getLocation();
4852 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004853
Steve Naroff54055232008-10-27 17:20:55 +00004854 // We have 1 or more arguments that have closure pointers.
4855 const char *startBuf = SM->getCharacterData(DeclLoc);
4856 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004857
Steve Naroff54055232008-10-27 17:20:55 +00004858 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004859
Steve Naroff54055232008-10-27 17:20:55 +00004860 parenCount++;
4861 // advance the location to startArgList.
4862 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4863 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004864
Steve Naroff54055232008-10-27 17:20:55 +00004865 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004866
Steve Naroff54055232008-10-27 17:20:55 +00004867 while (*argPtr++ && parenCount) {
4868 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004869 case '^':
4870 // Replace the '^' with '*'.
4871 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004872 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004873 break;
4874 case '(':
4875 parenCount++;
4876 break;
4877 case ')':
4878 parenCount--;
4879 break;
Steve Naroff54055232008-10-27 17:20:55 +00004880 }
4881 }
4882 return;
4883}
4884
4885bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004886 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004887 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004888 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004889 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004890 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004891 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004892 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004893 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004894 }
4895 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004896 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004897 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004898 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004899 return true;
4900 }
4901 return false;
4902}
4903
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004904bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4905 const FunctionProtoType *FTP;
4906 const PointerType *PT = QT->getAs<PointerType>();
4907 if (PT) {
4908 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4909 } else {
4910 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4911 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4912 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4913 }
4914 if (FTP) {
4915 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004916 E = FTP->arg_type_end(); I != E; ++I) {
4917 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004918 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004919 if ((*I)->isObjCObjectPointerType() &&
4920 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4921 return true;
4922 }
4923
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004924 }
4925 return false;
4926}
4927
Ted Kremenek8189cde2009-02-07 01:47:29 +00004928void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4929 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004930 const char *argPtr = strchr(Name, '(');
4931 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004932
Steve Naroff54055232008-10-27 17:20:55 +00004933 LParen = argPtr; // output the start.
4934 argPtr++; // skip past the left paren.
4935 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004936
Steve Naroff54055232008-10-27 17:20:55 +00004937 while (*argPtr && parenCount) {
4938 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004939 case '(': parenCount++; break;
4940 case ')': parenCount--; break;
4941 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004942 }
4943 if (parenCount) argPtr++;
4944 }
4945 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4946 RParen = argPtr; // output the end
4947}
4948
4949void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4950 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4951 RewriteBlockPointerFunctionArgs(FD);
4952 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004953 }
Steve Naroff54055232008-10-27 17:20:55 +00004954 // Handle Variables and Typedefs.
4955 SourceLocation DeclLoc = ND->getLocation();
4956 QualType DeclT;
4957 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4958 DeclT = VD->getType();
4959 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4960 DeclT = TDD->getUnderlyingType();
4961 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4962 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004963 else
Steve Naroff54055232008-10-27 17:20:55 +00004964 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004965
Steve Naroff54055232008-10-27 17:20:55 +00004966 const char *startBuf = SM->getCharacterData(DeclLoc);
4967 const char *endBuf = startBuf;
4968 // scan backward (from the decl location) for the end of the previous decl.
4969 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4970 startBuf--;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004971 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4972 std::string buf;
4973 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004974 // *startBuf != '^' if we are dealing with a pointer to function that
4975 // may take block argument types (which will be handled below).
4976 if (*startBuf == '^') {
4977 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004978 buf = '*';
4979 startBuf++;
4980 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004981 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004982 while (*startBuf != ')') {
4983 buf += *startBuf;
4984 startBuf++;
4985 OrigLength++;
4986 }
4987 buf += ')';
4988 OrigLength++;
4989
4990 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4991 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004992 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004993 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004994 DeclLoc = ND->getLocation();
4995 startBuf = SM->getCharacterData(DeclLoc);
4996 const char *argListBegin, *argListEnd;
4997 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4998 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004999 if (*argListBegin == '^')
5000 buf += '*';
5001 else if (*argListBegin == '<') {
5002 buf += "/*";
5003 buf += *argListBegin++;
5004 OrigLength++;;
5005 while (*argListBegin != '>') {
5006 buf += *argListBegin++;
5007 OrigLength++;
5008 }
5009 buf += *argListBegin;
5010 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005011 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005012 else
5013 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005014 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005015 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005016 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005017 buf += ')';
5018 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005019 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005020 ReplaceText(Start, OrigLength, buf);
5021
Steve Naroff54055232008-10-27 17:20:55 +00005022 return;
5023}
5024
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005025
5026/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5027/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5028/// struct Block_byref_id_object *src) {
5029/// _Block_object_assign (&_dest->object, _src->object,
5030/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5031/// [|BLOCK_FIELD_IS_WEAK]) // object
5032/// _Block_object_assign(&_dest->object, _src->object,
5033/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5034/// [|BLOCK_FIELD_IS_WEAK]) // block
5035/// }
5036/// And:
5037/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5038/// _Block_object_dispose(_src->object,
5039/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5040/// [|BLOCK_FIELD_IS_WEAK]) // object
5041/// _Block_object_dispose(_src->object,
5042/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5043/// [|BLOCK_FIELD_IS_WEAK]) // block
5044/// }
5045
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005046std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5047 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005048 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005049 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005050 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005051 CopyDestroyCache.insert(flag);
5052 S = "static void __Block_byref_id_object_copy_";
5053 S += utostr(flag);
5054 S += "(void *dst, void *src) {\n";
5055
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005056 // offset into the object pointer is computed as:
5057 // void * + void* + int + int + void* + void *
5058 unsigned IntSize =
5059 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5060 unsigned VoidPtrSize =
5061 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5062
5063 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
5064 S += " _Block_object_assign((char*)dst + ";
5065 S += utostr(offset);
5066 S += ", *(void * *) ((char*)src + ";
5067 S += utostr(offset);
5068 S += "), ";
5069 S += utostr(flag);
5070 S += ");\n}\n";
5071
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005072 S += "static void __Block_byref_id_object_dispose_";
5073 S += utostr(flag);
5074 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005075 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5076 S += utostr(offset);
5077 S += "), ";
5078 S += utostr(flag);
5079 S += ");\n}\n";
5080 return S;
5081}
5082
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005083/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5084/// the declaration into:
5085/// struct __Block_byref_ND {
5086/// void *__isa; // NULL for everything except __weak pointers
5087/// struct __Block_byref_ND *__forwarding;
5088/// int32_t __flags;
5089/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005090/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5091/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005092/// typex ND;
5093/// };
5094///
5095/// It then replaces declaration of ND variable with:
5096/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5097/// __size=sizeof(struct __Block_byref_ND),
5098/// ND=initializer-if-any};
5099///
5100///
5101void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005102 // Insert declaration for the function in which block literal is
5103 // used.
5104 if (CurFunctionDeclToDeclareForBlock)
5105 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005106 int flag = 0;
5107 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005108 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005109 if (DeclLoc.isInvalid())
5110 // If type location is missing, it is because of missing type (a warning).
5111 // Use variable's location which is good for this case.
5112 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005113 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005114 SourceLocation X = ND->getLocEnd();
5115 X = SM->getInstantiationLoc(X);
5116 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005117 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005118 std::string ByrefType;
5119 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005120 ByrefType += " {\n";
5121 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005122 RewriteByRefString(ByrefType, Name, ND);
5123 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005124 ByrefType += " int __flags;\n";
5125 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005126 // Add void *__Block_byref_id_object_copy;
5127 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005128 QualType Ty = ND->getType();
5129 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5130 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005131 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5132 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005133 }
5134
5135 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005136 ByrefType += " " + Name + ";\n";
5137 ByrefType += "};\n";
5138 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005139 SourceLocation FunLocStart;
5140 if (CurFunctionDef)
5141 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5142 else {
5143 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5144 FunLocStart = CurMethodDef->getLocStart();
5145 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005146 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005147 if (Ty.isObjCGCWeak()) {
5148 flag |= BLOCK_FIELD_IS_WEAK;
5149 isa = 1;
5150 }
5151
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005152 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005153 flag = BLOCK_BYREF_CALLER;
5154 QualType Ty = ND->getType();
5155 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5156 if (Ty->isBlockPointerType())
5157 flag |= BLOCK_FIELD_IS_BLOCK;
5158 else
5159 flag |= BLOCK_FIELD_IS_OBJECT;
5160 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005161 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005162 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005163 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005164
5165 // struct __Block_byref_ND ND =
5166 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5167 // initializer-if-any};
5168 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005169 unsigned flags = 0;
5170 if (HasCopyAndDispose)
5171 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005172 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005173 ByrefType.clear();
5174 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005175 std::string ForwardingCastType("(");
5176 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005177 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005178 ByrefType += " " + Name + " = {(void*)";
5179 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005180 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005181 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005182 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005183 ByrefType += "sizeof(";
5184 RewriteByRefString(ByrefType, Name, ND);
5185 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005186 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005187 ByrefType += ", __Block_byref_id_object_copy_";
5188 ByrefType += utostr(flag);
5189 ByrefType += ", __Block_byref_id_object_dispose_";
5190 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005191 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005192 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00005193 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005194 }
5195 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005196 SourceLocation startLoc;
5197 Expr *E = ND->getInit();
5198 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5199 startLoc = ECE->getLParenLoc();
5200 else
5201 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00005202 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005203 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005204 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005205 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005206 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005207 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005208 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005209 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005210 ByrefType += "sizeof(";
5211 RewriteByRefString(ByrefType, Name, ND);
5212 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005213 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005214 ByrefType += "__Block_byref_id_object_copy_";
5215 ByrefType += utostr(flag);
5216 ByrefType += ", __Block_byref_id_object_dispose_";
5217 ByrefType += utostr(flag);
5218 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005219 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005220 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005221
5222 // Complete the newly synthesized compound expression by inserting a right
5223 // curly brace before the end of the declaration.
5224 // FIXME: This approach avoids rewriting the initializer expression. It
5225 // also assumes there is only one declarator. For example, the following
5226 // isn't currently supported by this routine (in general):
5227 //
5228 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5229 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005230 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5231 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005232 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5233 SourceLocation semiLoc =
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005234 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005235
Benjamin Kramerd999b372010-02-14 14:14:16 +00005236 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005237 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005238 return;
5239}
5240
Mike Stump1eb44332009-09-09 15:08:12 +00005241void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005242 // Add initializers for any closure decl refs.
5243 GetBlockDeclRefExprs(Exp->getBody());
5244 if (BlockDeclRefs.size()) {
5245 // Unique all "by copy" declarations.
5246 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005247 if (!BlockDeclRefs[i]->isByRef()) {
5248 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5249 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5250 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5251 }
5252 }
Steve Naroff54055232008-10-27 17:20:55 +00005253 // Unique all "by ref" declarations.
5254 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5255 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005256 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5257 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5258 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5259 }
Steve Naroff54055232008-10-27 17:20:55 +00005260 }
5261 // Find any imported blocks...they will need special attention.
5262 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005263 if (BlockDeclRefs[i]->isByRef() ||
5264 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005265 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005266 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005267 }
5268}
5269
Daniel Dunbar4087f272010-08-17 22:39:59 +00005270FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005271 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005272 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00005273 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCalld931b082010-08-26 03:08:43 +00005274 ID, FType, 0, SC_Extern,
5275 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005276}
5277
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005278Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5279 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005280 Blocks.push_back(Exp);
5281
5282 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005283
5284 // Add inner imported variables now used in current block.
5285 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005286 if (!InnerBlockDeclRefs.empty()) {
5287 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5288 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5289 ValueDecl *VD = Exp->getDecl();
5290 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005291 // We need to save the copied-in variables in nested
5292 // blocks because it is needed at the end for some of the API generations.
5293 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005294 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5295 BlockDeclRefs.push_back(Exp);
5296 BlockByCopyDeclsPtrSet.insert(VD);
5297 BlockByCopyDecls.push_back(VD);
5298 }
5299 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5300 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5301 BlockDeclRefs.push_back(Exp);
5302 BlockByRefDeclsPtrSet.insert(VD);
5303 BlockByRefDecls.push_back(VD);
5304 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005305 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005306 // Find any imported blocks...they will need special attention.
5307 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5308 if (InnerBlockDeclRefs[i]->isByRef() ||
5309 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5310 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5311 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005312 }
5313 InnerDeclRefsCount.push_back(countOfInnerDecls);
5314
Steve Narofffa15fd92008-10-28 20:29:00 +00005315 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005316
Steve Narofffa15fd92008-10-28 20:29:00 +00005317 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005318 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005319 else if (CurMethodDef)
5320 BuildUniqueMethodName(FuncName, CurMethodDef);
5321 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005322 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005323
Steve Narofffa15fd92008-10-28 20:29:00 +00005324 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005325
Steve Narofffa15fd92008-10-28 20:29:00 +00005326 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5327 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005328
Steve Narofffa15fd92008-10-28 20:29:00 +00005329 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005330 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5331 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005332
5333 FunctionDecl *FD;
5334 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005335
Steve Narofffa15fd92008-10-28 20:29:00 +00005336 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005337 FD = SynthBlockInitFunctionDecl(Tag);
Ted Kremenek8189cde2009-02-07 01:47:29 +00005338 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005339
Steve Narofffa15fd92008-10-28 20:29:00 +00005340 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005341
Steve Narofffdc03722008-10-29 21:23:59 +00005342 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005343 FD = SynthBlockInitFunctionDecl(Func);
Ted Kremenek8189cde2009-02-07 01:47:29 +00005344 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5345 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005346 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005347 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005348 InitExprs.push_back(castExpr);
5349
Steve Naroff01aec112009-12-06 21:14:13 +00005350 // Initialize the block descriptor.
5351 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005352
Steve Naroff01aec112009-12-06 21:14:13 +00005353 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5354 &Context->Idents.get(DescData.c_str()),
5355 Context->VoidPtrTy, 0,
John McCalld931b082010-08-26 03:08:43 +00005356 SC_Static, SC_None);
Steve Naroff01aec112009-12-06 21:14:13 +00005357 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5358 new (Context) DeclRefExpr(NewVD,
5359 Context->VoidPtrTy, SourceLocation()),
John McCall2de56d12010-08-25 11:45:40 +00005360 UO_AddrOf,
Steve Naroff01aec112009-12-06 21:14:13 +00005361 Context->getPointerType(Context->VoidPtrTy),
5362 SourceLocation());
5363 InitExprs.push_back(DescRefExpr);
5364
Steve Narofffa15fd92008-10-28 20:29:00 +00005365 // Add initializers for any closure decl refs.
5366 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005367 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005368 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005369 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005370 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005371 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005372 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005373 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005374 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005375 if (HasLocalVariableExternalStorage(*I)) {
5376 QualType QT = (*I)->getType();
5377 QT = Context->getPointerType(QT);
John McCall2de56d12010-08-25 11:45:40 +00005378 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005379 SourceLocation());
5380 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005381 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005382 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005383 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005384 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005385 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005386 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005387 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005388 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005389 if (HasLocalVariableExternalStorage(*I)) {
5390 QualType QT = (*I)->getType();
5391 QT = Context->getPointerType(QT);
John McCall2de56d12010-08-25 11:45:40 +00005392 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005393 SourceLocation());
5394 }
5395
Steve Narofffa15fd92008-10-28 20:29:00 +00005396 }
Mike Stump1eb44332009-09-09 15:08:12 +00005397 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005398 }
5399 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005400 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005401 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005402 ValueDecl *ND = (*I);
5403 std::string Name(ND->getNameAsString());
5404 std::string RecName;
5405 RewriteByRefString(RecName, Name, ND);
5406 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5407 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005408 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005409 SourceLocation(), II);
5410 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5411 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5412
Daniel Dunbar4087f272010-08-17 22:39:59 +00005413 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005414 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005415 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005416 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00005417 SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005418 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005419 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005420 }
5421 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005422 if (ImportedBlockDecls.size()) {
5423 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5424 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005425 unsigned IntSize =
5426 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005427 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5428 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005429 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005430 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005431 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5432 FType, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005433 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005434 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00005435 SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005436 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005437 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005438 BlockDeclRefs.clear();
5439 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005440 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005441 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005442 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005443 ImportedBlockDecls.clear();
5444 return NewRep;
5445}
5446
5447//===----------------------------------------------------------------------===//
5448// Function Body / Expression rewriting
5449//===----------------------------------------------------------------------===//
5450
Steve Naroffc77a6362008-12-04 16:24:46 +00005451// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5452// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5453// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5454// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5455// Since the rewriter isn't capable of rewriting rewritten code, it's important
5456// we get this right.
5457void RewriteObjC::CollectPropertySetters(Stmt *S) {
5458 // Perform a bottom up traversal of all children.
5459 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5460 CI != E; ++CI)
5461 if (*CI)
5462 CollectPropertySetters(*CI);
5463
5464 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5465 if (BinOp->isAssignmentOp()) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005466 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()) ||
5467 isa<ObjCImplicitSetterGetterRefExpr>(BinOp->getLHS()))
5468 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005469 }
5470 }
5471}
5472
Steve Narofffa15fd92008-10-28 20:29:00 +00005473Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005474 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005475 isa<DoStmt>(S) || isa<ForStmt>(S))
5476 Stmts.push_back(S);
5477 else if (isa<ObjCForCollectionStmt>(S)) {
5478 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005479 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005480 }
Mike Stump1eb44332009-09-09 15:08:12 +00005481
Steve Narofffa15fd92008-10-28 20:29:00 +00005482 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005483
Steve Narofffa15fd92008-10-28 20:29:00 +00005484 // Perform a bottom up rewrite of all children.
5485 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5486 CI != E; ++CI)
5487 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005488 Stmt *newStmt;
5489 Stmt *S = (*CI);
5490 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5491 Expr *OldBase = IvarRefExpr->getBase();
5492 bool replaced = false;
5493 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5494 if (replaced) {
5495 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5496 ReplaceStmt(OldBase, IRE->getBase());
5497 else
5498 ReplaceStmt(S, newStmt);
5499 }
5500 }
5501 else
5502 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005503 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005504 *CI = newStmt;
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005505 // If dealing with an assignment with LHS being a property reference
5506 // expression, the entire assignment tree is rewritten into a property
5507 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5508 // RHS again.
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005509 if (Expr *Exp = dyn_cast<Expr>(S))
5510 if (isa<ObjCPropertyRefExpr>(Exp) ||
5511 isa<ObjCImplicitSetterGetterRefExpr>(Exp)) {
5512 if (PropSetters[Exp]) {
5513 ++CI;
5514 continue;
5515 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005516 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005517 }
Mike Stump1eb44332009-09-09 15:08:12 +00005518
Steve Narofffa15fd92008-10-28 20:29:00 +00005519 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005520 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005521 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5522 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005523 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005524 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005525 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005526 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005527 Stmt *SaveCurrentBody = CurrentBody;
5528 CurrentBody = BE->getBody();
5529 PropParentMap = 0;
Steve Narofffa15fd92008-10-28 20:29:00 +00005530 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005531 CurrentBody = SaveCurrentBody;
5532 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005533 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005534 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005535 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005536 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005537
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005538 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5539
Steve Narofffa15fd92008-10-28 20:29:00 +00005540 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005541 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005542 return blockTranscribed;
5543 }
5544 // Handle specific things.
5545 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5546 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005547
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005548 if (isa<ObjCPropertyRefExpr>(S) || isa<ObjCImplicitSetterGetterRefExpr>(S)) {
5549 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5550 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5551
5552 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005553 if (BinOp) {
5554 // Because the rewriter doesn't allow us to rewrite rewritten code,
5555 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005556 DisableReplaceStmt = true;
5557 // Save the source range. Even if we disable the replacement, the
5558 // rewritten node will have been inserted into the tree. If the synthesized
5559 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005560 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005561 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5562 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005563 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005564 // Need to rewrite the ivar access expression if need be.
5565 if (isa<ObjCIvarRefExpr>(newStmt)) {
5566 bool replaced = false;
5567 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5568 }
5569
Steve Naroffb619d952008-12-09 12:56:34 +00005570 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005571 //
5572 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5573 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5574 // to see the original expression). Consider this example:
5575 //
5576 // Foo *obj1, *obj2;
5577 //
5578 // obj1.i = [obj2 rrrr];
5579 //
5580 // 'BinOp' for the previous expression looks like:
5581 //
5582 // (BinaryOperator 0x231ccf0 'int' '='
5583 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5584 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5585 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5586 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5587 //
5588 // 'newStmt' represents the rewritten message expression. For example:
5589 //
5590 // (CallExpr 0x231d300 'id':'struct objc_object *'
5591 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5592 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5593 // (CStyleCastExpr 0x231d220 'void *'
5594 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5595 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005596 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005597 // can be used as the setter argument. ReplaceStmt() will still 'see'
5598 // the original RHS (since we haven't altered BinOp).
5599 //
Mike Stump1eb44332009-09-09 15:08:12 +00005600 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005601 // node. As a result, we now leak the original AST nodes.
5602 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005603 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005604 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005605 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005606 }
5607 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005608
Steve Narofffa15fd92008-10-28 20:29:00 +00005609 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5610 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005611
Steve Narofffa15fd92008-10-28 20:29:00 +00005612 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5613 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005614
Steve Narofffa15fd92008-10-28 20:29:00 +00005615 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005616#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005617 // Before we rewrite it, put the original message expression in a comment.
5618 SourceLocation startLoc = MessExpr->getLocStart();
5619 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005620
Steve Narofffa15fd92008-10-28 20:29:00 +00005621 const char *startBuf = SM->getCharacterData(startLoc);
5622 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005623
Steve Narofffa15fd92008-10-28 20:29:00 +00005624 std::string messString;
5625 messString += "// ";
5626 messString.append(startBuf, endBuf-startBuf+1);
5627 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005628
5629 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005630 // InsertText(clang::SourceLocation, char const*, unsigned int).
5631 // InsertText(startLoc, messString.c_str(), messString.size());
5632 // Tried this, but it didn't work either...
5633 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005634#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005635 return RewriteMessageExpr(MessExpr);
5636 }
Mike Stump1eb44332009-09-09 15:08:12 +00005637
Steve Narofffa15fd92008-10-28 20:29:00 +00005638 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5639 return RewriteObjCTryStmt(StmtTry);
5640
5641 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5642 return RewriteObjCSynchronizedStmt(StmtTry);
5643
5644 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5645 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005646
Steve Narofffa15fd92008-10-28 20:29:00 +00005647 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5648 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005649
5650 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005651 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005652 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005653 OrigStmtRange.getEnd());
5654 if (BreakStmt *StmtBreakStmt =
5655 dyn_cast<BreakStmt>(S))
5656 return RewriteBreakStmt(StmtBreakStmt);
5657 if (ContinueStmt *StmtContinueStmt =
5658 dyn_cast<ContinueStmt>(S))
5659 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005660
5661 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005662 // and cast exprs.
5663 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5664 // FIXME: What we're doing here is modifying the type-specifier that
5665 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005666 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005667 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5668 // the context of an ObjCForCollectionStmt. For example:
5669 // NSArray *someArray;
5670 // for (id <FooProtocol> index in someArray) ;
5671 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5672 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005673 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005674 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005675
Steve Narofffa15fd92008-10-28 20:29:00 +00005676 // Blocks rewrite rules.
5677 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5678 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005679 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005680 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005681 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005682 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005683 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005684 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005685 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005686 if (VD->hasAttr<BlocksAttr>()) {
5687 static unsigned uniqueByrefDeclCount = 0;
5688 assert(!BlockByRefDeclNo.count(ND) &&
5689 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5690 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005691 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005692 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005693 else
5694 RewriteTypeOfDecl(VD);
5695 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005696 }
5697 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005698 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005699 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005700 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005701 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5702 }
5703 }
5704 }
Mike Stump1eb44332009-09-09 15:08:12 +00005705
Steve Narofffa15fd92008-10-28 20:29:00 +00005706 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5707 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005708
5709 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005710 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5711 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005712 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5713 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005714 && "Statement stack mismatch");
5715 Stmts.pop_back();
5716 }
5717 // Handle blocks rewriting.
5718 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5719 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005720 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005721 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005722 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5723 ValueDecl *VD = DRE->getDecl();
5724 if (VD->hasAttr<BlocksAttr>())
5725 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005726 if (HasLocalVariableExternalStorage(VD))
5727 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005728 }
5729
Steve Narofffa15fd92008-10-28 20:29:00 +00005730 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005731 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005732 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005733 ReplaceStmt(S, BlockCall);
5734 return BlockCall;
5735 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005736 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005737 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005738 RewriteCastExpr(CE);
5739 }
5740#if 0
5741 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005742 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5743 ICE->getSubExpr(),
5744 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005745 // Get the new text.
5746 std::string SStr;
5747 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005748 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005749 const std::string &Str = Buf.str();
5750
5751 printf("CAST = %s\n", &Str[0]);
5752 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5753 delete S;
5754 return Replacement;
5755 }
5756#endif
5757 // Return this stmt unmodified.
5758 return S;
5759}
5760
Steve Naroff3d7e7862009-12-05 15:55:59 +00005761void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5762 for (RecordDecl::field_iterator i = RD->field_begin(),
5763 e = RD->field_end(); i != e; ++i) {
5764 FieldDecl *FD = *i;
5765 if (isTopLevelBlockPointerType(FD->getType()))
5766 RewriteBlockPointerDecl(FD);
5767 if (FD->getType()->isObjCQualifiedIdType() ||
5768 FD->getType()->isObjCQualifiedInterfaceType())
5769 RewriteObjCQualifiedInterfaceTypes(FD);
5770 }
5771}
5772
Steve Narofffa15fd92008-10-28 20:29:00 +00005773/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5774/// main file of the input.
5775void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5776 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005777 if (FD->isOverloadedOperator())
5778 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005779
Steve Narofffa15fd92008-10-28 20:29:00 +00005780 // Since function prototypes don't have ParmDecl's, we check the function
5781 // prototype. This enables us to rewrite function declarations and
5782 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005783 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005784
Sebastian Redld3a413d2009-04-26 20:35:05 +00005785 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005786 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005787 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005788 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005789 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005790 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005791 Body =
5792 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5793 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005794 CurrentBody = 0;
5795 if (PropParentMap) {
5796 delete PropParentMap;
5797 PropParentMap = 0;
5798 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005799 // This synthesizes and inserts the block "impl" struct, invoke function,
5800 // and any copy/dispose helper functions.
5801 InsertBlockLiteralsWithinFunction(FD);
5802 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005803 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005804 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005805 return;
5806 }
5807 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005808 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005809 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005810 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005811 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005812 Body =
5813 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5814 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005815 CurrentBody = 0;
5816 if (PropParentMap) {
5817 delete PropParentMap;
5818 PropParentMap = 0;
5819 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005820 InsertBlockLiteralsWithinMethod(MD);
5821 CurMethodDef = 0;
5822 }
5823 }
5824 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5825 ClassImplementation.push_back(CI);
5826 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5827 CategoryImplementation.push_back(CI);
5828 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5829 RewriteForwardClassDecl(CD);
5830 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5831 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005832 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005833 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005834 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005835 CheckFunctionPointerDecl(VD->getType(), VD);
5836 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005837 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005838 RewriteCastExpr(CE);
5839 }
5840 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005841 } else if (VD->getType()->isRecordType()) {
5842 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5843 if (RD->isDefinition())
5844 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005845 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005846 if (VD->getInit()) {
5847 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005848 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005849 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005850 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005851 CurrentBody = 0;
5852 if (PropParentMap) {
5853 delete PropParentMap;
5854 PropParentMap = 0;
5855 }
Mike Stump1eb44332009-09-09 15:08:12 +00005856 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005857 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005858 GlobalVarDecl = 0;
5859
5860 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005861 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005862 RewriteCastExpr(CE);
5863 }
5864 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005865 return;
5866 }
5867 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005868 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005869 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005870 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005871 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5872 return;
5873 }
5874 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005875 if (RD->isDefinition())
5876 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005877 return;
5878 }
5879 // Nothing yet.
5880}
5881
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005882void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005883 if (Diags.hasErrorOccurred())
5884 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005885
Steve Narofffa15fd92008-10-28 20:29:00 +00005886 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005887
Steve Naroff621edce2009-04-29 16:37:50 +00005888 // Here's a great place to add any extra declarations that may be needed.
5889 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005890 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005891 E = ProtocolExprDecls.end(); I != E; ++I)
5892 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5893
Benjamin Kramerd999b372010-02-14 14:14:16 +00005894 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005895 if (ClassImplementation.size() || CategoryImplementation.size())
5896 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005897
Steve Narofffa15fd92008-10-28 20:29:00 +00005898 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5899 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005900 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005901 Rewrite.getRewriteBufferFor(MainFileID)) {
5902 //printf("Changed:\n");
5903 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5904 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005905 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005906 }
Steve Narofface66252008-11-13 20:07:04 +00005907
Steve Naroff621edce2009-04-29 16:37:50 +00005908 if (ClassImplementation.size() || CategoryImplementation.size() ||
5909 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005910 // Rewrite Objective-c meta data*
5911 std::string ResultStr;
5912 SynthesizeMetaDataIntoBuffer(ResultStr);
5913 // Emit metadata.
5914 *OutFile << ResultStr;
5915 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005916 OutFile->flush();
5917}