blob: 539ee49a6c4ed48e8f3ab0dbe4852683798693b7 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar9b414d32010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000035 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000036 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000037 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000041 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000042 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000043 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000044 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner2c64b7b2007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattner01c57482007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000069
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 }
John McCall0e88aa72010-12-14 06:51:39 +0000453
454 QualType getSimpleFunctionType(QualType result,
455 const QualType *args,
456 unsigned numArgs,
457 bool variadic = false) {
458 FunctionProtoType::ExtProtoInfo fpi;
459 fpi.Variadic = variadic;
460 return Context->getFunctionType(result, args, numArgs, fpi);
461 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000462 };
John McCall9d125032010-01-15 18:39:57 +0000463
464 // Helper function: create a CStyleCastExpr with trivial type source info.
465 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000466 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000467 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +0000468 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallf871d0c2010-08-07 06:22:56 +0000469 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000470 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000471}
472
Mike Stump1eb44332009-09-09 15:08:12 +0000473void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
474 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000475 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000476 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000477 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000478 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000479 // All the args are checked/rewritten. Don't call twice!
480 RewriteBlockPointerDecl(D);
481 break;
482 }
483 }
484}
485
486void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000487 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000488 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000489 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000490}
491
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000492static bool IsHeaderFile(const std::string &Filename) {
493 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000495 if (DotPos == std::string::npos) {
496 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000497 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000498 }
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000500 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
501 // C header: .h
502 // C++ header: .hh or .H;
503 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000504}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000505
Eli Friedman66d6f042009-05-18 22:20:00 +0000506RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000507 Diagnostic &D, const LangOptions &LOpts,
508 bool silenceMacroWarn)
509 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
510 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000511 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000512 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000513 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000514 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000515 "rewriter doesn't support user-specified control flow semantics "
516 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000517}
518
Eli Friedmanbce831b2009-05-18 22:29:17 +0000519ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
520 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000521 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000522 const LangOptions &LOpts,
523 bool SilenceRewriteMacroWarning) {
524 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000525}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000526
Steve Naroffb29b4272008-04-14 22:03:09 +0000527void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000528 Context = &context;
529 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000530 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000531 MsgSendFunctionDecl = 0;
532 MsgSendSuperFunctionDecl = 0;
533 MsgSendStretFunctionDecl = 0;
534 MsgSendSuperStretFunctionDecl = 0;
535 MsgSendFpretFunctionDecl = 0;
536 GetClassFunctionDecl = 0;
537 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000538 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000539 SelGetUidFunctionDecl = 0;
540 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000541 ConstantStringClassReference = 0;
542 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000543 CurMethodDef = 0;
544 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000545 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000546 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000547 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000548 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000549 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000550 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000551 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000552 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000553 PropParentMap = 0;
554 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000555 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000556 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000558 // Get the ID and start/end of the main file.
559 MainFileID = SM->getMainFileID();
560 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
561 MainFileStart = MainBuf->getBufferStart();
562 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Chris Lattner2c78b872009-04-14 23:22:57 +0000564 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000566 // declaring objc_selector outside the parameter list removes a silly
567 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000568 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000569 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000570 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000571 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000572 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000573 if (LangOpts.Microsoft) {
574 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000575 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
576 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000577 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000578 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000579 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000580 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
581 Preamble += "typedef struct objc_object Protocol;\n";
582 Preamble += "#define _REWRITER_typedef_Protocol\n";
583 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000584 if (LangOpts.Microsoft) {
585 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
586 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
587 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000588 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000589 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000590 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000591 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000592 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000593 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000594 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000595 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000596 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000597 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000598 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000599 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000600 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000601 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
602 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000603 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000604 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000605 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
606 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
607 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
608 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
609 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000610 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000611 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000612 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
613 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
614 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000615 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
616 Preamble += "struct __objcFastEnumerationState {\n\t";
617 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000618 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000619 Preamble += "unsigned long *mutationsPtr;\n\t";
620 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000621 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000622 Preamble += "#define __FASTENUMERATIONSTATE\n";
623 Preamble += "#endif\n";
624 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
625 Preamble += "struct __NSConstantStringImpl {\n";
626 Preamble += " int *isa;\n";
627 Preamble += " int flags;\n";
628 Preamble += " char *str;\n";
629 Preamble += " long length;\n";
630 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000631 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
632 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
633 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000634 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000635 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000636 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
637 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000638 // Blocks preamble.
639 Preamble += "#ifndef BLOCK_IMPL\n";
640 Preamble += "#define BLOCK_IMPL\n";
641 Preamble += "struct __block_impl {\n";
642 Preamble += " void *isa;\n";
643 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000644 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000645 Preamble += " void *FuncPtr;\n";
646 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000647 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000648 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000649 Preamble += "extern \"C\" __declspec(dllexport) "
650 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000651 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
652 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
653 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
654 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000655 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
656 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000657 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
658 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
659 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000660 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000661 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000662 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
663 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000664 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000665 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000666 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000667 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000668 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000669 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000670 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000671 Preamble += "#define __weak\n";
672 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000673 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
674 // as this avoids warning in any 64bit/32bit compilation model.
675 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000676}
677
678
Chris Lattnerf04da132007-10-24 17:06:59 +0000679//===----------------------------------------------------------------------===//
680// Top Level Driver Code
681//===----------------------------------------------------------------------===//
682
Chris Lattner682bf922009-03-29 16:50:03 +0000683void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000684 if (Diags.hasErrorOccurred())
685 return;
686
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000687 // Two cases: either the decl could be in the main file, or it could be in a
688 // #included file. If the former, rewrite it now. If the later, check to see
689 // if we rewrote the #include/#import.
690 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000691 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000693 // If this is for a builtin, ignore it.
694 if (Loc.isInvalid()) return;
695
Steve Naroffebf2b562007-10-23 23:50:29 +0000696 // Look for built-in declarations that we need to refer during the rewrite.
697 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000698 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000699 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000700 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000701 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000702 ConstantStringClassReference = FVD;
703 return;
704 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000705 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000706 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000707 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000708 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000709 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000710 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000711 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000712 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000713 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000714 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
715 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000716 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
717 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000718 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000719 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000720 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000721 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000722 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000723 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000724}
725
Chris Lattnerf04da132007-10-24 17:06:59 +0000726//===----------------------------------------------------------------------===//
727// Syntactic (non-AST) Rewriting Code
728//===----------------------------------------------------------------------===//
729
Steve Naroffb29b4272008-04-14 22:03:09 +0000730void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000731 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000732 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
733 const char *MainBufStart = MainBuf.begin();
734 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000735 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000737 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000738 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
739 if (*BufPtr == '#') {
740 if (++BufPtr == MainBufEnd)
741 return;
742 while (*BufPtr == ' ' || *BufPtr == '\t')
743 if (++BufPtr == MainBufEnd)
744 return;
745 if (!strncmp(BufPtr, "import", ImportLen)) {
746 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000747 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000748 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000749 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000750 BufPtr += ImportLen;
751 }
752 }
753 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000754}
755
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000756static std::string getIvarAccessString(ObjCIvarDecl *OID) {
757 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000758 std::string S;
759 S = "((struct ";
760 S += ClassDecl->getIdentifier()->getName();
761 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000762 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000763 return S;
764}
765
Steve Naroffa0876e82008-12-02 17:36:43 +0000766void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
767 ObjCImplementationDecl *IMD,
768 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000769 static bool objcGetPropertyDefined = false;
770 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000771 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000772 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000773 const char *startBuf = SM->getCharacterData(startLoc);
774 assert((*startBuf == '@') && "bogus @synthesize location");
775 const char *semiBuf = strchr(startBuf, ';');
776 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000777 SourceLocation onePastSemiLoc =
778 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000779
780 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
781 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Steve Naroffeb0646c2008-12-02 15:48:25 +0000783 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000784 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000785 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000787 if (!OID)
788 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000789 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000790 if (!PD->getGetterMethodDecl()->isDefined()) {
791 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
792 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
793 ObjCPropertyDecl::OBJC_PR_copy));
794 std::string Getr;
795 if (GenGetProperty && !objcGetPropertyDefined) {
796 objcGetPropertyDefined = true;
797 // FIXME. Is this attribute correct in all cases?
798 Getr = "\nextern \"C\" __declspec(dllimport) "
799 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000800 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000801 RewriteObjCMethodDecl(OID->getContainingInterface(),
802 PD->getGetterMethodDecl(), Getr);
803 Getr += "{ ";
804 // Synthesize an explicit cast to gain access to the ivar.
805 // See objc-act.c:objc_synthesize_new_getter() for details.
806 if (GenGetProperty) {
807 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
808 Getr += "typedef ";
809 const FunctionType *FPRetType = 0;
810 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
811 FPRetType);
812 Getr += " _TYPE";
813 if (FPRetType) {
814 Getr += ")"; // close the precedence "scope" for "*".
815
816 // Now, emit the argument types (if any).
817 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
818 Getr += "(";
819 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
820 if (i) Getr += ", ";
821 std::string ParamStr = FT->getArgType(i).getAsString(
822 Context->PrintingPolicy);
823 Getr += ParamStr;
824 }
825 if (FT->isVariadic()) {
826 if (FT->getNumArgs()) Getr += ", ";
827 Getr += "...";
828 }
829 Getr += ")";
830 } else
831 Getr += "()";
832 }
833 Getr += ";\n";
834 Getr += "return (_TYPE)";
835 Getr += "objc_getProperty(self, _cmd, ";
836 SynthesizeIvarOffsetComputation(OID, Getr);
837 Getr += ", 1)";
838 }
839 else
840 Getr += "return " + getIvarAccessString(OID);
841 Getr += "; }";
842 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000843 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000844
845 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000846 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Steve Naroffeb0646c2008-12-02 15:48:25 +0000848 // Generate the 'setter' function.
849 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000850 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
851 ObjCPropertyDecl::OBJC_PR_copy);
852 if (GenSetProperty && !objcSetPropertyDefined) {
853 objcSetPropertyDefined = true;
854 // FIXME. Is this attribute correct in all cases?
855 Setr = "\nextern \"C\" __declspec(dllimport) "
856 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
857 }
858
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000859 RewriteObjCMethodDecl(OID->getContainingInterface(),
860 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000861 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000862 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000863 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000864 if (GenSetProperty) {
865 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000866 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000867 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000868 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000869 Setr += ", ";
870 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
871 Setr += "0, ";
872 else
873 Setr += "1, ";
874 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
875 Setr += "1)";
876 else
877 Setr += "0)";
878 }
879 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000880 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000881 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000882 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000883 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000884 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000885}
Chris Lattner8a12c272007-10-11 18:38:32 +0000886
Steve Naroffb29b4272008-04-14 22:03:09 +0000887void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000888 // Get the start location and compute the semi location.
889 SourceLocation startLoc = ClassDecl->getLocation();
890 const char *startBuf = SM->getCharacterData(startLoc);
891 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Chris Lattnerf04da132007-10-24 17:06:59 +0000893 // Translate to typedef's that forward reference structs with the same name
894 // as the class. As a convenience, we include the original declaration
895 // as a comment.
896 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000897 typedefString += "// @class ";
898 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
899 I != E; ++I) {
900 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
901 typedefString += ForwardDecl->getNameAsString();
902 if (I+1 != E)
903 typedefString += ", ";
904 else
905 typedefString += ";\n";
906 }
907
Chris Lattner67956052009-02-20 18:04:31 +0000908 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
909 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000910 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000911 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000912 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000913 typedefString += "\n";
914 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000915 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000916 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000917 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000918 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000919 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000920 }
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Steve Naroff934f2762007-10-24 22:48:43 +0000922 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000923 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000924}
925
Steve Naroffb29b4272008-04-14 22:03:09 +0000926void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000927 // When method is a synthesized one, such as a getter/setter there is
928 // nothing to rewrite.
929 if (Method->isSynthesized())
930 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000931 SourceLocation LocStart = Method->getLocStart();
932 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000933
Chris Lattner30fc9332009-02-04 01:06:56 +0000934 if (SM->getInstantiationLineNumber(LocEnd) >
935 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000936 InsertText(LocStart, "#if 0\n");
937 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000938 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000939 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000940 }
941}
942
Mike Stump1eb44332009-09-09 15:08:12 +0000943void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000944 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Benjamin Kramerd999b372010-02-14 14:14:16 +0000946 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000947 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000948}
949
Steve Naroffb29b4272008-04-14 22:03:09 +0000950void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000951 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Steve Naroff423cb562007-10-30 13:30:57 +0000953 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000954 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000956 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
957 E = CatDecl->prop_end(); I != E; ++I)
958 RewriteProperty(*I);
959
Mike Stump1eb44332009-09-09 15:08:12 +0000960 for (ObjCCategoryDecl::instmeth_iterator
961 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000962 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000963 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000964 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000965 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000966 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000967 RewriteMethodDeclaration(*I);
968
Steve Naroff423cb562007-10-30 13:30:57 +0000969 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000970 ReplaceText(CatDecl->getAtEndRange().getBegin(),
971 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000972}
973
Steve Naroffb29b4272008-04-14 22:03:09 +0000974void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000975 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Steve Naroff752d6ef2007-10-30 16:42:30 +0000977 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000978 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000979
980 for (ObjCProtocolDecl::instmeth_iterator
981 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000982 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000983 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000984 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000985 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000986 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000987 RewriteMethodDeclaration(*I);
988
Fariborz Jahanian07acdf42010-09-24 18:36:58 +0000989 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
990 E = PDecl->prop_end(); I != E; ++I)
991 RewriteProperty(*I);
992
Steve Naroff752d6ef2007-10-30 16:42:30 +0000993 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000994 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000995 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000996
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000997 // Must comment out @optional/@required
998 const char *startBuf = SM->getCharacterData(LocStart);
999 const char *endBuf = SM->getCharacterData(LocEnd);
1000 for (const char *p = startBuf; p < endBuf; p++) {
1001 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001002 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001003 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001004
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001005 }
1006 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001007 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001008 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001010 }
1011 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001012}
1013
Steve Naroffb29b4272008-04-14 22:03:09 +00001014void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001015 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001016 if (LocStart.isInvalid())
1017 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001018 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001019 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001020}
1021
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001022void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1023 const FunctionType *&FPRetType) {
1024 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001025 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001026 else if (T->isFunctionPointerType() ||
1027 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001028 // needs special handling, since pointer-to-functions have special
1029 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001030 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001031 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001032 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001033 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001034 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001035 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001036 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001037 ResultStr += FPRetType->getResultType().getAsString(
1038 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001039 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001040 }
1041 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001042 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001043}
1044
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001045void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1046 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001047 std::string &ResultStr) {
1048 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1049 const FunctionType *FPRetType = 0;
1050 ResultStr += "\nstatic ";
1051 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001052 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001054 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001055 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001057 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001058 NameStr += "_I_";
1059 else
1060 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001062 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001063 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001064
1065 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001066 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001067 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001068 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001069 }
Mike Stump1eb44332009-09-09 15:08:12 +00001070 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001071 {
1072 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001073 int len = selString.size();
1074 for (int i = 0; i < len; i++)
1075 if (selString[i] == ':')
1076 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001077 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001078 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001079 // Remember this name for metadata emission
1080 MethodInternalNames[OMD] = NameStr;
1081 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001083 // Rewrite arguments
1084 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001086 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001087 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001088 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001089 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001090 if (!LangOpts.Microsoft) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001091 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001092 ResultStr += "struct ";
1093 }
1094 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001095 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001096 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001097 }
1098 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001099 ResultStr += Context->getObjCClassType().getAsString(
1100 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001102 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001103 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001104 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001106 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001107 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1108 E = OMD->param_end(); PI != E; ++PI) {
1109 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001110 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001111 if (PDecl->getType()->isObjCQualifiedIdType()) {
1112 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001113 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001114 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001115 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001116 QualType QT = PDecl->getType();
1117 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1118 if (convertBlockPointerToFunctionPointer(QT))
1119 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1120 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001121 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001122 ResultStr += Name;
1123 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001124 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001125 if (OMD->isVariadic())
1126 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001127 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Steve Naroff76e429d2008-07-16 14:40:40 +00001129 if (FPRetType) {
1130 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Steve Naroff76e429d2008-07-16 14:40:40 +00001132 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001133 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001134 ResultStr += "(";
1135 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1136 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001137 std::string ParamStr = FT->getArgType(i).getAsString(
1138 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001139 ResultStr += ParamStr;
1140 }
1141 if (FT->isVariadic()) {
1142 if (FT->getNumArgs()) ResultStr += ", ";
1143 ResultStr += "...";
1144 }
1145 ResultStr += ")";
1146 } else {
1147 ResultStr += "()";
1148 }
1149 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001150}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001151void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001152 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1153 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001155 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001157 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001158 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1159 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001160 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001161 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001162 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001163 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001164 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001165 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001166
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001167 const char *startBuf = SM->getCharacterData(LocStart);
1168 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001169 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001170 }
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001172 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001173 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1174 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001175 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001176 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001177 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001178 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001179 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001180 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001182 const char *startBuf = SM->getCharacterData(LocStart);
1183 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001184 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001185 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001186 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001187 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001188 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001189 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001190 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001191 }
1192
Benjamin Kramerd999b372010-02-14 14:14:16 +00001193 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001194}
1195
Steve Naroffb29b4272008-04-14 22:03:09 +00001196void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001197 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001198 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001199 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001200 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001201 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001202 ResultStr += "\n";
1203 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001204 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001205 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001206 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001207 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001208 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001209 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001210 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001211 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001212 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001213
1214 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001215 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001216 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001217 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001218 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001219 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001220 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001221 for (ObjCInterfaceDecl::classmeth_iterator
1222 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001223 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001224 RewriteMethodDeclaration(*I);
1225
Steve Naroff2feac5e2007-10-30 03:43:13 +00001226 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001227 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1228 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001229}
1230
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001231Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001232 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001233 ObjCMethodDecl *OMD = 0;
1234 QualType Ty;
1235 Selector Sel;
Duncan Sands54bd4572010-10-20 08:21:16 +00001236 Stmt *Receiver = 0;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001237 bool Super = false;
1238 QualType SuperTy;
1239 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001240 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001241 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001242 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCall12f78a62010-12-02 01:19:52 +00001243 if (ObjCPropertyRefExpr *PropRefExpr =
1244 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001245 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001246 if (PropRefExpr->isExplicitProperty()) {
1247 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1248 OMD = PDecl->getSetterMethodDecl();
1249 Ty = PDecl->getType();
1250 Sel = PDecl->getSetterName();
1251 } else {
1252 OMD = PropRefExpr->getImplicitPropertySetter();
1253 Sel = OMD->getSelector();
1254 Ty = PropRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001255 }
John McCall12f78a62010-12-02 01:19:52 +00001256 Super = PropRefExpr->isSuperReceiver();
1257 if (!Super) {
1258 Receiver = PropRefExpr->getBase();
1259 } else {
1260 SuperTy = PropRefExpr->getSuperReceiverType();
1261 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001262 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001263 }
1264
1265 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Steve Naroffc77a6362008-12-04 16:24:46 +00001266 llvm::SmallVector<Expr *, 1> ExprVec;
1267 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001269 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001270 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001271 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001272 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001273 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001274 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001275 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001276 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001277 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001278 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001279 &ExprVec[0], 1,
1280 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001281 else {
1282 // FIXME. Refactor this into common code with that in
1283 // RewritePropertyOrImplicitGetter
1284 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1285 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1286 if (PropGetters[Exp])
1287 // This allows us to handle chain/nested property/implicit getters.
1288 Receiver = PropGetters[Exp];
1289
Douglas Gregor04badcf2010-04-21 00:45:42 +00001290 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001291 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001292 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001293 /*FIXME: */SourceLocation(),
1294 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001295 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001296 &ExprVec[0], 1,
1297 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001298 }
Steve Naroffc77a6362008-12-04 16:24:46 +00001299 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001300
Steve Naroffc77a6362008-12-04 16:24:46 +00001301 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001302 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001303 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001304 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1305 // to things that stay around.
1306 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001307 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001308}
1309
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001310Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1311 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001312 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001313 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001314 ObjCMethodDecl *OMD = 0;
1315 QualType Ty;
1316 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001317 bool Super = false;
1318 QualType SuperTy;
1319 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001320 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001321 if (ObjCPropertyRefExpr *PropRefExpr =
1322 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001323 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001324 if (PropRefExpr->isExplicitProperty()) {
1325 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1326 OMD = PDecl->getGetterMethodDecl();
1327 Ty = PDecl->getType();
1328 Sel = PDecl->getGetterName();
1329 } else {
1330 OMD = PropRefExpr->getImplicitPropertyGetter();
1331 Sel = OMD->getSelector();
1332 Ty = PropRefExpr->getType();
1333 }
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001334 Super = PropRefExpr->isSuperReceiver();
1335 if (!Super)
1336 Receiver = PropRefExpr->getBase();
1337 else {
John McCall12f78a62010-12-02 01:19:52 +00001338 SuperTy = PropRefExpr->getSuperReceiverType();
1339 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001340 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001341 }
1342
1343 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1344
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001345 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001346 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001347 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001348 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001349 Expr::getValueKindForType(Ty),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001350 /*FIXME?*/SourceLocation(),
1351 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001352 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001353 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001354 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001355 0, 0,
1356 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001357 else {
1358 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1359 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1360 if (PropGetters[Exp])
1361 // This allows us to handle chain/nested property/implicit getters.
1362 Receiver = PropGetters[Exp];
Douglas Gregor04badcf2010-04-21 00:45:42 +00001363 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001364 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001365 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001366 /*FIXME:*/SourceLocation(),
1367 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001368 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001369 0, 0,
1370 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001371 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001372
Steve Naroff4c3580e2008-12-04 23:50:32 +00001373 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001374
1375 if (!PropParentMap)
1376 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001377 bool NestedPropertyRef = false;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001378 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001379 ImplicitCastExpr*ICE=0;
1380 if (Parent)
1381 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1382 assert((ICE->getCastKind() == CK_GetObjCProperty)
1383 && "RewritePropertyOrImplicitGetter");
1384 Parent = PropParentMap->getParent(Parent);
1385 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1386 }
1387 if (NestedPropertyRef) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001388 // We stash away the ReplacingStmt since actually doing the
1389 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001390 PropGetters[ICE] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001391 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1392 // to things that stay around.
1393 Context->Deallocate(MsgExpr);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001394 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001395 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001396 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001397 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001398 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1399 // to things that stay around.
1400 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001401 return ReplacingStmt;
1402 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001403}
1404
Mike Stump1eb44332009-09-09 15:08:12 +00001405Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001406 SourceLocation OrigStart,
1407 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001408 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001409 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001410 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001411 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001412 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001413 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001414 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001415 // lookup which class implements the instance variable.
1416 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001417 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001418 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001419 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Steve Narofff0757612008-05-08 17:52:16 +00001421 // Synthesize an explicit cast to gain access to the ivar.
1422 std::string RecName = clsDeclared->getIdentifier()->getName();
1423 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001424 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001425 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001426 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001427 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1428 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001429 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001430 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001431 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001432 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001433 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCallf89e55a2010-11-18 06:31:45 +00001434 IV->getBase()->getLocEnd(),
1435 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001436 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001437 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001438 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001439 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001440 IV->getLocation(),
1441 D->getType(),
1442 VK_LValue, OK_Ordinary);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001443 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001444 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001445 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001446 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001447 // Cannot delete IV->getBase(), since PE points to it.
1448 // Replace the old base with the cast. This is important when doing
1449 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001450 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001451 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001452 }
Steve Naroff84472a82008-04-18 21:55:08 +00001453 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001454 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Steve Naroff9f525972008-05-06 23:20:07 +00001456 // Explicit ivar refs need to have a cast inserted.
1457 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001458 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001459 ObjCInterfaceType *iFaceDecl =
1460 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001461 // lookup which class implements the instance variable.
1462 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001463 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001464 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001465 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Steve Naroff9f525972008-05-06 23:20:07 +00001467 // Synthesize an explicit cast to gain access to the ivar.
1468 std::string RecName = clsDeclared->getIdentifier()->getName();
1469 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001470 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001471 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001472 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001473 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1474 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001475 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001476 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001477 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001478 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001479 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001480 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001481 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001482 // Cannot delete IV->getBase(), since PE points to it.
1483 // Replace the old base with the cast. This is important when doing
1484 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001485 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001486 return IV;
1487 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001488 }
Steve Naroff84472a82008-04-18 21:55:08 +00001489 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001490}
1491
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001492Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1493 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1494 CI != E; ++CI) {
1495 if (*CI) {
1496 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1497 if (newStmt)
1498 *CI = newStmt;
1499 }
1500 }
1501 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1502 SourceRange OrigStmtRange = S->getSourceRange();
1503 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1504 replaced);
1505 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001506 }
1507 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1508 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1509 return newStmt;
1510 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001511 return S;
1512}
1513
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001514/// SynthCountByEnumWithState - To print:
1515/// ((unsigned int (*)
1516/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001517/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001518/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001519/// "countByEnumeratingWithState:objects:count:"),
1520/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001521/// (id *)items, (unsigned int)16)
1522///
Steve Naroffb29b4272008-04-14 22:03:09 +00001523void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001524 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1525 "id *, unsigned int))(void *)objc_msgSend)";
1526 buf += "\n\t\t";
1527 buf += "((id)l_collection,\n\t\t";
1528 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1529 buf += "\n\t\t";
1530 buf += "&enumState, "
1531 "(id *)items, (unsigned int)16)";
1532}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001533
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001534/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1535/// statement to exit to its outer synthesized loop.
1536///
Steve Naroffb29b4272008-04-14 22:03:09 +00001537Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001538 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1539 return S;
1540 // replace break with goto __break_label
1541 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001543 SourceLocation startLoc = S->getLocStart();
1544 buf = "goto __break_label_";
1545 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001546 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001547
1548 return 0;
1549}
1550
1551/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1552/// statement to continue with its inner synthesized loop.
1553///
Steve Naroffb29b4272008-04-14 22:03:09 +00001554Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001555 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1556 return S;
1557 // replace continue with goto __continue_label
1558 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001560 SourceLocation startLoc = S->getLocStart();
1561 buf = "goto __continue_label_";
1562 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001563 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001565 return 0;
1566}
1567
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001568/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001569/// It rewrites:
1570/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001572/// Into:
1573/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001574/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001575/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001576/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001577/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001578/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001579/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001580/// if (limit) {
1581/// unsigned long startMutations = *enumState.mutationsPtr;
1582/// do {
1583/// unsigned long counter = 0;
1584/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001585/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001586/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001587/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001588/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001589/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001590/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001591/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001592/// objects:items count:16]);
1593/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001594/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001595/// }
1596/// else
1597/// elem = nil;
1598/// }
1599///
Steve Naroffb29b4272008-04-14 22:03:09 +00001600Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001601 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001602 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001603 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001604 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001605 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001606 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001608 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001609 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar4087f272010-08-17 22:39:59 +00001610 llvm::StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001611 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001612 std::string buf;
1613 buf = "\n{\n\t";
1614 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1615 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001616 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001617 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001618 if (ElementType->isObjCQualifiedIdType() ||
1619 ElementType->isObjCQualifiedInterfaceType())
1620 // Simply use 'id' for all qualified types.
1621 elementTypeAsString = "id";
1622 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001623 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001624 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001625 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001626 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001627 buf += elementName;
1628 buf += ";\n\t";
1629 }
Chris Lattner06767512008-04-08 05:52:18 +00001630 else {
1631 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001632 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001633 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1634 if (VD->getType()->isObjCQualifiedIdType() ||
1635 VD->getType()->isObjCQualifiedInterfaceType())
1636 // Simply use 'id' for all qualified types.
1637 elementTypeAsString = "id";
1638 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001639 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001640 }
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001642 // struct __objcFastEnumerationState enumState = { 0 };
1643 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1644 // id items[16];
1645 buf += "id items[16];\n\t";
1646 // id l_collection = (id)
1647 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001648 // Find start location of 'collection' the hard way!
1649 const char *startCollectionBuf = startBuf;
1650 startCollectionBuf += 3; // skip 'for'
1651 startCollectionBuf = strchr(startCollectionBuf, '(');
1652 startCollectionBuf++; // skip '('
1653 // find 'in' and skip it.
1654 while (*startCollectionBuf != ' ' ||
1655 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1656 (*(startCollectionBuf+3) != ' ' &&
1657 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1658 startCollectionBuf++;
1659 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001660
1661 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001662 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001663 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001664 SourceLocation rightParenLoc = S->getRParenLoc();
1665 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1666 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001667 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001669 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1670 // objects:items count:16];
1671 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001672 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001673 // ((unsigned int (*)
1674 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001675 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001676 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001677 // "countByEnumeratingWithState:objects:count:"),
1678 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001679 // (id *)items, (unsigned int)16);
1680 buf += "unsigned long limit =\n\t\t";
1681 SynthCountByEnumWithState(buf);
1682 buf += ";\n\t";
1683 /// if (limit) {
1684 /// unsigned long startMutations = *enumState.mutationsPtr;
1685 /// do {
1686 /// unsigned long counter = 0;
1687 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001688 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001689 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001690 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001691 buf += "if (limit) {\n\t";
1692 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1693 buf += "do {\n\t\t";
1694 buf += "unsigned long counter = 0;\n\t\t";
1695 buf += "do {\n\t\t\t";
1696 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1697 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1698 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001699 buf += " = (";
1700 buf += elementTypeAsString;
1701 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001702 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001703 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001704
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001705 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001706 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001707 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001708 /// objects:items count:16]);
1709 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001710 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001711 /// }
1712 /// else
1713 /// elem = nil;
1714 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001715 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001716 buf = ";\n\t";
1717 buf += "__continue_label_";
1718 buf += utostr(ObjCBcLabelNo.back());
1719 buf += ": ;";
1720 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001721 buf += "} while (counter < limit);\n\t";
1722 buf += "} while (limit = ";
1723 SynthCountByEnumWithState(buf);
1724 buf += ");\n\t";
1725 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001726 buf += " = ((";
1727 buf += elementTypeAsString;
1728 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001729 buf += "__break_label_";
1730 buf += utostr(ObjCBcLabelNo.back());
1731 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001732 buf += "}\n\t";
1733 buf += "else\n\t\t";
1734 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001735 buf += " = ((";
1736 buf += elementTypeAsString;
1737 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001738 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001739
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001740 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001741 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001742 if (isa<CompoundStmt>(S->getBody())) {
1743 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001744 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001745 } else {
1746 /* Need to treat single statements specially. For example:
1747 *
1748 * for (A *a in b) if (stuff()) break;
1749 * for (A *a in b) xxxyy;
1750 *
1751 * The following code simply scans ahead to the semi to find the actual end.
1752 */
1753 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1754 const char *semiBuf = strchr(stmtBuf, ';');
1755 assert(semiBuf && "Can't find ';'");
1756 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001757 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001758 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001759 Stmts.pop_back();
1760 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001761 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001762}
1763
Mike Stump1eb44332009-09-09 15:08:12 +00001764/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001765/// This routine rewrites @synchronized(expr) stmt;
1766/// into:
1767/// objc_sync_enter(expr);
1768/// @try stmt @finally { objc_sync_exit(expr); }
1769///
Steve Naroffb29b4272008-04-14 22:03:09 +00001770Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001771 // Get the start location and compute the semi location.
1772 SourceLocation startLoc = S->getLocStart();
1773 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001775 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001776
1777 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001778 buf = "objc_sync_enter((id)";
1779 const char *lparenBuf = startBuf;
1780 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001781 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001782 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1783 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001784 // been rewritten! (which implies the SourceLocation's are invalid).
1785 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001786 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001787 while (*endBuf != ')') endBuf--;
1788 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001789 buf = ");\n";
1790 // declare a new scope with two variables, _stack and _rethrow.
1791 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1792 buf += "int buf[18/*32-bit i386*/];\n";
1793 buf += "char *pointers[4];} _stack;\n";
1794 buf += "id volatile _rethrow = 0;\n";
1795 buf += "objc_exception_try_enter(&_stack);\n";
1796 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001797 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001798 startLoc = S->getSynchBody()->getLocEnd();
1799 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001800
Steve Naroffc7089f12008-08-19 13:04:19 +00001801 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001802 SourceLocation lastCurlyLoc = startLoc;
1803 buf = "}\nelse {\n";
1804 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001805 buf += "}\n";
1806 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001807 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001808
1809 std::string syncBuf;
1810 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001811 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00001812 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001813 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001814 std::string syncExprBufS;
1815 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001816 syncExpr->printPretty(syncExprBuf, *Context, 0,
1817 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001818 syncBuf += syncExprBuf.str();
1819 syncBuf += ");";
1820
1821 buf += syncBuf;
1822 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001823 buf += "}\n";
1824 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Benjamin Kramerd999b372010-02-14 14:14:16 +00001826 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001827
1828 bool hasReturns = false;
1829 HasReturnStmts(S->getSynchBody(), hasReturns);
1830 if (hasReturns)
1831 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1832
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001833 return 0;
1834}
1835
Steve Naroffb85e77a2009-12-05 21:43:12 +00001836void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1837{
Steve Naroff8c565152008-12-05 17:03:39 +00001838 // Perform a bottom up traversal of all children.
1839 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1840 CI != E; ++CI)
1841 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001842 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001843
Steve Naroffb85e77a2009-12-05 21:43:12 +00001844 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001845 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001846 TryFinallyContainsReturnDiag);
1847 }
1848 return;
1849}
1850
Steve Naroffb85e77a2009-12-05 21:43:12 +00001851void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1852{
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 HasReturnStmts(*CI, hasReturns);
1858
1859 if (isa<ReturnStmt>(S))
1860 hasReturns = true;
1861 return;
1862}
1863
1864void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1865 // Perform a bottom up traversal of all children.
1866 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1867 CI != E; ++CI)
1868 if (*CI) {
1869 RewriteTryReturnStmts(*CI);
1870 }
1871 if (isa<ReturnStmt>(S)) {
1872 SourceLocation startLoc = S->getLocStart();
1873 const char *startBuf = SM->getCharacterData(startLoc);
1874
1875 const char *semiBuf = strchr(startBuf, ';');
1876 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1877 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1878
1879 std::string buf;
1880 buf = "{ objc_exception_try_exit(&_stack); return";
1881
Benjamin Kramerd999b372010-02-14 14:14:16 +00001882 ReplaceText(startLoc, 6, buf);
1883 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001884 }
1885 return;
1886}
1887
1888void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1889 // Perform a bottom up traversal of all children.
1890 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1891 CI != E; ++CI)
1892 if (*CI) {
1893 RewriteSyncReturnStmts(*CI, syncExitBuf);
1894 }
1895 if (isa<ReturnStmt>(S)) {
1896 SourceLocation startLoc = S->getLocStart();
1897 const char *startBuf = SM->getCharacterData(startLoc);
1898
1899 const char *semiBuf = strchr(startBuf, ';');
1900 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1901 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1902
1903 std::string buf;
1904 buf = "{ objc_exception_try_exit(&_stack);";
1905 buf += syncExitBuf;
1906 buf += " return";
1907
Benjamin Kramerd999b372010-02-14 14:14:16 +00001908 ReplaceText(startLoc, 6, buf);
1909 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001910 }
1911 return;
1912}
1913
Steve Naroffb29b4272008-04-14 22:03:09 +00001914Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001915 // Get the start location and compute the semi location.
1916 SourceLocation startLoc = S->getLocStart();
1917 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Steve Naroff75730982007-11-07 04:08:17 +00001919 assert((*startBuf == '@') && "bogus @try location");
1920
1921 std::string buf;
1922 // declare a new scope with two variables, _stack and _rethrow.
1923 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1924 buf += "int buf[18/*32-bit i386*/];\n";
1925 buf += "char *pointers[4];} _stack;\n";
1926 buf += "id volatile _rethrow = 0;\n";
1927 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001928 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001929
Benjamin Kramerd999b372010-02-14 14:14:16 +00001930 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001931
Steve Naroff75730982007-11-07 04:08:17 +00001932 startLoc = S->getTryBody()->getLocEnd();
1933 startBuf = SM->getCharacterData(startLoc);
1934
1935 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Steve Naroff75730982007-11-07 04:08:17 +00001937 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001938 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001939 startLoc = startLoc.getFileLocWithOffset(1);
1940 buf = " /* @catch begin */ else {\n";
1941 buf += " id _caught = objc_exception_extract(&_stack);\n";
1942 buf += " objc_exception_try_enter (&_stack);\n";
1943 buf += " if (_setjmp(_stack.buf))\n";
1944 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1945 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Benjamin Kramerd999b372010-02-14 14:14:16 +00001947 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001948 } else { /* no catch list */
1949 buf = "}\nelse {\n";
1950 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1951 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001952 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001953 }
Steve Naroff75730982007-11-07 04:08:17 +00001954 bool sawIdTypedCatch = false;
1955 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001956 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1957 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001958 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001959
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001960 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001961 buf = "if ("; // we are generating code for the first catch clause
1962 else
1963 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001964 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001965 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Steve Naroff75730982007-11-07 04:08:17 +00001967 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Steve Naroff75730982007-11-07 04:08:17 +00001969 const char *lParenLoc = strchr(startBuf, '(');
1970
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001971 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001972 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001973 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001974 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1975 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001976 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001977 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001978 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Steve Naroffe12e6922008-02-01 20:02:07 +00001980 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001981 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001982 } else if (catchDecl) {
1983 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001984 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001985 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001986 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001987 sawIdTypedCatch = true;
John McCall506b57e2010-05-17 21:00:27 +00001988 } else if (const ObjCObjectPointerType *Ptr =
1989 t->getAs<ObjCObjectPointerType>()) {
1990 // Should be a pointer to a class.
1991 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1992 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001993 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001994 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001995 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001996 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001997 }
1998 }
1999 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002000 lastCatchBody = Catch->getCatchBody();
2001 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00002002 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2003 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2004 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2005 assert((*rParenBuf == ')') && "bogus @catch paren location");
2006 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002007
Mike Stump1eb44332009-09-09 15:08:12 +00002008 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002009 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002010 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002011 } else {
Steve Naroff75730982007-11-07 04:08:17 +00002012 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002013 }
Steve Naroff75730982007-11-07 04:08:17 +00002014 }
2015 // Complete the catch list...
2016 if (lastCatchBody) {
2017 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002018 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2019 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Steve Naroff378f47a2008-09-11 15:29:03 +00002021 // Insert the last (implicit) else clause *before* the right curly brace.
2022 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2023 buf = "} /* last catch end */\n";
2024 buf += "else {\n";
2025 buf += " _rethrow = _caught;\n";
2026 buf += " objc_exception_try_exit(&_stack);\n";
2027 buf += "} } /* @catch end */\n";
2028 if (!S->getFinallyStmt())
2029 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002030 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002031
Steve Naroff75730982007-11-07 04:08:17 +00002032 // Set lastCurlyLoc
2033 lastCurlyLoc = lastCatchBody->getLocEnd();
2034 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002035 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002036 startLoc = finalStmt->getLocStart();
2037 startBuf = SM->getCharacterData(startLoc);
2038 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002039
Benjamin Kramerd999b372010-02-14 14:14:16 +00002040 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Steve Naroff75730982007-11-07 04:08:17 +00002042 Stmt *body = finalStmt->getFinallyBody();
2043 SourceLocation startLoc = body->getLocStart();
2044 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002045 assert(*SM->getCharacterData(startLoc) == '{' &&
2046 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002047 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002048 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Steve Naroff75730982007-11-07 04:08:17 +00002050 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002051 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00002052 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002053 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002054
Steve Naroff75730982007-11-07 04:08:17 +00002055 // Set lastCurlyLoc
2056 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Steve Naroff8c565152008-12-05 17:03:39 +00002058 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002059 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002060 } else { /* no finally clause - make sure we synthesize an implicit one */
2061 buf = "{ /* implicit finally clause */\n";
2062 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2063 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2064 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002065 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002066
2067 // Now check for any return/continue/go statements within the @try.
2068 // The implicit finally clause won't called if the @try contains any
2069 // jump statements.
2070 bool hasReturns = false;
2071 HasReturnStmts(S->getTryBody(), hasReturns);
2072 if (hasReturns)
2073 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002074 }
2075 // Now emit the final closing curly brace...
2076 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002077 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002078 return 0;
2079}
2080
Mike Stump1eb44332009-09-09 15:08:12 +00002081// This can't be done with ReplaceStmt(S, ThrowExpr), since
2082// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002083// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002084Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002085 // Get the start location and compute the semi location.
2086 SourceLocation startLoc = S->getLocStart();
2087 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Steve Naroff2bd03922007-11-07 15:32:26 +00002089 assert((*startBuf == '@') && "bogus @throw location");
2090
2091 std::string buf;
2092 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002093 if (S->getThrowExpr())
2094 buf = "objc_exception_throw(";
2095 else // add an implicit argument
2096 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002098 // handle "@ throw" correctly.
2099 const char *wBuf = strchr(startBuf, 'w');
2100 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002101 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Steve Naroff2bd03922007-11-07 15:32:26 +00002103 const char *semiBuf = strchr(startBuf, ';');
2104 assert((*semiBuf == ';') && "@throw: can't find ';'");
2105 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002106 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002107 return 0;
2108}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002109
Steve Naroffb29b4272008-04-14 22:03:09 +00002110Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002111 // Create a new string expression.
2112 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002113 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002114 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00002115 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2116 StrEncoding.length(), false,StrType,
2117 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002118 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Chris Lattner07506182007-11-30 22:53:43 +00002120 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002121 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002122 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002123}
2124
Steve Naroffb29b4272008-04-14 22:03:09 +00002125Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002126 if (!SelGetUidFunctionDecl)
2127 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002128 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2129 // Create a call to sel_registerName("selName").
2130 llvm::SmallVector<Expr*, 8> SelExprs;
2131 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002132 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002133 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002134 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002135 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002136 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2137 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002138 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002139 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002140 return SelExp;
2141}
2142
Steve Naroffb29b4272008-04-14 22:03:09 +00002143CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002144 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2145 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002146 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002147 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Steve Naroffebf2b562007-10-23 23:50:29 +00002149 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002150 DeclRefExpr *DRE =
2151 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002152
Steve Naroffebf2b562007-10-23 23:50:29 +00002153 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002154 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002155 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002156 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002157 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002158
John McCall183700f2009-09-21 23:43:11 +00002159 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002161 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002162 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002163 FT->getCallResultType(*Context),
2164 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002165 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002166}
2167
Steve Naroffd5255f52007-11-01 13:24:47 +00002168static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2169 const char *&startRef, const char *&endRef) {
2170 while (startBuf < endBuf) {
2171 if (*startBuf == '<')
2172 startRef = startBuf; // mark the start.
2173 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002174 if (startRef && *startRef == '<') {
2175 endRef = startBuf; // mark the end.
2176 return true;
2177 }
2178 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002179 }
2180 startBuf++;
2181 }
2182 return false;
2183}
2184
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002185static void scanToNextArgument(const char *&argRef) {
2186 int angle = 0;
2187 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2188 if (*argRef == '<')
2189 angle++;
2190 else if (*argRef == '>')
2191 angle--;
2192 argRef++;
2193 }
2194 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2195}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002196
Steve Naroffb29b4272008-04-14 22:03:09 +00002197bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002198 if (T->isObjCQualifiedIdType())
2199 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002200 if (const PointerType *PT = T->getAs<PointerType>()) {
2201 if (PT->getPointeeType()->isObjCQualifiedIdType())
2202 return true;
2203 }
2204 if (T->isObjCObjectPointerType()) {
2205 T = T->getPointeeType();
2206 return T->isObjCQualifiedInterfaceType();
2207 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002208 if (T->isArrayType()) {
2209 QualType ElemTy = Context->getBaseElementType(T);
2210 return needToScanForQualifiers(ElemTy);
2211 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002212 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002213}
2214
Steve Naroff4f95b752008-07-29 18:15:38 +00002215void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2216 QualType Type = E->getType();
2217 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002218 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002219
Steve Naroffcda658e2008-11-19 21:15:47 +00002220 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2221 Loc = ECE->getLParenLoc();
2222 EndLoc = ECE->getRParenLoc();
2223 } else {
2224 Loc = E->getLocStart();
2225 EndLoc = E->getLocEnd();
2226 }
2227 // This will defend against trying to rewrite synthesized expressions.
2228 if (Loc.isInvalid() || EndLoc.isInvalid())
2229 return;
2230
Steve Naroff4f95b752008-07-29 18:15:38 +00002231 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002232 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002233 const char *startRef = 0, *endRef = 0;
2234 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2235 // Get the locations of the startRef, endRef.
2236 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2237 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2238 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002239 InsertText(LessLoc, "/*");
2240 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002241 }
2242 }
2243}
2244
Steve Naroffb29b4272008-04-14 22:03:09 +00002245void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002246 SourceLocation Loc;
2247 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002248 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002249 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2250 Loc = VD->getLocation();
2251 Type = VD->getType();
2252 }
2253 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2254 Loc = FD->getLocation();
2255 // Check for ObjC 'id' and class types that have been adorned with protocol
2256 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002257 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002258 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002259 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002260 if (!proto)
2261 return;
2262 Type = proto->getResultType();
2263 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002264 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2265 Loc = FD->getLocation();
2266 Type = FD->getType();
2267 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002268 else
2269 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002270
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002271 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002272 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Steve Naroffd5255f52007-11-01 13:24:47 +00002274 const char *endBuf = SM->getCharacterData(Loc);
2275 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002276 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002277 startBuf--; // scan backward (from the decl location) for return type.
2278 const char *startRef = 0, *endRef = 0;
2279 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2280 // Get the locations of the startRef, endRef.
2281 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2282 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2283 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002284 InsertText(LessLoc, "/*");
2285 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002286 }
2287 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002288 if (!proto)
2289 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002290 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002291 const char *startBuf = SM->getCharacterData(Loc);
2292 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002293 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2294 if (needToScanForQualifiers(proto->getArgType(i))) {
2295 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002296
Steve Naroffd5255f52007-11-01 13:24:47 +00002297 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002298 // scan forward (from the decl location) for argument types.
2299 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002300 const char *startRef = 0, *endRef = 0;
2301 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2302 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002303 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002304 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002305 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002306 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002307 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002308 InsertText(LessLoc, "/*");
2309 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002310 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002311 startBuf = ++endBuf;
2312 }
2313 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002314 // If the function name is derived from a macro expansion, then the
2315 // argument buffer will not follow the name. Need to speak with Chris.
2316 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002317 startBuf++; // scan forward (from the decl location) for argument types.
2318 startBuf++;
2319 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002320 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002321}
2322
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002323void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2324 QualType QT = ND->getType();
2325 const Type* TypePtr = QT->getAs<Type>();
2326 if (!isa<TypeOfExprType>(TypePtr))
2327 return;
2328 while (isa<TypeOfExprType>(TypePtr)) {
2329 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2330 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2331 TypePtr = QT->getAs<Type>();
2332 }
2333 // FIXME. This will not work for multiple declarators; as in:
2334 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002335 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002336 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2337 const char *startBuf = SM->getCharacterData(DeclLoc);
2338 if (ND->getInit()) {
2339 std::string Name(ND->getNameAsString());
2340 TypeAsString += " " + Name + " = ";
2341 Expr *E = ND->getInit();
2342 SourceLocation startLoc;
2343 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2344 startLoc = ECE->getLParenLoc();
2345 else
2346 startLoc = E->getLocStart();
2347 startLoc = SM->getInstantiationLoc(startLoc);
2348 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002349 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002350 }
2351 else {
2352 SourceLocation X = ND->getLocEnd();
2353 X = SM->getInstantiationLoc(X);
2354 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002355 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002356 }
2357}
2358
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002359// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002360void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002361 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2362 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002363 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCall0e88aa72010-12-14 06:51:39 +00002364 QualType getFuncType =
2365 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002366 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002367 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002368 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002369 SC_Extern,
2370 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002371}
2372
Steve Naroffb29b4272008-04-14 22:03:09 +00002373void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002374 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002375 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002376 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002377 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002378 return;
2379 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002380 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002381}
2382
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002383void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2384 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002385 const char *argPtr = TypeString.c_str();
2386 if (!strchr(argPtr, '^')) {
2387 Str += TypeString;
2388 return;
2389 }
2390 while (*argPtr) {
2391 Str += (*argPtr == '^' ? '*' : *argPtr);
2392 argPtr++;
2393 }
2394}
2395
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002396// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002397void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2398 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002399 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002400 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002401 const char *argPtr = TypeString.c_str();
2402 int paren = 0;
2403 while (*argPtr) {
2404 switch (*argPtr) {
2405 case '(':
2406 Str += *argPtr;
2407 paren++;
2408 break;
2409 case ')':
2410 Str += *argPtr;
2411 paren--;
2412 break;
2413 case '^':
2414 Str += '*';
2415 if (paren == 1)
2416 Str += VD->getNameAsString();
2417 break;
2418 default:
2419 Str += *argPtr;
2420 break;
2421 }
2422 argPtr++;
2423 }
2424}
2425
2426
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002427void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2428 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2429 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2430 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2431 if (!proto)
2432 return;
2433 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002434 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002435 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002436 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002437 FdStr += "(";
2438 unsigned numArgs = proto->getNumArgs();
2439 for (unsigned i = 0; i < numArgs; i++) {
2440 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002441 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002442 if (i+1 < numArgs)
2443 FdStr += ", ";
2444 }
2445 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002446 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002447 CurFunctionDeclToDeclareForBlock = 0;
2448}
2449
Steve Naroffc0a123c2008-03-11 17:37:02 +00002450// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002451void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002452 if (SuperContructorFunctionDecl)
2453 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002454 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002455 llvm::SmallVector<QualType, 16> ArgTys;
2456 QualType argT = Context->getObjCIdType();
2457 assert(!argT.isNull() && "Can't find 'id' type");
2458 ArgTys.push_back(argT);
2459 ArgTys.push_back(argT);
John McCall0e88aa72010-12-14 06:51:39 +00002460 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2461 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002462 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002463 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002464 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002465 SC_Extern,
2466 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002467}
2468
Steve Naroff09b266e2007-10-30 23:14:51 +00002469// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002470void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002471 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2472 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002473 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002474 assert(!argT.isNull() && "Can't find 'id' type");
2475 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002476 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002477 assert(!argT.isNull() && "Can't find 'SEL' type");
2478 ArgTys.push_back(argT);
John McCall0e88aa72010-12-14 06:51:39 +00002479 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2480 &ArgTys[0], ArgTys.size(),
2481 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002482 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002483 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002484 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002485 SC_Extern,
2486 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002487}
2488
Steve Naroff874e2322007-11-15 10:28:18 +00002489// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002490void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002491 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2492 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002493 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002494 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002495 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002496 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2497 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2498 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002499 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002500 assert(!argT.isNull() && "Can't find 'SEL' type");
2501 ArgTys.push_back(argT);
John McCall0e88aa72010-12-14 06:51:39 +00002502 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2503 &ArgTys[0], ArgTys.size(),
2504 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002505 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002506 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002507 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002508 SC_Extern,
2509 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002510}
2511
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002512// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002513void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002514 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2515 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002516 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002517 assert(!argT.isNull() && "Can't find 'id' type");
2518 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002519 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002520 assert(!argT.isNull() && "Can't find 'SEL' type");
2521 ArgTys.push_back(argT);
John McCall0e88aa72010-12-14 06:51:39 +00002522 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2523 &ArgTys[0], ArgTys.size(),
2524 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002525 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002526 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002527 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002528 SC_Extern,
2529 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002530}
2531
Mike Stump1eb44332009-09-09 15:08:12 +00002532// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002533// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002534void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002535 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002536 &Context->Idents.get("objc_msgSendSuper_stret");
2537 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002538 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002539 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002540 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002541 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2542 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2543 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002544 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002545 assert(!argT.isNull() && "Can't find 'SEL' type");
2546 ArgTys.push_back(argT);
John McCall0e88aa72010-12-14 06:51:39 +00002547 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2548 &ArgTys[0], ArgTys.size(),
2549 true /*isVariadic*/);
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);
John McCall0e88aa72010-12-14 06:51:39 +00002567 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2568 &ArgTys[0], ArgTys.size(),
2569 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002570 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002571 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002572 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002573 SC_Extern,
2574 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002575}
2576
Steve Naroff09b266e2007-10-30 23:14:51 +00002577// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002578void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002579 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2580 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002581 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCall0e88aa72010-12-14 06:51:39 +00002582 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2583 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002584 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002585 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002586 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002587 SC_Extern,
2588 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002589}
2590
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002591// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2592void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2593 IdentifierInfo *getSuperClassIdent =
2594 &Context->Idents.get("class_getSuperclass");
2595 llvm::SmallVector<QualType, 16> ArgTys;
2596 ArgTys.push_back(Context->getObjCClassType());
John McCall0e88aa72010-12-14 06:51:39 +00002597 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2598 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002599 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002600 SourceLocation(),
2601 getSuperClassIdent,
2602 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002603 SC_Extern,
2604 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002605 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002606}
2607
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002608// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002609void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002610 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2611 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002612 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCall0e88aa72010-12-14 06:51:39 +00002613 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2614 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002615 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002616 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002617 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002618 SC_Extern,
2619 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002620}
2621
Steve Naroffb29b4272008-04-14 22:03:09 +00002622Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002623 QualType strType = getConstantStringStructType();
2624
2625 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002626
2627 std::string tmpName = InFileName;
2628 unsigned i;
2629 for (i=0; i < tmpName.length(); i++) {
2630 char c = tmpName.at(i);
2631 // replace any non alphanumeric characters with '_'.
2632 if (!isalpha(c) && (c < '0' || c > '9'))
2633 tmpName[i] = '_';
2634 }
2635 S += tmpName;
2636 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002637 S += utostr(NumObjCStringLiterals++);
2638
Steve Naroffba92b2e2008-03-27 22:29:16 +00002639 Preamble += "static __NSConstantStringImpl " + S;
2640 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2641 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002642 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002643 std::string prettyBufS;
2644 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002645 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2646 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002647 Preamble += prettyBuf.str();
2648 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002649 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002650
2651 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002652 &Context->Idents.get(S), strType, 0,
John McCalld931b082010-08-26 03:08:43 +00002653 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002654 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2655 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002656 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002657 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002658 VK_RValue, OK_Ordinary,
2659 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002660 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002661 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00002662 CK_BitCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002663 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002664 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002665 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002666}
2667
Steve Naroff874e2322007-11-15 10:28:18 +00002668// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002669QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002670 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002671 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002672 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002673 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002674 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002675
Steve Naroff874e2322007-11-15 10:28:18 +00002676 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002677 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002678 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002679 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002680
Steve Naroff874e2322007-11-15 10:28:18 +00002681 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002682 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002683 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2684 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002685 FieldTypes[i], 0,
2686 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002687 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002688 }
Mike Stump1eb44332009-09-09 15:08:12 +00002689
Douglas Gregor838db382010-02-11 01:19:42 +00002690 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002691 }
2692 return Context->getTagDeclType(SuperStructDecl);
2693}
2694
Steve Naroffb29b4272008-04-14 22:03:09 +00002695QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002696 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002697 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002698 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002699 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002700 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002701
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002702 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002703 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002704 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002705 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002706 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002707 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002708 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002709 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002710
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002711 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002712 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002713 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2714 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002715 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002716 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002717 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002718 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002719 }
2720
Douglas Gregor838db382010-02-11 01:19:42 +00002721 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002722 }
2723 return Context->getTagDeclType(ConstantStringDecl);
2724}
2725
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002726Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2727 SourceLocation StartLoc,
2728 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002729 if (!SelGetUidFunctionDecl)
2730 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002731 if (!MsgSendFunctionDecl)
2732 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002733 if (!MsgSendSuperFunctionDecl)
2734 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002735 if (!MsgSendStretFunctionDecl)
2736 SynthMsgSendStretFunctionDecl();
2737 if (!MsgSendSuperStretFunctionDecl)
2738 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002739 if (!MsgSendFpretFunctionDecl)
2740 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002741 if (!GetClassFunctionDecl)
2742 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002743 if (!GetSuperClassFunctionDecl)
2744 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002745 if (!GetMetaClassFunctionDecl)
2746 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002747
Steve Naroff874e2322007-11-15 10:28:18 +00002748 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002749 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2750 // May need to use objc_msgSend_stret() as well.
2751 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002752 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2753 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002754 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002755 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002756 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002757 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002758 }
Mike Stump1eb44332009-09-09 15:08:12 +00002759
Steve Naroff934f2762007-10-24 22:48:43 +00002760 // Synthesize a call to objc_msgSend().
2761 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002762 switch (Exp->getReceiverKind()) {
2763 case ObjCMessageExpr::SuperClass: {
2764 MsgSendFlavor = MsgSendSuperFunctionDecl;
2765 if (MsgSendStretFlavor)
2766 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2767 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002768
Douglas Gregor04badcf2010-04-21 00:45:42 +00002769 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002770
Douglas Gregor04badcf2010-04-21 00:45:42 +00002771 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002772
Douglas Gregor04badcf2010-04-21 00:45:42 +00002773 // set the receiver to self, the first argument to all methods.
2774 InitExprs.push_back(
2775 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002776 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002777 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002778 Context->getObjCIdType(),
2779 VK_RValue,
2780 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002781 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002782
Douglas Gregor04badcf2010-04-21 00:45:42 +00002783 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2784 llvm::SmallVector<Expr*, 8> ClsExprs;
2785 QualType argType = Context->getPointerType(Context->CharTy);
2786 ClsExprs.push_back(StringLiteral::Create(*Context,
2787 ClassDecl->getIdentifier()->getNameStart(),
2788 ClassDecl->getIdentifier()->getLength(),
2789 false, argType, SourceLocation()));
2790 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2791 &ClsExprs[0],
2792 ClsExprs.size(),
2793 StartLoc,
2794 EndLoc);
2795 // (Class)objc_getClass("CurrentClass")
2796 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2797 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002798 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002799 ClsExprs.clear();
2800 ClsExprs.push_back(ArgExpr);
2801 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2802 &ClsExprs[0], ClsExprs.size(),
2803 StartLoc, EndLoc);
2804
2805 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2806 // To turn off a warning, type-cast to 'id'
2807 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2808 NoTypeInfoCStyleCastExpr(Context,
2809 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002810 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002811 // struct objc_super
2812 QualType superType = getSuperStructType();
2813 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002814
Douglas Gregor04badcf2010-04-21 00:45:42 +00002815 if (LangOpts.Microsoft) {
2816 SynthSuperContructorFunctionDecl();
2817 // Simulate a contructor call...
2818 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002819 superType, VK_LValue,
2820 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002821 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2822 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002823 superType, VK_LValue,
2824 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002825 // The code for super is a little tricky to prevent collision with
2826 // the structure definition in the header. The rewriter has it's own
2827 // internal definition (__rw_objc_super) that is uses. This is why
2828 // we need the cast below. For example:
2829 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2830 //
John McCall2de56d12010-08-25 11:45:40 +00002831 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002832 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002833 VK_RValue, OK_Ordinary,
2834 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002835 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2836 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002837 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002838 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002839 // (struct objc_super) { <exprs from above> }
2840 InitListExpr *ILE =
2841 new (Context) InitListExpr(*Context, SourceLocation(),
2842 &InitExprs[0], InitExprs.size(),
2843 SourceLocation());
2844 TypeSourceInfo *superTInfo
2845 = Context->getTrivialTypeSourceInfo(superType);
2846 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002847 superType, VK_LValue,
2848 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002849 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002850 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002851 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002852 VK_RValue, OK_Ordinary,
2853 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002854 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002855 MsgExprs.push_back(SuperRep);
2856 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002857 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002858
2859 case ObjCMessageExpr::Class: {
2860 llvm::SmallVector<Expr*, 8> ClsExprs;
2861 QualType argType = Context->getPointerType(Context->CharTy);
2862 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002863 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002864 IdentifierInfo *clsName = Class->getIdentifier();
2865 ClsExprs.push_back(StringLiteral::Create(*Context,
2866 clsName->getNameStart(),
2867 clsName->getLength(),
2868 false, argType,
2869 SourceLocation()));
2870 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2871 &ClsExprs[0],
2872 ClsExprs.size(),
2873 StartLoc, EndLoc);
2874 MsgExprs.push_back(Cls);
2875 break;
2876 }
2877
2878 case ObjCMessageExpr::SuperInstance:{
2879 MsgSendFlavor = MsgSendSuperFunctionDecl;
2880 if (MsgSendStretFlavor)
2881 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2882 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2883 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2884 llvm::SmallVector<Expr*, 4> InitExprs;
2885
2886 InitExprs.push_back(
2887 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002888 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002889 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002890 Context->getObjCIdType(),
2891 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002892 ); // set the 'receiver'.
2893
2894 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2895 llvm::SmallVector<Expr*, 8> ClsExprs;
2896 QualType argType = Context->getPointerType(Context->CharTy);
2897 ClsExprs.push_back(StringLiteral::Create(*Context,
2898 ClassDecl->getIdentifier()->getNameStart(),
2899 ClassDecl->getIdentifier()->getLength(),
2900 false, argType, SourceLocation()));
2901 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2902 &ClsExprs[0],
2903 ClsExprs.size(),
2904 StartLoc, EndLoc);
2905 // (Class)objc_getClass("CurrentClass")
2906 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2907 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002908 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002909 ClsExprs.clear();
2910 ClsExprs.push_back(ArgExpr);
2911 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2912 &ClsExprs[0], ClsExprs.size(),
2913 StartLoc, EndLoc);
2914
2915 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2916 // To turn off a warning, type-cast to 'id'
2917 InitExprs.push_back(
2918 // set 'super class', using class_getSuperclass().
2919 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002920 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002921 // struct objc_super
2922 QualType superType = getSuperStructType();
2923 Expr *SuperRep;
2924
2925 if (LangOpts.Microsoft) {
2926 SynthSuperContructorFunctionDecl();
2927 // Simulate a contructor call...
2928 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002929 superType, VK_LValue,
2930 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002931 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2932 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002933 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002934 // The code for super is a little tricky to prevent collision with
2935 // the structure definition in the header. The rewriter has it's own
2936 // internal definition (__rw_objc_super) that is uses. This is why
2937 // we need the cast below. For example:
2938 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2939 //
John McCall2de56d12010-08-25 11:45:40 +00002940 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002941 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002942 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002943 SourceLocation());
2944 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2945 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002946 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002947 } else {
2948 // (struct objc_super) { <exprs from above> }
2949 InitListExpr *ILE =
2950 new (Context) InitListExpr(*Context, SourceLocation(),
2951 &InitExprs[0], InitExprs.size(),
2952 SourceLocation());
2953 TypeSourceInfo *superTInfo
2954 = Context->getTrivialTypeSourceInfo(superType);
2955 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002956 superType, VK_RValue, ILE,
2957 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002958 }
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,
John McCallf89e55a2010-11-18 06:31:45 +00003051 VK_LValue, 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.
John McCall0e88aa72010-12-14 06:51:39 +00003062 QualType castType =
3063 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3064 // If we don't have a method decl, force a variadic cast.
3065 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003066 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003067 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003068 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003069
3070 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003071 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003072
John McCall183700f2009-09-21 23:43:11 +00003073 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003074 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003075 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003076 FT->getResultType(), VK_RValue,
3077 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003078 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003079 if (MsgSendStretFlavor) {
3080 // We have the method which returns a struct/union. Must also generate
3081 // call to objc_msgSend_stret and hang both varieties on a conditional
3082 // expression which dictate which one to envoke depending on size of
3083 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003084
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003085 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003086 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003087 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003088 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003089 cast = NoTypeInfoCStyleCastExpr(Context,
3090 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003091 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003092 // Now do the "normal" pointer to function cast.
John McCall0e88aa72010-12-14 06:51:39 +00003093 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3094 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003095 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003096 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003097 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003098
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003099 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003100 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003101
John McCall183700f2009-09-21 23:43:11 +00003102 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003103 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003104 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003105 FT->getResultType(), VK_RValue,
3106 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003107
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003108 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00003109 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00003110 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00003111 Context->getSizeType(),
3112 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003113 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3114 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3115 // For X86 it is more complicated and some kind of target specific routine
3116 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003117 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003118 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003119 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3120 llvm::APInt(IntSize, 8),
3121 Context->IntTy,
3122 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003123 BinaryOperator *lessThanExpr =
3124 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3125 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003126 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003127 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003128 new (Context) ConditionalOperator(lessThanExpr,
3129 SourceLocation(), CE,
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003130 SourceLocation(), STCE, (Expr*)0,
John McCall09431682010-11-18 19:01:18 +00003131 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003132 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3133 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003134 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003135 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003136 return ReplacingStmt;
3137}
3138
Steve Naroffb29b4272008-04-14 22:03:09 +00003139Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003140 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3141 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003142
Steve Naroff934f2762007-10-24 22:48:43 +00003143 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003144 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003145
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003146 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003147 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003148}
3149
Steve Naroff621edce2009-04-29 16:37:50 +00003150// typedef struct objc_object Protocol;
3151QualType RewriteObjC::getProtocolType() {
3152 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003153 TypeSourceInfo *TInfo
3154 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003155 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003156 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003157 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003158 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003159 }
3160 return Context->getTypeDeclType(ProtocolTypeDecl);
3161}
3162
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003163/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003164/// a synthesized/forward data reference (to the protocol's metadata).
3165/// The forward references (and metadata) are generated in
3166/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003167Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003168 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3169 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003170 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00003171 ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003172 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003173 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3174 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003175 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003176 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003177 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003178 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003179 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003180 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003181 ReplaceStmt(Exp, castExpr);
3182 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003183 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003184 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003185
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003186}
3187
Mike Stump1eb44332009-09-09 15:08:12 +00003188bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003189 const char *endBuf) {
3190 while (startBuf < endBuf) {
3191 if (*startBuf == '#') {
3192 // Skip whitespace.
3193 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3194 ;
3195 if (!strncmp(startBuf, "if", strlen("if")) ||
3196 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3197 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3198 !strncmp(startBuf, "define", strlen("define")) ||
3199 !strncmp(startBuf, "undef", strlen("undef")) ||
3200 !strncmp(startBuf, "else", strlen("else")) ||
3201 !strncmp(startBuf, "elif", strlen("elif")) ||
3202 !strncmp(startBuf, "endif", strlen("endif")) ||
3203 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3204 !strncmp(startBuf, "include", strlen("include")) ||
3205 !strncmp(startBuf, "import", strlen("import")) ||
3206 !strncmp(startBuf, "include_next", strlen("include_next")))
3207 return true;
3208 }
3209 startBuf++;
3210 }
3211 return false;
3212}
3213
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003214/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003215/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003216void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003217 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003218 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003219 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003220 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003221 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003222 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003223 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003224 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003225 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003226 SourceLocation LocStart = CDecl->getLocStart();
3227 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003228
Steve Narofffea763e82007-11-14 19:25:57 +00003229 const char *startBuf = SM->getCharacterData(LocStart);
3230 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003231
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003232 // If no ivars and no root or if its root, directly or indirectly,
3233 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003234 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3235 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003236 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003237 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003238 return;
3239 }
Mike Stump1eb44332009-09-09 15:08:12 +00003240
3241 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003242 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003243 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003244 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003245 if (LangOpts.Microsoft)
3246 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003247
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003248 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003249 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003250 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003251 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003252 // If the buffer contains preprocessor directives, we do more fine-grained
3253 // rewrites. This is intended to fix code that looks like (which occurs in
3254 // NSURL.h, for example):
3255 //
3256 // #ifdef XYZ
3257 // @interface Foo : NSObject
3258 // #else
3259 // @interface FooBar : NSObject
3260 // #endif
3261 // {
3262 // int i;
3263 // }
3264 // @end
3265 //
3266 // This clause is segregated to avoid breaking the common case.
3267 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003268 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003269 CDecl->getClassLoc();
3270 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003271 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003272
Chris Lattnercafeb352009-02-20 18:18:36 +00003273 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003274 // advance to the end of the referenced protocols.
3275 while (endHeader < cursor && *endHeader != '>') endHeader++;
3276 endHeader++;
3277 }
3278 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003279 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003280 } else {
3281 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003282 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003283 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003284 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003285 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003286 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003287 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003288 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003289 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003290
Steve Narofffea763e82007-11-14 19:25:57 +00003291 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003292 SourceLocation OnePastCurly =
3293 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003294 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003295 }
3296 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003297
Steve Narofffea763e82007-11-14 19:25:57 +00003298 // Now comment out any visibility specifiers.
3299 while (cursor < endBuf) {
3300 if (*cursor == '@') {
3301 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003302 // Skip whitespace.
3303 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3304 /*scan*/;
3305
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003306 // FIXME: presence of @public, etc. inside comment results in
3307 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003308 if (!strncmp(cursor, "public", strlen("public")) ||
3309 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003310 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003311 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003312 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003313 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003314 // FIXME: If there are cases where '<' is used in ivar declaration part
3315 // of user code, then scan the ivar list and use needToScanForQualifiers
3316 // for type checking.
3317 else if (*cursor == '<') {
3318 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003319 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003320 cursor = strchr(cursor, '>');
3321 cursor++;
3322 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003323 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003324 } else if (*cursor == '^') { // rewrite block specifier.
3325 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003326 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003327 }
Steve Narofffea763e82007-11-14 19:25:57 +00003328 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003329 }
Steve Narofffea763e82007-11-14 19:25:57 +00003330 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003331 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003332 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003333 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003334 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003335 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003336 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003337 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003338 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003339 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003340 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003341 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003342 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003343 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003344}
3345
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003346// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003347/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003348template<typename MethodIterator>
3349void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3350 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003351 bool IsInstanceMethod,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003352 llvm::StringRef prefix,
3353 llvm::StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003354 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003355 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003356
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003357 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003358 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003359 SEL _cmd;
3360 char *method_types;
3361 void *_imp;
3362 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003363 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003364 Result += "\nstruct _objc_method {\n";
3365 Result += "\tSEL _cmd;\n";
3366 Result += "\tchar *method_types;\n";
3367 Result += "\tvoid *_imp;\n";
3368 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003369
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003370 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003371 }
Mike Stump1eb44332009-09-09 15:08:12 +00003372
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003373 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003374
Steve Naroff946a6932008-03-11 00:12:29 +00003375 /* struct {
3376 struct _objc_method_list *next_method;
3377 int method_count;
3378 struct _objc_method method_list[];
3379 }
3380 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003381 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003382 Result += "\nstatic struct {\n";
3383 Result += "\tstruct _objc_method_list *next_method;\n";
3384 Result += "\tint method_count;\n";
3385 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003386 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003387 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003388 Result += prefix;
3389 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3390 Result += "_METHODS_";
3391 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003392 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003393 Result += IsInstanceMethod ? "inst" : "cls";
3394 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003395 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003396
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003397 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003398 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003399 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003400 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003401 Result += "\", \"";
3402 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003403 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003404 Result += MethodInternalNames[*MethodBegin];
3405 Result += "}\n";
3406 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3407 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003408 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003409 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003410 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003411 Result += "\", \"";
3412 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003413 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003414 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003415 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003416 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003417 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003418}
3419
Steve Naroff621edce2009-04-29 16:37:50 +00003420/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003421void RewriteObjC::
Daniel Dunbar4087f272010-08-17 22:39:59 +00003422RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3423 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003424 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003425
3426 // Output struct protocol_methods holder of method selector and type.
3427 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3428 /* struct protocol_methods {
3429 SEL _cmd;
3430 char *method_types;
3431 }
3432 */
3433 Result += "\nstruct _protocol_methods {\n";
3434 Result += "\tstruct objc_selector *_cmd;\n";
3435 Result += "\tchar *method_types;\n";
3436 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003437
Steve Naroff621edce2009-04-29 16:37:50 +00003438 objc_protocol_methods = true;
3439 }
3440 // Do not synthesize the protocol more than once.
3441 if (ObjCSynthesizedProtocols.count(PDecl))
3442 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003443
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003444 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3445 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3446 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003447 /* struct _objc_protocol_method_list {
3448 int protocol_method_count;
3449 struct protocol_methods protocols[];
3450 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003451 */
Steve Naroff621edce2009-04-29 16:37:50 +00003452 Result += "\nstatic struct {\n";
3453 Result += "\tint protocol_method_count;\n";
3454 Result += "\tstruct _protocol_methods protocol_methods[";
3455 Result += utostr(NumMethods);
3456 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3457 Result += PDecl->getNameAsString();
3458 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3459 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003460
Steve Naroff621edce2009-04-29 16:37:50 +00003461 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003462 for (ObjCProtocolDecl::instmeth_iterator
3463 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003464 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003465 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003466 Result += "\t ,{{(struct objc_selector *)\"";
3467 else
3468 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003469 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003470 std::string MethodTypeString;
3471 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3472 Result += "\", \"";
3473 Result += MethodTypeString;
3474 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003475 }
Steve Naroff621edce2009-04-29 16:37:50 +00003476 Result += "\t }\n};\n";
3477 }
Mike Stump1eb44332009-09-09 15:08:12 +00003478
Steve Naroff621edce2009-04-29 16:37:50 +00003479 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003480 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3481 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003482 if (NumMethods > 0) {
3483 /* struct _objc_protocol_method_list {
3484 int protocol_method_count;
3485 struct protocol_methods protocols[];
3486 }
3487 */
3488 Result += "\nstatic struct {\n";
3489 Result += "\tint protocol_method_count;\n";
3490 Result += "\tstruct _protocol_methods protocol_methods[";
3491 Result += utostr(NumMethods);
3492 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3493 Result += PDecl->getNameAsString();
3494 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3495 "{\n\t";
3496 Result += utostr(NumMethods);
3497 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003498
Steve Naroff621edce2009-04-29 16:37:50 +00003499 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003500 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003501 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003502 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003503 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003504 Result += "\t ,{{(struct objc_selector *)\"";
3505 else
3506 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003507 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003508 std::string MethodTypeString;
3509 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3510 Result += "\", \"";
3511 Result += MethodTypeString;
3512 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003513 }
Steve Naroff621edce2009-04-29 16:37:50 +00003514 Result += "\t }\n};\n";
3515 }
3516
3517 // Output:
3518 /* struct _objc_protocol {
3519 // Objective-C 1.0 extensions
3520 struct _objc_protocol_extension *isa;
3521 char *protocol_name;
3522 struct _objc_protocol **protocol_list;
3523 struct _objc_protocol_method_list *instance_methods;
3524 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003525 };
Steve Naroff621edce2009-04-29 16:37:50 +00003526 */
3527 static bool objc_protocol = false;
3528 if (!objc_protocol) {
3529 Result += "\nstruct _objc_protocol {\n";
3530 Result += "\tstruct _objc_protocol_extension *isa;\n";
3531 Result += "\tchar *protocol_name;\n";
3532 Result += "\tstruct _objc_protocol **protocol_list;\n";
3533 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3534 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003535 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003536
Steve Naroff621edce2009-04-29 16:37:50 +00003537 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003538 }
Mike Stump1eb44332009-09-09 15:08:12 +00003539
Steve Naroff621edce2009-04-29 16:37:50 +00003540 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3541 Result += PDecl->getNameAsString();
3542 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3543 "{\n\t0, \"";
3544 Result += PDecl->getNameAsString();
3545 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003546 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003547 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3548 Result += PDecl->getNameAsString();
3549 Result += ", ";
3550 }
3551 else
3552 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003553 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003554 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3555 Result += PDecl->getNameAsString();
3556 Result += "\n";
3557 }
3558 else
3559 Result += "0\n";
3560 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003561
Steve Naroff621edce2009-04-29 16:37:50 +00003562 // Mark this protocol as having been generated.
3563 if (!ObjCSynthesizedProtocols.insert(PDecl))
3564 assert(false && "protocol already synthesized");
3565
3566}
3567
3568void RewriteObjC::
3569RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003570 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003571 std::string &Result) {
3572 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003573
Steve Naroff621edce2009-04-29 16:37:50 +00003574 for (unsigned i = 0; i != Protocols.size(); i++)
3575 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3576
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003577 // Output the top lovel protocol meta-data for the class.
3578 /* struct _objc_protocol_list {
3579 struct _objc_protocol_list *next;
3580 int protocol_count;
3581 struct _objc_protocol *class_protocols[];
3582 }
3583 */
3584 Result += "\nstatic struct {\n";
3585 Result += "\tstruct _objc_protocol_list *next;\n";
3586 Result += "\tint protocol_count;\n";
3587 Result += "\tstruct _objc_protocol *class_protocols[";
3588 Result += utostr(Protocols.size());
3589 Result += "];\n} _OBJC_";
3590 Result += prefix;
3591 Result += "_PROTOCOLS_";
3592 Result += ClassName;
3593 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3594 "{\n\t0, ";
3595 Result += utostr(Protocols.size());
3596 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003597
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003598 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003599 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003600 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003601
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003602 for (unsigned i = 1; i != Protocols.size(); i++) {
3603 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003604 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003605 Result += "\n";
3606 }
3607 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003608}
3609
Steve Naroff621edce2009-04-29 16:37:50 +00003610
Mike Stump1eb44332009-09-09 15:08:12 +00003611/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003612/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003613void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003614 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003615 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003616 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003617 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003618 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003619 CDecl = CDecl->getNextClassCategory())
3620 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3621 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003623 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003624 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003625 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003626
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003627 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003628 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003629 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003630
3631 // If any of our property implementations have associated getters or
3632 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003633 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3634 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003635 Prop != PropEnd; ++Prop) {
3636 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3637 continue;
3638 if (!(*Prop)->getPropertyIvarDecl())
3639 continue;
3640 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3641 if (!PD)
3642 continue;
3643 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3644 InstanceMethods.push_back(Getter);
3645 if (PD->isReadOnly())
3646 continue;
3647 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3648 InstanceMethods.push_back(Setter);
3649 }
3650 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003651 true, "CATEGORY_", FullCategoryName.c_str(),
3652 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003653
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003654 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003655 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003656 false, "CATEGORY_", FullCategoryName.c_str(),
3657 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003658
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003659 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003660 // Null CDecl is case of a category implementation with no category interface
3661 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003662 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003663 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003664 /* struct _objc_category {
3665 char *category_name;
3666 char *class_name;
3667 struct _objc_method_list *instance_methods;
3668 struct _objc_method_list *class_methods;
3669 struct _objc_protocol_list *protocols;
3670 // Objective-C 1.0 extensions
3671 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003672 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003673 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003674 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003675 */
Mike Stump1eb44332009-09-09 15:08:12 +00003676
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003677 static bool objc_category = false;
3678 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003679 Result += "\nstruct _objc_category {\n";
3680 Result += "\tchar *category_name;\n";
3681 Result += "\tchar *class_name;\n";
3682 Result += "\tstruct _objc_method_list *instance_methods;\n";
3683 Result += "\tstruct _objc_method_list *class_methods;\n";
3684 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003685 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003686 Result += "\tstruct _objc_property_list *instance_properties;\n";
3687 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003688 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003689 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003690 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3691 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003692 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003693 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003694 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003695 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003696 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003697
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003698 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003699 Result += "\t, (struct _objc_method_list *)"
3700 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3701 Result += FullCategoryName;
3702 Result += "\n";
3703 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003704 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003705 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003706 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003707 Result += "\t, (struct _objc_method_list *)"
3708 "&_OBJC_CATEGORY_CLASS_METHODS_";
3709 Result += FullCategoryName;
3710 Result += "\n";
3711 }
3712 else
3713 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003714
Chris Lattnercafeb352009-02-20 18:18:36 +00003715 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003716 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003717 Result += FullCategoryName;
3718 Result += "\n";
3719 }
3720 else
3721 Result += "\t, 0\n";
3722 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003723}
3724
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003725/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3726/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003727void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003728 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003729 if (ivar->isBitField()) {
3730 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3731 // place all bitfields at offset 0.
3732 Result += "0";
3733 } else {
3734 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003735 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003736 if (LangOpts.Microsoft)
3737 Result += "_IMPL";
3738 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003739 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003740 Result += ")";
3741 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003742}
3743
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003744//===----------------------------------------------------------------------===//
3745// Meta Data Emission
3746//===----------------------------------------------------------------------===//
3747
Steve Naroffb29b4272008-04-14 22:03:09 +00003748void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003749 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003750 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003751
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003752 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003753 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003754 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003755 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003756 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003757 }
Mike Stump1eb44332009-09-09 15:08:12 +00003758
Chris Lattnerbe6df082007-12-12 07:56:42 +00003759 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003760 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003761 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003762 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003763 if (NumIvars > 0) {
3764 static bool objc_ivar = false;
3765 if (!objc_ivar) {
3766 /* struct _objc_ivar {
3767 char *ivar_name;
3768 char *ivar_type;
3769 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003770 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003771 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003772 Result += "\nstruct _objc_ivar {\n";
3773 Result += "\tchar *ivar_name;\n";
3774 Result += "\tchar *ivar_type;\n";
3775 Result += "\tint ivar_offset;\n";
3776 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003777
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003778 objc_ivar = true;
3779 }
3780
Steve Naroff946a6932008-03-11 00:12:29 +00003781 /* struct {
3782 int ivar_count;
3783 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003784 };
Steve Naroff946a6932008-03-11 00:12:29 +00003785 */
Mike Stump1eb44332009-09-09 15:08:12 +00003786 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003787 Result += "\tint ivar_count;\n";
3788 Result += "\tstruct _objc_ivar ivar_list[";
3789 Result += utostr(NumIvars);
3790 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003791 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003792 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003793 "{\n\t";
3794 Result += utostr(NumIvars);
3795 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003796
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003797 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003798 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003799 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003800 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003801 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003802 IV != IVEnd; ++IV)
3803 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003804 IVI = IDecl->ivar_begin();
3805 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003806 } else {
3807 IVI = CDecl->ivar_begin();
3808 IVE = CDecl->ivar_end();
3809 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003810 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003811 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003812 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003813 std::string TmpString, StrEncoding;
3814 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3815 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003816 Result += StrEncoding;
3817 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003818 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003819 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003820 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003821 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003822 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003823 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003824 std::string TmpString, StrEncoding;
3825 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3826 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003827 Result += StrEncoding;
3828 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003829 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003830 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003831 }
Mike Stump1eb44332009-09-09 15:08:12 +00003832
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003833 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003834 }
Mike Stump1eb44332009-09-09 15:08:12 +00003835
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003836 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003837 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003838 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003839
3840 // If any of our property implementations have associated getters or
3841 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003842 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3843 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003844 Prop != PropEnd; ++Prop) {
3845 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3846 continue;
3847 if (!(*Prop)->getPropertyIvarDecl())
3848 continue;
3849 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3850 if (!PD)
3851 continue;
3852 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003853 if (!Getter->isDefined())
3854 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003855 if (PD->isReadOnly())
3856 continue;
3857 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003858 if (!Setter->isDefined())
3859 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003860 }
3861 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003862 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003863
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003864 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003865 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003866 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003867
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003868 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003869 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003870 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003871
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003872 // Declaration of class/meta-class metadata
3873 /* struct _objc_class {
3874 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003875 const char *super_class_name;
3876 char *name;
3877 long version;
3878 long info;
3879 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003880 struct _objc_ivar_list *ivars;
3881 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003882 struct objc_cache *cache;
3883 struct objc_protocol_list *protocols;
3884 const char *ivar_layout;
3885 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003886 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003887 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003888 static bool objc_class = false;
3889 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003890 Result += "\nstruct _objc_class {\n";
3891 Result += "\tstruct _objc_class *isa;\n";
3892 Result += "\tconst char *super_class_name;\n";
3893 Result += "\tchar *name;\n";
3894 Result += "\tlong version;\n";
3895 Result += "\tlong info;\n";
3896 Result += "\tlong instance_size;\n";
3897 Result += "\tstruct _objc_ivar_list *ivars;\n";
3898 Result += "\tstruct _objc_method_list *methods;\n";
3899 Result += "\tstruct objc_cache *cache;\n";
3900 Result += "\tstruct _objc_protocol_list *protocols;\n";
3901 Result += "\tconst char *ivar_layout;\n";
3902 Result += "\tstruct _objc_class_ext *ext;\n";
3903 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003904 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003905 }
Mike Stump1eb44332009-09-09 15:08:12 +00003906
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003907 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003908 ObjCInterfaceDecl *RootClass = 0;
3909 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003910 while (SuperClass) {
3911 RootClass = SuperClass;
3912 SuperClass = SuperClass->getSuperClass();
3913 }
3914 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003915
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003916 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003917 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003918 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003919 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003920 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003921 Result += "\"";
3922
3923 if (SuperClass) {
3924 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003925 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003926 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003927 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003928 Result += "\"";
3929 }
3930 else {
3931 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003932 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003933 Result += "\"";
3934 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003935 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003936 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003937 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003938 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003939 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003940 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003941 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003942 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003943 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003944 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003945 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003946 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003947 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003948 Result += ",0,0\n";
3949 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003950 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003951 Result += "\t,0,0,0,0\n";
3952 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003953
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003954 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003955 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003956 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003957 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003958 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003959 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003960 if (SuperClass) {
3961 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003962 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003963 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003964 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003965 Result += "\"";
3966 }
3967 else {
3968 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003969 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003970 Result += "\"";
3971 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003972 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003973 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003974 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003975 Result += ",0";
3976 else {
3977 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003978 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003979 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003980 if (LangOpts.Microsoft)
3981 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003982 Result += ")";
3983 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003984 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003985 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003986 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003987 Result += "\n\t";
3988 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003989 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003990 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003991 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003992 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003993 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003994 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003995 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003996 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003997 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003998 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003999 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004000 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004001 Result += ", 0,0\n";
4002 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004003 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004004 Result += ",0,0,0\n";
4005 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004006}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004007
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004008/// RewriteImplementations - This routine rewrites all method implementations
4009/// and emits meta-data.
4010
Steve Narofface66252008-11-13 20:07:04 +00004011void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004012 int ClsDefCount = ClassImplementation.size();
4013 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004014
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004015 // Rewrite implemented methods
4016 for (int i = 0; i < ClsDefCount; i++)
4017 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004018
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004019 for (int i = 0; i < CatDefCount; i++)
4020 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004021}
Mike Stump1eb44332009-09-09 15:08:12 +00004022
Steve Narofface66252008-11-13 20:07:04 +00004023void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4024 int ClsDefCount = ClassImplementation.size();
4025 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004026
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004027 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004028 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004029 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004030
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004031 // For each implemented category, write out all its meta data.
4032 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004033 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004034
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004035 // Write objc_symtab metadata
4036 /*
4037 struct _objc_symtab
4038 {
4039 long sel_ref_cnt;
4040 SEL *refs;
4041 short cls_def_cnt;
4042 short cat_def_cnt;
4043 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004044 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004045 */
Mike Stump1eb44332009-09-09 15:08:12 +00004046
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004047 Result += "\nstruct _objc_symtab {\n";
4048 Result += "\tlong sel_ref_cnt;\n";
4049 Result += "\tSEL *refs;\n";
4050 Result += "\tshort cls_def_cnt;\n";
4051 Result += "\tshort cat_def_cnt;\n";
4052 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4053 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004054
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004055 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004056 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004057 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004058 + ", " + utostr(CatDefCount) + "\n";
4059 for (int i = 0; i < ClsDefCount; i++) {
4060 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004061 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004062 Result += "\n";
4063 }
Mike Stump1eb44332009-09-09 15:08:12 +00004064
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004065 for (int i = 0; i < CatDefCount; i++) {
4066 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004067 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004068 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004069 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004070 Result += "\n";
4071 }
Mike Stump1eb44332009-09-09 15:08:12 +00004072
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004073 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004074
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004075 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004076
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004077 /*
4078 struct _objc_module {
4079 long version;
4080 long size;
4081 const char *name;
4082 struct _objc_symtab *symtab;
4083 }
4084 */
Mike Stump1eb44332009-09-09 15:08:12 +00004085
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004086 Result += "\nstruct _objc_module {\n";
4087 Result += "\tlong version;\n";
4088 Result += "\tlong size;\n";
4089 Result += "\tconst char *name;\n";
4090 Result += "\tstruct _objc_symtab *symtab;\n";
4091 Result += "};\n\n";
4092 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004093 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004094 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004095 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004096 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004097
4098 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004099 if (ProtocolExprDecls.size()) {
4100 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4101 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004102 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004103 E = ProtocolExprDecls.end(); I != E; ++I) {
4104 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4105 Result += (*I)->getNameAsString();
4106 Result += " = &_OBJC_PROTOCOL_";
4107 Result += (*I)->getNameAsString();
4108 Result += ";\n";
4109 }
4110 Result += "#pragma data_seg(pop)\n\n";
4111 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004112 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004113 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004114 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4115 Result += "&_OBJC_MODULES;\n";
4116 Result += "#pragma data_seg(pop)\n\n";
4117 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004118}
Chris Lattner311ff022007-10-16 22:36:42 +00004119
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004120void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4121 const std::string &Name,
4122 ValueDecl *VD) {
4123 assert(BlockByRefDeclNo.count(VD) &&
4124 "RewriteByRefString: ByRef decl missing");
4125 ResultStr += "struct __Block_byref_" + Name +
4126 "_" + utostr(BlockByRefDeclNo[VD]) ;
4127}
4128
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004129static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4130 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4131 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4132 return false;
4133}
4134
Steve Naroff54055232008-10-27 17:20:55 +00004135std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004136 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004137 std::string Tag) {
4138 const FunctionType *AFT = CE->getFunctionType();
4139 QualType RT = AFT->getResultType();
4140 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004141 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004142 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004143
Steve Naroff54055232008-10-27 17:20:55 +00004144 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004145
Douglas Gregor72564e72009-02-26 23:50:07 +00004146 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004147 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004148 // block (to reference imported block decl refs).
4149 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004150 } else if (BD->param_empty()) {
4151 S += "(" + StructRef + " *__cself)";
4152 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004153 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004154 assert(FT && "SynthesizeBlockFunc: No function proto");
4155 S += '(';
4156 // first add the implicit argument.
4157 S += StructRef + " *__cself, ";
4158 std::string ParamStr;
4159 for (BlockDecl::param_iterator AI = BD->param_begin(),
4160 E = BD->param_end(); AI != E; ++AI) {
4161 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004162 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004163 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004164 if (convertBlockPointerToFunctionPointer(QT))
4165 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004166 else
4167 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004168 S += ParamStr;
4169 }
4170 if (FT->isVariadic()) {
4171 if (!BD->param_empty()) S += ", ";
4172 S += "...";
4173 }
4174 S += ')';
4175 }
4176 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004177
Steve Naroff54055232008-10-27 17:20:55 +00004178 // Create local declarations to avoid rewriting all closure decl ref exprs.
4179 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004180 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004181 E = BlockByRefDecls.end(); I != E; ++I) {
4182 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004183 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004184 std::string TypeString;
4185 RewriteByRefString(TypeString, Name, (*I));
4186 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004187 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004188 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004189 }
Steve Naroff54055232008-10-27 17:20:55 +00004190 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004191 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004192 E = BlockByCopyDecls.end(); I != E; ++I) {
4193 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004194 // Handle nested closure invocation. For example:
4195 //
4196 // void (^myImportedClosure)(void);
4197 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004198 //
Steve Naroff54055232008-10-27 17:20:55 +00004199 // void (^anotherClosure)(void);
4200 // anotherClosure = ^(void) {
4201 // myImportedClosure(); // import and invoke the closure
4202 // };
4203 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004204 if (isTopLevelBlockPointerType((*I)->getType())) {
4205 RewriteBlockPointerTypeVariable(S, (*I));
4206 S += " = (";
4207 RewriteBlockPointerType(S, (*I)->getType());
4208 S += ")";
4209 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4210 }
4211 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004212 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004213 QualType QT = (*I)->getType();
4214 if (HasLocalVariableExternalStorage(*I))
4215 QT = Context->getPointerType(QT);
4216 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004217 S += Name + " = __cself->" +
4218 (*I)->getNameAsString() + "; // bound by copy\n";
4219 }
Steve Naroff54055232008-10-27 17:20:55 +00004220 }
4221 std::string RewrittenStr = RewrittenBlockExprs[CE];
4222 const char *cstr = RewrittenStr.c_str();
4223 while (*cstr++ != '{') ;
4224 S += cstr;
4225 S += "\n";
4226 return S;
4227}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004228
Steve Naroff54055232008-10-27 17:20:55 +00004229std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004230 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004231 std::string Tag) {
4232 std::string StructRef = "struct " + Tag;
4233 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004234
Steve Naroff54055232008-10-27 17:20:55 +00004235 S += funcName;
4236 S += "_block_copy_" + utostr(i);
4237 S += "(" + StructRef;
4238 S += "*dst, " + StructRef;
4239 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004240 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004241 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004242 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004243 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004244 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004245 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004246 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004247 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004248 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004249 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004250 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004251 S += "}\n";
4252
Steve Naroff54055232008-10-27 17:20:55 +00004253 S += "\nstatic void __";
4254 S += funcName;
4255 S += "_block_dispose_" + utostr(i);
4256 S += "(" + StructRef;
4257 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004258 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004259 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004260 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004261 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004262 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004263 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004264 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004265 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004266 }
Mike Stump1eb44332009-09-09 15:08:12 +00004267 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004268 return S;
4269}
4270
Steve Naroff01aec112009-12-06 21:14:13 +00004271std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4272 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004273 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004274 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004275
Steve Naroff54055232008-10-27 17:20:55 +00004276 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004277 S += " struct " + Desc;
4278 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004279
Steve Naroff01aec112009-12-06 21:14:13 +00004280 Constructor += "(void *fp, "; // Invoke function pointer.
4281 Constructor += "struct " + Desc; // Descriptor pointer.
4282 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004283
Steve Naroff54055232008-10-27 17:20:55 +00004284 if (BlockDeclRefs.size()) {
4285 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004286 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004287 E = BlockByCopyDecls.end(); I != E; ++I) {
4288 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004289 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004290 std::string ArgName = "_" + FieldName;
4291 // Handle nested closure invocation. For example:
4292 //
4293 // void (^myImportedBlock)(void);
4294 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004295 //
Steve Naroff54055232008-10-27 17:20:55 +00004296 // void (^anotherBlock)(void);
4297 // anotherBlock = ^(void) {
4298 // myImportedBlock(); // import and invoke the closure
4299 // };
4300 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004301 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004302 S += "struct __block_impl *";
4303 Constructor += ", void *" + ArgName;
4304 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004305 QualType QT = (*I)->getType();
4306 if (HasLocalVariableExternalStorage(*I))
4307 QT = Context->getPointerType(QT);
4308 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4309 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004310 Constructor += ", " + ArgName;
4311 }
4312 S += FieldName + ";\n";
4313 }
4314 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004315 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004316 E = BlockByRefDecls.end(); I != E; ++I) {
4317 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004318 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004319 std::string ArgName = "_" + FieldName;
4320 // Handle nested closure invocation. For example:
4321 //
4322 // void (^myImportedBlock)(void);
4323 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004324 //
Steve Naroff54055232008-10-27 17:20:55 +00004325 // void (^anotherBlock)(void);
4326 // anotherBlock = ^(void) {
4327 // myImportedBlock(); // import and invoke the closure
4328 // };
4329 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004330 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004331 S += "struct __block_impl *";
4332 Constructor += ", void *" + ArgName;
4333 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004334 std::string TypeString;
4335 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004336 TypeString += " *";
4337 FieldName = TypeString + FieldName;
4338 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004339 Constructor += ", " + ArgName;
4340 }
4341 S += FieldName + "; // by ref\n";
4342 }
4343 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004344 Constructor += ", int flags=0)";
4345 // Initialize all "by copy" arguments.
4346 bool firsTime = true;
4347 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4348 E = BlockByCopyDecls.end(); I != E; ++I) {
4349 std::string Name = (*I)->getNameAsString();
4350 if (firsTime) {
4351 Constructor += " : ";
4352 firsTime = false;
4353 }
4354 else
4355 Constructor += ", ";
4356 if (isTopLevelBlockPointerType((*I)->getType()))
4357 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4358 else
4359 Constructor += Name + "(_" + Name + ")";
4360 }
4361 // Initialize all "by ref" arguments.
4362 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4363 E = BlockByRefDecls.end(); I != E; ++I) {
4364 std::string Name = (*I)->getNameAsString();
4365 if (firsTime) {
4366 Constructor += " : ";
4367 firsTime = false;
4368 }
4369 else
4370 Constructor += ", ";
4371 if (isTopLevelBlockPointerType((*I)->getType()))
4372 Constructor += Name + "((struct __block_impl *)_"
4373 + Name + "->__forwarding)";
4374 else
4375 Constructor += Name + "(_" + Name + "->__forwarding)";
4376 }
4377
4378 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004379 if (GlobalVarDecl)
4380 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4381 else
4382 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004383 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004384
Steve Naroff01aec112009-12-06 21:14:13 +00004385 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004386 } else {
4387 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004388 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004389 if (GlobalVarDecl)
4390 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4391 else
4392 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004393 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4394 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004395 }
4396 Constructor += " ";
4397 Constructor += "}\n";
4398 S += Constructor;
4399 S += "};\n";
4400 return S;
4401}
4402
Steve Naroff01aec112009-12-06 21:14:13 +00004403std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4404 std::string ImplTag, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004405 llvm::StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004406 unsigned hasCopy) {
4407 std::string S = "\nstatic struct " + DescTag;
4408
4409 S += " {\n unsigned long reserved;\n";
4410 S += " unsigned long Block_size;\n";
4411 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004412 S += " void (*copy)(struct ";
4413 S += ImplTag; S += "*, struct ";
4414 S += ImplTag; S += "*);\n";
4415
4416 S += " void (*dispose)(struct ";
4417 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004418 }
4419 S += "} ";
4420
4421 S += DescTag + "_DATA = { 0, sizeof(struct ";
4422 S += ImplTag + ")";
4423 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004424 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4425 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004426 }
4427 S += "};\n";
4428 return S;
4429}
4430
Steve Naroff54055232008-10-27 17:20:55 +00004431void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004432 llvm::StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004433 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004434 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004435 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004436 bool RewriteSC = (GlobalVarDecl &&
4437 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004438 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004439 GlobalVarDecl->getType().getCVRQualifiers());
4440 if (RewriteSC) {
4441 std::string SC(" void __");
4442 SC += GlobalVarDecl->getNameAsString();
4443 SC += "() {}";
4444 InsertText(FunLocStart, SC);
4445 }
4446
Steve Naroff54055232008-10-27 17:20:55 +00004447 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004448 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4449 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004450 // Need to copy-in the inner copied-in variables not actually used in this
4451 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004452 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4453 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4454 ValueDecl *VD = Exp->getDecl();
4455 BlockDeclRefs.push_back(Exp);
4456 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4457 BlockByCopyDeclsPtrSet.insert(VD);
4458 BlockByCopyDecls.push_back(VD);
4459 }
4460 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4461 BlockByRefDeclsPtrSet.insert(VD);
4462 BlockByRefDecls.push_back(VD);
4463 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004464 // imported objects in the inner blocks not used in the outer
4465 // blocks must be copied/disposed in the outer block as well.
4466 if (Exp->isByRef() ||
4467 VD->getType()->isObjCObjectPointerType() ||
4468 VD->getType()->isBlockPointerType())
4469 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004470 }
Steve Naroff54055232008-10-27 17:20:55 +00004471
Daniel Dunbar4087f272010-08-17 22:39:59 +00004472 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4473 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004474
Steve Naroff01aec112009-12-06 21:14:13 +00004475 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004476
Benjamin Kramerd999b372010-02-14 14:14:16 +00004477 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004478
Steve Naroff01aec112009-12-06 21:14:13 +00004479 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004480
Benjamin Kramerd999b372010-02-14 14:14:16 +00004481 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004482
4483 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004484 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004485 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004486 }
Steve Naroff01aec112009-12-06 21:14:13 +00004487 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4488 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004489 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004490
Steve Naroff54055232008-10-27 17:20:55 +00004491 BlockDeclRefs.clear();
4492 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004493 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004494 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004495 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004496 ImportedBlockDecls.clear();
4497 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004498 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004499 // Must insert any 'const/volatile/static here. Since it has been
4500 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004501 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004502 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004503 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004504 if (GlobalVarDecl->getType().isConstQualified())
4505 SC += "const ";
4506 if (GlobalVarDecl->getType().isVolatileQualified())
4507 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004508 if (GlobalVarDecl->getType().isRestrictQualified())
4509 SC += "restrict ";
4510 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004511 }
4512
Steve Naroff54055232008-10-27 17:20:55 +00004513 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004514 InnerDeclRefsCount.clear();
4515 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004516 RewrittenBlockExprs.clear();
4517}
4518
4519void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4520 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004521 llvm::StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004522
Steve Naroff54055232008-10-27 17:20:55 +00004523 SynthesizeBlockLiterals(FunLocStart, FuncName);
4524}
4525
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004526static void BuildUniqueMethodName(std::string &Name,
4527 ObjCMethodDecl *MD) {
4528 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004529 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004530 Name += "__" + MD->getSelector().getAsString();
4531 // Convert colons to underscores.
4532 std::string::size_type loc = 0;
4533 while ((loc = Name.find(":", loc)) != std::string::npos)
4534 Name.replace(loc, 1, "_");
4535}
4536
Steve Naroff54055232008-10-27 17:20:55 +00004537void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004538 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4539 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004540 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004541 std::string FuncName;
4542 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004543 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004544}
4545
4546void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4547 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4548 CI != E; ++CI)
4549 if (*CI) {
4550 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4551 GetBlockDeclRefExprs(CBE->getBody());
4552 else
4553 GetBlockDeclRefExprs(*CI);
4554 }
4555 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004556 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004557 // FIXME: Handle enums.
4558 if (!isa<FunctionDecl>(CDRE->getDecl()))
4559 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004560 }
4561 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4562 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4563 BlockDeclRefExpr *BDRE =
4564 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004565 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004566 BlockDeclRefs.push_back(BDRE);
4567 }
4568
Steve Naroff54055232008-10-27 17:20:55 +00004569 return;
4570}
4571
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004572void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4573 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004574 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004575 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4576 CI != E; ++CI)
4577 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004578 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4579 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004580 GetInnerBlockDeclRefExprs(CBE->getBody(),
4581 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004582 InnerContexts);
4583 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004584 else
4585 GetInnerBlockDeclRefExprs(*CI,
4586 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004587 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004588
4589 }
4590 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004591 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004592 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004593 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004594 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004595 }
4596 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4597 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4598 if (Var->isFunctionOrMethodVarDecl())
4599 ImportedLocalExternalDecls.insert(Var);
4600 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004601
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004602 return;
4603}
4604
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004605/// convertFunctionTypeOfBlocks - This routine converts a function type
4606/// whose result type may be a block pointer or whose argument type(s)
4607/// might be block pointers to an equivalent funtion type replacing
4608/// all block pointers to function pointers.
4609QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4610 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4611 // FTP will be null for closures that don't take arguments.
4612 // Generate a funky cast.
4613 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004614 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004615 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004616
4617 if (FTP) {
4618 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4619 E = FTP->arg_type_end(); I && (I != E); ++I) {
4620 QualType t = *I;
4621 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004622 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004623 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004624 ArgTypes.push_back(t);
4625 }
4626 }
4627 QualType FuncType;
4628 // FIXME. Does this work if block takes no argument but has a return type
4629 // which is of block type?
4630 if (HasBlockType)
John McCall0e88aa72010-12-14 06:51:39 +00004631 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004632 else FuncType = QualType(FT, 0);
4633 return FuncType;
4634}
4635
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004636Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004637 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004638 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004639
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004640 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004641 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004642 } else if (const BlockDeclRefExpr *CDRE =
4643 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004644 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004645 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004646 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004647 }
4648 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4649 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4650 }
4651 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4652 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4653 else if (const ConditionalOperator *CEXPR =
4654 dyn_cast<ConditionalOperator>(BlockExp)) {
4655 Expr *LHSExp = CEXPR->getLHS();
4656 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4657 Expr *RHSExp = CEXPR->getRHS();
4658 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4659 Expr *CONDExp = CEXPR->getCond();
4660 ConditionalOperator *CondExpr =
4661 new (Context) ConditionalOperator(CONDExp,
4662 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004663 SourceLocation(), cast<Expr>(RHSStmt),
4664 (Expr*)0,
John McCall09431682010-11-18 19:01:18 +00004665 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004666 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004667 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4668 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004669 } else {
4670 assert(1 && "RewriteBlockClass: Bad type");
4671 }
4672 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004673 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004674 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004675 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004676 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004677
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004678 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004679 SourceLocation(),
4680 &Context->Idents.get("__block_impl"));
4681 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004682
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004683 // Generate a funky cast.
4684 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004685
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004686 // Push the block argument type.
4687 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004688 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004689 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004690 E = FTP->arg_type_end(); I && (I != E); ++I) {
4691 QualType t = *I;
4692 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004693 if (!convertBlockPointerToFunctionPointer(t))
4694 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004695 ArgTypes.push_back(t);
4696 }
Steve Naroff54055232008-10-27 17:20:55 +00004697 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004698 // Now do the pointer to function cast.
John McCall0e88aa72010-12-14 06:51:39 +00004699 QualType PtrToFuncCastType
4700 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004701
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004702 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004703
John McCall9d125032010-01-15 18:39:57 +00004704 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004705 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004706 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004707 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004708 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4709 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004710 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004711
Douglas Gregor44b43212008-12-11 16:49:14 +00004712 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004713 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004714 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004715 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004716 FD->getType(), VK_LValue,
4717 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004718
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004719
John McCall9d125032010-01-15 18:39:57 +00004720 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004721 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004722 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004723
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004724 llvm::SmallVector<Expr*, 8> BlkExprs;
4725 // Add the implicit argument.
4726 BlkExprs.push_back(BlkCast);
4727 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004728 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004729 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004730 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004731 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004732 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4733 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004734 Exp->getType(), VK_RValue,
4735 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004736 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004737}
4738
Steve Naroff621edce2009-04-29 16:37:50 +00004739// We need to return the rewritten expression to handle cases where the
4740// BlockDeclRefExpr is embedded in another expression being rewritten.
4741// For example:
4742//
4743// int main() {
4744// __block Foo *f;
4745// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004746//
Steve Naroff621edce2009-04-29 16:37:50 +00004747// void (^myblock)() = ^() {
4748// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4749// i = 77;
4750// };
4751//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004752Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004753 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004754 // for each DeclRefExp where BYREFVAR is name of the variable.
4755 ValueDecl *VD;
4756 bool isArrow = true;
4757 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4758 VD = BDRE->getDecl();
4759 else {
4760 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4761 isArrow = false;
4762 }
4763
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004764 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4765 &Context->Idents.get("__forwarding"),
4766 Context->VoidPtrTy, 0,
4767 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004768 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4769 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004770 FD->getType(), VK_LValue,
4771 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004772
Daniel Dunbar4087f272010-08-17 22:39:59 +00004773 llvm::StringRef Name = VD->getName();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004774 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4775 &Context->Idents.get(Name),
4776 Context->VoidPtrTy, 0,
4777 /*BitWidth=*/0, /*Mutable=*/true);
4778 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004779 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004780
4781
4782
Steve Naroffdf8570d2009-02-02 17:19:26 +00004783 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004784 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4785 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004786 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004787 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004788}
4789
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004790// Rewrites the imported local variable V with external storage
4791// (static, extern, etc.) as *V
4792//
4793Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4794 ValueDecl *VD = DRE->getDecl();
4795 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4796 if (!ImportedLocalExternalDecls.count(Var))
4797 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004798 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4799 VK_LValue, OK_Ordinary,
4800 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004801 // Need parens to enforce precedence.
4802 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4803 Exp);
4804 ReplaceStmt(DRE, PE);
4805 return PE;
4806}
4807
Steve Naroffb2f9e512008-11-03 23:29:32 +00004808void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4809 SourceLocation LocStart = CE->getLParenLoc();
4810 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004811
4812 // Need to avoid trying to rewrite synthesized casts.
4813 if (LocStart.isInvalid())
4814 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004815 // Need to avoid trying to rewrite casts contained in macros.
4816 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4817 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004818
Steve Naroff54055232008-10-27 17:20:55 +00004819 const char *startBuf = SM->getCharacterData(LocStart);
4820 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004821 QualType QT = CE->getType();
4822 const Type* TypePtr = QT->getAs<Type>();
4823 if (isa<TypeOfExprType>(TypePtr)) {
4824 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4825 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4826 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004827 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004828 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004829 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004830 return;
4831 }
Steve Naroff54055232008-10-27 17:20:55 +00004832 // advance the location to startArgList.
4833 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004834
Steve Naroff54055232008-10-27 17:20:55 +00004835 while (*argPtr++ && (argPtr < endBuf)) {
4836 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004837 case '^':
4838 // Replace the '^' with '*'.
4839 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004840 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004841 break;
Steve Naroff54055232008-10-27 17:20:55 +00004842 }
4843 }
4844 return;
4845}
4846
4847void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4848 SourceLocation DeclLoc = FD->getLocation();
4849 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004850
Steve Naroff54055232008-10-27 17:20:55 +00004851 // We have 1 or more arguments that have closure pointers.
4852 const char *startBuf = SM->getCharacterData(DeclLoc);
4853 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004854
Steve Naroff54055232008-10-27 17:20:55 +00004855 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004856
Steve Naroff54055232008-10-27 17:20:55 +00004857 parenCount++;
4858 // advance the location to startArgList.
4859 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4860 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004861
Steve Naroff54055232008-10-27 17:20:55 +00004862 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004863
Steve Naroff54055232008-10-27 17:20:55 +00004864 while (*argPtr++ && parenCount) {
4865 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004866 case '^':
4867 // Replace the '^' with '*'.
4868 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004869 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004870 break;
4871 case '(':
4872 parenCount++;
4873 break;
4874 case ')':
4875 parenCount--;
4876 break;
Steve Naroff54055232008-10-27 17:20:55 +00004877 }
4878 }
4879 return;
4880}
4881
4882bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004883 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004884 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004885 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004886 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004887 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004888 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004889 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004890 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004891 }
4892 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004893 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004894 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004895 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004896 return true;
4897 }
4898 return false;
4899}
4900
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004901bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4902 const FunctionProtoType *FTP;
4903 const PointerType *PT = QT->getAs<PointerType>();
4904 if (PT) {
4905 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4906 } else {
4907 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4908 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4909 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4910 }
4911 if (FTP) {
4912 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004913 E = FTP->arg_type_end(); I != E; ++I) {
4914 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004915 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004916 if ((*I)->isObjCObjectPointerType() &&
4917 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4918 return true;
4919 }
4920
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004921 }
4922 return false;
4923}
4924
Ted Kremenek8189cde2009-02-07 01:47:29 +00004925void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4926 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004927 const char *argPtr = strchr(Name, '(');
4928 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004929
Steve Naroff54055232008-10-27 17:20:55 +00004930 LParen = argPtr; // output the start.
4931 argPtr++; // skip past the left paren.
4932 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004933
Steve Naroff54055232008-10-27 17:20:55 +00004934 while (*argPtr && parenCount) {
4935 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004936 case '(': parenCount++; break;
4937 case ')': parenCount--; break;
4938 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004939 }
4940 if (parenCount) argPtr++;
4941 }
4942 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4943 RParen = argPtr; // output the end
4944}
4945
4946void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4947 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4948 RewriteBlockPointerFunctionArgs(FD);
4949 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004950 }
Steve Naroff54055232008-10-27 17:20:55 +00004951 // Handle Variables and Typedefs.
4952 SourceLocation DeclLoc = ND->getLocation();
4953 QualType DeclT;
4954 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4955 DeclT = VD->getType();
4956 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4957 DeclT = TDD->getUnderlyingType();
4958 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4959 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004960 else
Steve Naroff54055232008-10-27 17:20:55 +00004961 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004962
Steve Naroff54055232008-10-27 17:20:55 +00004963 const char *startBuf = SM->getCharacterData(DeclLoc);
4964 const char *endBuf = startBuf;
4965 // scan backward (from the decl location) for the end of the previous decl.
4966 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4967 startBuf--;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004968 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4969 std::string buf;
4970 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004971 // *startBuf != '^' if we are dealing with a pointer to function that
4972 // may take block argument types (which will be handled below).
4973 if (*startBuf == '^') {
4974 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004975 buf = '*';
4976 startBuf++;
4977 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004978 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004979 while (*startBuf != ')') {
4980 buf += *startBuf;
4981 startBuf++;
4982 OrigLength++;
4983 }
4984 buf += ')';
4985 OrigLength++;
4986
4987 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4988 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004989 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004990 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004991 DeclLoc = ND->getLocation();
4992 startBuf = SM->getCharacterData(DeclLoc);
4993 const char *argListBegin, *argListEnd;
4994 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4995 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004996 if (*argListBegin == '^')
4997 buf += '*';
4998 else if (*argListBegin == '<') {
4999 buf += "/*";
5000 buf += *argListBegin++;
5001 OrigLength++;;
5002 while (*argListBegin != '>') {
5003 buf += *argListBegin++;
5004 OrigLength++;
5005 }
5006 buf += *argListBegin;
5007 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005008 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005009 else
5010 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005011 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005012 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005013 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005014 buf += ')';
5015 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005016 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005017 ReplaceText(Start, OrigLength, buf);
5018
Steve Naroff54055232008-10-27 17:20:55 +00005019 return;
5020}
5021
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005022
5023/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5024/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5025/// struct Block_byref_id_object *src) {
5026/// _Block_object_assign (&_dest->object, _src->object,
5027/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5028/// [|BLOCK_FIELD_IS_WEAK]) // object
5029/// _Block_object_assign(&_dest->object, _src->object,
5030/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5031/// [|BLOCK_FIELD_IS_WEAK]) // block
5032/// }
5033/// And:
5034/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5035/// _Block_object_dispose(_src->object,
5036/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5037/// [|BLOCK_FIELD_IS_WEAK]) // object
5038/// _Block_object_dispose(_src->object,
5039/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5040/// [|BLOCK_FIELD_IS_WEAK]) // block
5041/// }
5042
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005043std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5044 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005045 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005046 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005047 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005048 CopyDestroyCache.insert(flag);
5049 S = "static void __Block_byref_id_object_copy_";
5050 S += utostr(flag);
5051 S += "(void *dst, void *src) {\n";
5052
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005053 // offset into the object pointer is computed as:
5054 // void * + void* + int + int + void* + void *
5055 unsigned IntSize =
5056 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5057 unsigned VoidPtrSize =
5058 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5059
5060 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
5061 S += " _Block_object_assign((char*)dst + ";
5062 S += utostr(offset);
5063 S += ", *(void * *) ((char*)src + ";
5064 S += utostr(offset);
5065 S += "), ";
5066 S += utostr(flag);
5067 S += ");\n}\n";
5068
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005069 S += "static void __Block_byref_id_object_dispose_";
5070 S += utostr(flag);
5071 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005072 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5073 S += utostr(offset);
5074 S += "), ";
5075 S += utostr(flag);
5076 S += ");\n}\n";
5077 return S;
5078}
5079
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005080/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5081/// the declaration into:
5082/// struct __Block_byref_ND {
5083/// void *__isa; // NULL for everything except __weak pointers
5084/// struct __Block_byref_ND *__forwarding;
5085/// int32_t __flags;
5086/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005087/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5088/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005089/// typex ND;
5090/// };
5091///
5092/// It then replaces declaration of ND variable with:
5093/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5094/// __size=sizeof(struct __Block_byref_ND),
5095/// ND=initializer-if-any};
5096///
5097///
5098void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005099 // Insert declaration for the function in which block literal is
5100 // used.
5101 if (CurFunctionDeclToDeclareForBlock)
5102 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005103 int flag = 0;
5104 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005105 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005106 if (DeclLoc.isInvalid())
5107 // If type location is missing, it is because of missing type (a warning).
5108 // Use variable's location which is good for this case.
5109 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005110 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005111 SourceLocation X = ND->getLocEnd();
5112 X = SM->getInstantiationLoc(X);
5113 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005114 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005115 std::string ByrefType;
5116 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005117 ByrefType += " {\n";
5118 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005119 RewriteByRefString(ByrefType, Name, ND);
5120 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005121 ByrefType += " int __flags;\n";
5122 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005123 // Add void *__Block_byref_id_object_copy;
5124 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005125 QualType Ty = ND->getType();
5126 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5127 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005128 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5129 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005130 }
5131
5132 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005133 ByrefType += " " + Name + ";\n";
5134 ByrefType += "};\n";
5135 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005136 SourceLocation FunLocStart;
5137 if (CurFunctionDef)
5138 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5139 else {
5140 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5141 FunLocStart = CurMethodDef->getLocStart();
5142 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005143 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005144 if (Ty.isObjCGCWeak()) {
5145 flag |= BLOCK_FIELD_IS_WEAK;
5146 isa = 1;
5147 }
5148
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005149 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005150 flag = BLOCK_BYREF_CALLER;
5151 QualType Ty = ND->getType();
5152 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5153 if (Ty->isBlockPointerType())
5154 flag |= BLOCK_FIELD_IS_BLOCK;
5155 else
5156 flag |= BLOCK_FIELD_IS_OBJECT;
5157 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005158 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005159 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005160 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005161
5162 // struct __Block_byref_ND ND =
5163 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5164 // initializer-if-any};
5165 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005166 unsigned flags = 0;
5167 if (HasCopyAndDispose)
5168 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005169 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005170 ByrefType.clear();
5171 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005172 std::string ForwardingCastType("(");
5173 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005174 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005175 ByrefType += " " + Name + " = {(void*)";
5176 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005177 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005178 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005179 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005180 ByrefType += "sizeof(";
5181 RewriteByRefString(ByrefType, Name, ND);
5182 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005183 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005184 ByrefType += ", __Block_byref_id_object_copy_";
5185 ByrefType += utostr(flag);
5186 ByrefType += ", __Block_byref_id_object_dispose_";
5187 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005188 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005189 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00005190 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005191 }
5192 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005193 SourceLocation startLoc;
5194 Expr *E = ND->getInit();
5195 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5196 startLoc = ECE->getLParenLoc();
5197 else
5198 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00005199 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005200 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005201 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005202 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005203 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005204 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005205 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005206 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005207 ByrefType += "sizeof(";
5208 RewriteByRefString(ByrefType, Name, ND);
5209 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005210 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005211 ByrefType += "__Block_byref_id_object_copy_";
5212 ByrefType += utostr(flag);
5213 ByrefType += ", __Block_byref_id_object_dispose_";
5214 ByrefType += utostr(flag);
5215 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005216 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005217 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005218
5219 // Complete the newly synthesized compound expression by inserting a right
5220 // curly brace before the end of the declaration.
5221 // FIXME: This approach avoids rewriting the initializer expression. It
5222 // also assumes there is only one declarator. For example, the following
5223 // isn't currently supported by this routine (in general):
5224 //
5225 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5226 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005227 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5228 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005229 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5230 SourceLocation semiLoc =
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005231 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005232
Benjamin Kramerd999b372010-02-14 14:14:16 +00005233 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005234 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005235 return;
5236}
5237
Mike Stump1eb44332009-09-09 15:08:12 +00005238void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005239 // Add initializers for any closure decl refs.
5240 GetBlockDeclRefExprs(Exp->getBody());
5241 if (BlockDeclRefs.size()) {
5242 // Unique all "by copy" declarations.
5243 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005244 if (!BlockDeclRefs[i]->isByRef()) {
5245 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5246 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5247 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5248 }
5249 }
Steve Naroff54055232008-10-27 17:20:55 +00005250 // Unique all "by ref" declarations.
5251 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5252 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005253 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5254 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5255 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5256 }
Steve Naroff54055232008-10-27 17:20:55 +00005257 }
5258 // Find any imported blocks...they will need special attention.
5259 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005260 if (BlockDeclRefs[i]->isByRef() ||
5261 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005262 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005263 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005264 }
5265}
5266
Daniel Dunbar4087f272010-08-17 22:39:59 +00005267FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005268 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005269 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00005270 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCalld931b082010-08-26 03:08:43 +00005271 ID, FType, 0, SC_Extern,
5272 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005273}
5274
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005275Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5276 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005277 Blocks.push_back(Exp);
5278
5279 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005280
5281 // Add inner imported variables now used in current block.
5282 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005283 if (!InnerBlockDeclRefs.empty()) {
5284 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5285 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5286 ValueDecl *VD = Exp->getDecl();
5287 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005288 // We need to save the copied-in variables in nested
5289 // blocks because it is needed at the end for some of the API generations.
5290 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005291 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5292 BlockDeclRefs.push_back(Exp);
5293 BlockByCopyDeclsPtrSet.insert(VD);
5294 BlockByCopyDecls.push_back(VD);
5295 }
5296 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5297 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5298 BlockDeclRefs.push_back(Exp);
5299 BlockByRefDeclsPtrSet.insert(VD);
5300 BlockByRefDecls.push_back(VD);
5301 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005302 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005303 // Find any imported blocks...they will need special attention.
5304 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5305 if (InnerBlockDeclRefs[i]->isByRef() ||
5306 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5307 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5308 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005309 }
5310 InnerDeclRefsCount.push_back(countOfInnerDecls);
5311
Steve Narofffa15fd92008-10-28 20:29:00 +00005312 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005313
Steve Narofffa15fd92008-10-28 20:29:00 +00005314 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005315 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005316 else if (CurMethodDef)
5317 BuildUniqueMethodName(FuncName, CurMethodDef);
5318 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005319 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005320
Steve Narofffa15fd92008-10-28 20:29:00 +00005321 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005322
Steve Narofffa15fd92008-10-28 20:29:00 +00005323 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5324 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005325
Steve Narofffa15fd92008-10-28 20:29:00 +00005326 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005327 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5328 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005329
5330 FunctionDecl *FD;
5331 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005332
Steve Narofffa15fd92008-10-28 20:29:00 +00005333 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005334 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005335 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5336 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005337
Steve Narofffa15fd92008-10-28 20:29:00 +00005338 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005339
Steve Narofffdc03722008-10-29 21:23:59 +00005340 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005341 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005342 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005343 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005344 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005345 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005346 InitExprs.push_back(castExpr);
5347
Steve Naroff01aec112009-12-06 21:14:13 +00005348 // Initialize the block descriptor.
5349 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005350
Steve Naroff01aec112009-12-06 21:14:13 +00005351 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5352 &Context->Idents.get(DescData.c_str()),
5353 Context->VoidPtrTy, 0,
John McCalld931b082010-08-26 03:08:43 +00005354 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005355 UnaryOperator *DescRefExpr =
5356 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5357 Context->VoidPtrTy,
5358 VK_LValue,
5359 SourceLocation()),
5360 UO_AddrOf,
5361 Context->getPointerType(Context->VoidPtrTy),
5362 VK_RValue, OK_Ordinary,
5363 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005364 InitExprs.push_back(DescRefExpr);
5365
Steve Narofffa15fd92008-10-28 20:29:00 +00005366 // Add initializers for any closure decl refs.
5367 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005368 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005369 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005370 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005371 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005372 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005373 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005374 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005375 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5376 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005377 if (HasLocalVariableExternalStorage(*I)) {
5378 QualType QT = (*I)->getType();
5379 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005380 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5381 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005382 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005383 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005384 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005385 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5386 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005387 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005388 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005389 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005390 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005391 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5392 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005393 if (HasLocalVariableExternalStorage(*I)) {
5394 QualType QT = (*I)->getType();
5395 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005396 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5397 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005398 }
5399
Steve Narofffa15fd92008-10-28 20:29:00 +00005400 }
Mike Stump1eb44332009-09-09 15:08:12 +00005401 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005402 }
5403 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005404 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005405 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005406 ValueDecl *ND = (*I);
5407 std::string Name(ND->getNameAsString());
5408 std::string RecName;
5409 RewriteByRefString(RecName, Name, ND);
5410 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5411 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005412 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005413 SourceLocation(), II);
5414 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5415 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5416
Daniel Dunbar4087f272010-08-17 22:39:59 +00005417 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005418 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5419 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005420 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005421 Context->getPointerType(Exp->getType()),
5422 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005423 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005424 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005425 }
5426 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005427 if (ImportedBlockDecls.size()) {
5428 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5429 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005430 unsigned IntSize =
5431 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005432 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5433 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005434 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005435 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005436 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005437 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005438 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005439 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005440 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005441 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005442 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005443 BlockDeclRefs.clear();
5444 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005445 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005446 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005447 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005448 ImportedBlockDecls.clear();
5449 return NewRep;
5450}
5451
5452//===----------------------------------------------------------------------===//
5453// Function Body / Expression rewriting
5454//===----------------------------------------------------------------------===//
5455
Steve Naroffc77a6362008-12-04 16:24:46 +00005456// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5457// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5458// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5459// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5460// Since the rewriter isn't capable of rewriting rewritten code, it's important
5461// we get this right.
5462void RewriteObjC::CollectPropertySetters(Stmt *S) {
5463 // Perform a bottom up traversal of all children.
5464 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5465 CI != E; ++CI)
5466 if (*CI)
5467 CollectPropertySetters(*CI);
5468
5469 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5470 if (BinOp->isAssignmentOp()) {
John McCall12f78a62010-12-02 01:19:52 +00005471 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5472 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005473 }
5474 }
5475}
5476
Steve Narofffa15fd92008-10-28 20:29:00 +00005477Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005478 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005479 isa<DoStmt>(S) || isa<ForStmt>(S))
5480 Stmts.push_back(S);
5481 else if (isa<ObjCForCollectionStmt>(S)) {
5482 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005483 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005484 }
Mike Stump1eb44332009-09-09 15:08:12 +00005485
Steve Narofffa15fd92008-10-28 20:29:00 +00005486 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005487
Steve Narofffa15fd92008-10-28 20:29:00 +00005488 // Perform a bottom up rewrite of all children.
5489 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5490 CI != E; ++CI)
5491 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005492 Stmt *newStmt;
5493 Stmt *S = (*CI);
5494 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5495 Expr *OldBase = IvarRefExpr->getBase();
5496 bool replaced = false;
5497 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5498 if (replaced) {
5499 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5500 ReplaceStmt(OldBase, IRE->getBase());
5501 else
5502 ReplaceStmt(S, newStmt);
5503 }
5504 }
5505 else
5506 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005507 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005508 *CI = newStmt;
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005509 // If dealing with an assignment with LHS being a property reference
5510 // expression, the entire assignment tree is rewritten into a property
5511 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5512 // RHS again.
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005513 if (Expr *Exp = dyn_cast<Expr>(S))
John McCall12f78a62010-12-02 01:19:52 +00005514 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005515 if (PropSetters[Exp]) {
5516 ++CI;
5517 continue;
5518 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005519 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005520 }
Mike Stump1eb44332009-09-09 15:08:12 +00005521
Steve Narofffa15fd92008-10-28 20:29:00 +00005522 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005523 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005524 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5525 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005526 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005527 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005528 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005529 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005530 Stmt *SaveCurrentBody = CurrentBody;
5531 CurrentBody = BE->getBody();
5532 PropParentMap = 0;
Steve Narofffa15fd92008-10-28 20:29:00 +00005533 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005534 CurrentBody = SaveCurrentBody;
5535 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005536 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005537 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005538 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005539 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005540
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005541 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5542
Steve Narofffa15fd92008-10-28 20:29:00 +00005543 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005544 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005545 return blockTranscribed;
5546 }
5547 // Handle specific things.
5548 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5549 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005550
John McCall12f78a62010-12-02 01:19:52 +00005551 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005552 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5553 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5554
5555 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005556 if (BinOp) {
5557 // Because the rewriter doesn't allow us to rewrite rewritten code,
5558 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005559 DisableReplaceStmt = true;
5560 // Save the source range. Even if we disable the replacement, the
5561 // rewritten node will have been inserted into the tree. If the synthesized
5562 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005563 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005564 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5565 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005566 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005567 // Need to rewrite the ivar access expression if need be.
5568 if (isa<ObjCIvarRefExpr>(newStmt)) {
5569 bool replaced = false;
5570 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5571 }
5572
Steve Naroffb619d952008-12-09 12:56:34 +00005573 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005574 //
5575 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5576 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5577 // to see the original expression). Consider this example:
5578 //
5579 // Foo *obj1, *obj2;
5580 //
5581 // obj1.i = [obj2 rrrr];
5582 //
5583 // 'BinOp' for the previous expression looks like:
5584 //
5585 // (BinaryOperator 0x231ccf0 'int' '='
5586 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5587 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5588 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5589 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5590 //
5591 // 'newStmt' represents the rewritten message expression. For example:
5592 //
5593 // (CallExpr 0x231d300 'id':'struct objc_object *'
5594 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5595 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5596 // (CStyleCastExpr 0x231d220 'void *'
5597 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5598 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005599 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005600 // can be used as the setter argument. ReplaceStmt() will still 'see'
5601 // the original RHS (since we haven't altered BinOp).
5602 //
Mike Stump1eb44332009-09-09 15:08:12 +00005603 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005604 // node. As a result, we now leak the original AST nodes.
5605 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005606 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005607 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005608 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005609 }
5610 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005611
Steve Narofffa15fd92008-10-28 20:29:00 +00005612 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5613 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005614
Steve Narofffa15fd92008-10-28 20:29:00 +00005615 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5616 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005617
Steve Narofffa15fd92008-10-28 20:29:00 +00005618 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005619#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005620 // Before we rewrite it, put the original message expression in a comment.
5621 SourceLocation startLoc = MessExpr->getLocStart();
5622 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005623
Steve Narofffa15fd92008-10-28 20:29:00 +00005624 const char *startBuf = SM->getCharacterData(startLoc);
5625 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005626
Steve Narofffa15fd92008-10-28 20:29:00 +00005627 std::string messString;
5628 messString += "// ";
5629 messString.append(startBuf, endBuf-startBuf+1);
5630 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005631
5632 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005633 // InsertText(clang::SourceLocation, char const*, unsigned int).
5634 // InsertText(startLoc, messString.c_str(), messString.size());
5635 // Tried this, but it didn't work either...
5636 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005637#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005638 return RewriteMessageExpr(MessExpr);
5639 }
Mike Stump1eb44332009-09-09 15:08:12 +00005640
Steve Narofffa15fd92008-10-28 20:29:00 +00005641 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5642 return RewriteObjCTryStmt(StmtTry);
5643
5644 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5645 return RewriteObjCSynchronizedStmt(StmtTry);
5646
5647 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5648 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005649
Steve Narofffa15fd92008-10-28 20:29:00 +00005650 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5651 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005652
5653 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005654 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005655 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005656 OrigStmtRange.getEnd());
5657 if (BreakStmt *StmtBreakStmt =
5658 dyn_cast<BreakStmt>(S))
5659 return RewriteBreakStmt(StmtBreakStmt);
5660 if (ContinueStmt *StmtContinueStmt =
5661 dyn_cast<ContinueStmt>(S))
5662 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005663
5664 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005665 // and cast exprs.
5666 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5667 // FIXME: What we're doing here is modifying the type-specifier that
5668 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005669 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005670 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5671 // the context of an ObjCForCollectionStmt. For example:
5672 // NSArray *someArray;
5673 // for (id <FooProtocol> index in someArray) ;
5674 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5675 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005676 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005677 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005678
Steve Narofffa15fd92008-10-28 20:29:00 +00005679 // Blocks rewrite rules.
5680 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5681 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005682 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005683 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005684 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005685 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005686 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005687 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005688 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005689 if (VD->hasAttr<BlocksAttr>()) {
5690 static unsigned uniqueByrefDeclCount = 0;
5691 assert(!BlockByRefDeclNo.count(ND) &&
5692 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5693 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005694 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005695 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005696 else
5697 RewriteTypeOfDecl(VD);
5698 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005699 }
5700 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005701 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005702 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005703 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005704 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5705 }
5706 }
5707 }
Mike Stump1eb44332009-09-09 15:08:12 +00005708
Steve Narofffa15fd92008-10-28 20:29:00 +00005709 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5710 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005711
5712 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005713 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5714 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005715 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5716 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005717 && "Statement stack mismatch");
5718 Stmts.pop_back();
5719 }
5720 // Handle blocks rewriting.
5721 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5722 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005723 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005724 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005725 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5726 ValueDecl *VD = DRE->getDecl();
5727 if (VD->hasAttr<BlocksAttr>())
5728 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005729 if (HasLocalVariableExternalStorage(VD))
5730 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005731 }
5732
Steve Narofffa15fd92008-10-28 20:29:00 +00005733 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005734 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005735 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005736 ReplaceStmt(S, BlockCall);
5737 return BlockCall;
5738 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005739 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005740 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005741 RewriteCastExpr(CE);
5742 }
5743#if 0
5744 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005745 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5746 ICE->getSubExpr(),
5747 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005748 // Get the new text.
5749 std::string SStr;
5750 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005751 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005752 const std::string &Str = Buf.str();
5753
5754 printf("CAST = %s\n", &Str[0]);
5755 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5756 delete S;
5757 return Replacement;
5758 }
5759#endif
5760 // Return this stmt unmodified.
5761 return S;
5762}
5763
Steve Naroff3d7e7862009-12-05 15:55:59 +00005764void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5765 for (RecordDecl::field_iterator i = RD->field_begin(),
5766 e = RD->field_end(); i != e; ++i) {
5767 FieldDecl *FD = *i;
5768 if (isTopLevelBlockPointerType(FD->getType()))
5769 RewriteBlockPointerDecl(FD);
5770 if (FD->getType()->isObjCQualifiedIdType() ||
5771 FD->getType()->isObjCQualifiedInterfaceType())
5772 RewriteObjCQualifiedInterfaceTypes(FD);
5773 }
5774}
5775
Steve Narofffa15fd92008-10-28 20:29:00 +00005776/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5777/// main file of the input.
5778void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5779 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005780 if (FD->isOverloadedOperator())
5781 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005782
Steve Narofffa15fd92008-10-28 20:29:00 +00005783 // Since function prototypes don't have ParmDecl's, we check the function
5784 // prototype. This enables us to rewrite function declarations and
5785 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005786 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005787
Sebastian Redld3a413d2009-04-26 20:35:05 +00005788 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005789 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005790 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005791 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005792 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005793 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005794 Body =
5795 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5796 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005797 CurrentBody = 0;
5798 if (PropParentMap) {
5799 delete PropParentMap;
5800 PropParentMap = 0;
5801 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005802 // This synthesizes and inserts the block "impl" struct, invoke function,
5803 // and any copy/dispose helper functions.
5804 InsertBlockLiteralsWithinFunction(FD);
5805 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005806 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005807 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005808 return;
5809 }
5810 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005811 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005812 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005813 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005814 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005815 Body =
5816 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5817 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005818 CurrentBody = 0;
5819 if (PropParentMap) {
5820 delete PropParentMap;
5821 PropParentMap = 0;
5822 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005823 InsertBlockLiteralsWithinMethod(MD);
5824 CurMethodDef = 0;
5825 }
5826 }
5827 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5828 ClassImplementation.push_back(CI);
5829 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5830 CategoryImplementation.push_back(CI);
5831 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5832 RewriteForwardClassDecl(CD);
5833 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5834 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005835 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005836 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005837 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005838 CheckFunctionPointerDecl(VD->getType(), VD);
5839 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005840 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005841 RewriteCastExpr(CE);
5842 }
5843 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005844 } else if (VD->getType()->isRecordType()) {
5845 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5846 if (RD->isDefinition())
5847 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005848 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005849 if (VD->getInit()) {
5850 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005851 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005852 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005853 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005854 CurrentBody = 0;
5855 if (PropParentMap) {
5856 delete PropParentMap;
5857 PropParentMap = 0;
5858 }
Mike Stump1eb44332009-09-09 15:08:12 +00005859 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005860 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005861 GlobalVarDecl = 0;
5862
5863 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005864 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005865 RewriteCastExpr(CE);
5866 }
5867 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005868 return;
5869 }
5870 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005871 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005872 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005873 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005874 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5875 return;
5876 }
5877 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005878 if (RD->isDefinition())
5879 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005880 return;
5881 }
5882 // Nothing yet.
5883}
5884
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005885void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005886 if (Diags.hasErrorOccurred())
5887 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005888
Steve Narofffa15fd92008-10-28 20:29:00 +00005889 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005890
Steve Naroff621edce2009-04-29 16:37:50 +00005891 // Here's a great place to add any extra declarations that may be needed.
5892 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005893 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005894 E = ProtocolExprDecls.end(); I != E; ++I)
5895 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5896
Benjamin Kramerd999b372010-02-14 14:14:16 +00005897 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005898 if (ClassImplementation.size() || CategoryImplementation.size())
5899 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005900
Steve Narofffa15fd92008-10-28 20:29:00 +00005901 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5902 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005903 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005904 Rewrite.getRewriteBufferFor(MainFileID)) {
5905 //printf("Changed:\n");
5906 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5907 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005908 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005909 }
Steve Narofface66252008-11-13 20:07:04 +00005910
Steve Naroff621edce2009-04-29 16:37:50 +00005911 if (ClassImplementation.size() || CategoryImplementation.size() ||
5912 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005913 // Rewrite Objective-c meta data*
5914 std::string ResultStr;
5915 SynthesizeMetaDataIntoBuffer(ResultStr);
5916 // Emit metadata.
5917 *OutFile << ResultStr;
5918 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005919 OutFile->flush();
5920}