blob: d689f22f68d7a4e13b3be19a49c819d6b2126352 [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 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000453 };
John McCall9d125032010-01-15 18:39:57 +0000454
455 // Helper function: create a CStyleCastExpr with trivial type source info.
456 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000457 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000458 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +0000459 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallf871d0c2010-08-07 06:22:56 +0000460 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000461 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000462}
463
Mike Stump1eb44332009-09-09 15:08:12 +0000464void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
465 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000466 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000467 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000468 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000469 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000470 // All the args are checked/rewritten. Don't call twice!
471 RewriteBlockPointerDecl(D);
472 break;
473 }
474 }
475}
476
477void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000478 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000479 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000480 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000481}
482
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000483static bool IsHeaderFile(const std::string &Filename) {
484 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000486 if (DotPos == std::string::npos) {
487 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000488 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000489 }
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000491 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
492 // C header: .h
493 // C++ header: .hh or .H;
494 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000495}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000496
Eli Friedman66d6f042009-05-18 22:20:00 +0000497RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000498 Diagnostic &D, const LangOptions &LOpts,
499 bool silenceMacroWarn)
500 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
501 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000502 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000503 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000504 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000505 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000506 "rewriter doesn't support user-specified control flow semantics "
507 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000508}
509
Eli Friedmanbce831b2009-05-18 22:29:17 +0000510ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
511 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000512 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000513 const LangOptions &LOpts,
514 bool SilenceRewriteMacroWarning) {
515 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000516}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000517
Steve Naroffb29b4272008-04-14 22:03:09 +0000518void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000519 Context = &context;
520 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000521 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000522 MsgSendFunctionDecl = 0;
523 MsgSendSuperFunctionDecl = 0;
524 MsgSendStretFunctionDecl = 0;
525 MsgSendSuperStretFunctionDecl = 0;
526 MsgSendFpretFunctionDecl = 0;
527 GetClassFunctionDecl = 0;
528 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000529 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000530 SelGetUidFunctionDecl = 0;
531 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000532 ConstantStringClassReference = 0;
533 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000534 CurMethodDef = 0;
535 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000536 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000537 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000538 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000539 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000540 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000541 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000542 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000543 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000544 PropParentMap = 0;
545 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000546 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000547 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000549 // Get the ID and start/end of the main file.
550 MainFileID = SM->getMainFileID();
551 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
552 MainFileStart = MainBuf->getBufferStart();
553 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Chris Lattner2c78b872009-04-14 23:22:57 +0000555 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000557 // declaring objc_selector outside the parameter list removes a silly
558 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000559 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000560 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000561 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000562 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000563 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000564 if (LangOpts.Microsoft) {
565 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000566 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
567 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000568 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000569 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000570 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000571 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
572 Preamble += "typedef struct objc_object Protocol;\n";
573 Preamble += "#define _REWRITER_typedef_Protocol\n";
574 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000575 if (LangOpts.Microsoft) {
576 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
577 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
578 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000579 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000580 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000581 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000582 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000583 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000584 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000585 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000586 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000587 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000588 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000589 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000590 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000591 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000592 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
593 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000594 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000595 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000596 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
597 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
598 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
599 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
600 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000601 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000602 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000603 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
604 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
605 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000606 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
607 Preamble += "struct __objcFastEnumerationState {\n\t";
608 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000609 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000610 Preamble += "unsigned long *mutationsPtr;\n\t";
611 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000612 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000613 Preamble += "#define __FASTENUMERATIONSTATE\n";
614 Preamble += "#endif\n";
615 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
616 Preamble += "struct __NSConstantStringImpl {\n";
617 Preamble += " int *isa;\n";
618 Preamble += " int flags;\n";
619 Preamble += " char *str;\n";
620 Preamble += " long length;\n";
621 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000622 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
623 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
624 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000625 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000626 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000627 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
628 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000629 // Blocks preamble.
630 Preamble += "#ifndef BLOCK_IMPL\n";
631 Preamble += "#define BLOCK_IMPL\n";
632 Preamble += "struct __block_impl {\n";
633 Preamble += " void *isa;\n";
634 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000635 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000636 Preamble += " void *FuncPtr;\n";
637 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000638 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000639 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000640 Preamble += "extern \"C\" __declspec(dllexport) "
641 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000642 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
643 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
644 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
645 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000646 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
647 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000648 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
649 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
650 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000651 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000652 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000653 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
654 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000655 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000656 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000657 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000658 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000659 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000660 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000661 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000662 Preamble += "#define __weak\n";
663 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000664 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
665 // as this avoids warning in any 64bit/32bit compilation model.
666 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000667}
668
669
Chris Lattnerf04da132007-10-24 17:06:59 +0000670//===----------------------------------------------------------------------===//
671// Top Level Driver Code
672//===----------------------------------------------------------------------===//
673
Chris Lattner682bf922009-03-29 16:50:03 +0000674void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000675 if (Diags.hasErrorOccurred())
676 return;
677
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000678 // Two cases: either the decl could be in the main file, or it could be in a
679 // #included file. If the former, rewrite it now. If the later, check to see
680 // if we rewrote the #include/#import.
681 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000682 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000684 // If this is for a builtin, ignore it.
685 if (Loc.isInvalid()) return;
686
Steve Naroffebf2b562007-10-23 23:50:29 +0000687 // Look for built-in declarations that we need to refer during the rewrite.
688 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000689 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000690 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000691 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000692 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000693 ConstantStringClassReference = FVD;
694 return;
695 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000696 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000697 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000698 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000699 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000700 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000701 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000702 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000703 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000704 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000705 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
706 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000707 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
708 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000709 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000710 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000711 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000712 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000713 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000714 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000715}
716
Chris Lattnerf04da132007-10-24 17:06:59 +0000717//===----------------------------------------------------------------------===//
718// Syntactic (non-AST) Rewriting Code
719//===----------------------------------------------------------------------===//
720
Steve Naroffb29b4272008-04-14 22:03:09 +0000721void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000722 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000723 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
724 const char *MainBufStart = MainBuf.begin();
725 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000726 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000728 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000729 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
730 if (*BufPtr == '#') {
731 if (++BufPtr == MainBufEnd)
732 return;
733 while (*BufPtr == ' ' || *BufPtr == '\t')
734 if (++BufPtr == MainBufEnd)
735 return;
736 if (!strncmp(BufPtr, "import", ImportLen)) {
737 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000738 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000739 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000740 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000741 BufPtr += ImportLen;
742 }
743 }
744 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000745}
746
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000747static std::string getIvarAccessString(ObjCIvarDecl *OID) {
748 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000749 std::string S;
750 S = "((struct ";
751 S += ClassDecl->getIdentifier()->getName();
752 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000753 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000754 return S;
755}
756
Steve Naroffa0876e82008-12-02 17:36:43 +0000757void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
758 ObjCImplementationDecl *IMD,
759 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000760 static bool objcGetPropertyDefined = false;
761 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000762 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000763 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000764 const char *startBuf = SM->getCharacterData(startLoc);
765 assert((*startBuf == '@') && "bogus @synthesize location");
766 const char *semiBuf = strchr(startBuf, ';');
767 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000768 SourceLocation onePastSemiLoc =
769 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000770
771 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
772 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Steve Naroffeb0646c2008-12-02 15:48:25 +0000774 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000775 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000776 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000778 if (!OID)
779 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000780 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000781 if (!PD->getGetterMethodDecl()->isDefined()) {
782 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
783 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
784 ObjCPropertyDecl::OBJC_PR_copy));
785 std::string Getr;
786 if (GenGetProperty && !objcGetPropertyDefined) {
787 objcGetPropertyDefined = true;
788 // FIXME. Is this attribute correct in all cases?
789 Getr = "\nextern \"C\" __declspec(dllimport) "
790 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000791 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000792 RewriteObjCMethodDecl(OID->getContainingInterface(),
793 PD->getGetterMethodDecl(), Getr);
794 Getr += "{ ";
795 // Synthesize an explicit cast to gain access to the ivar.
796 // See objc-act.c:objc_synthesize_new_getter() for details.
797 if (GenGetProperty) {
798 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
799 Getr += "typedef ";
800 const FunctionType *FPRetType = 0;
801 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
802 FPRetType);
803 Getr += " _TYPE";
804 if (FPRetType) {
805 Getr += ")"; // close the precedence "scope" for "*".
806
807 // Now, emit the argument types (if any).
808 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
809 Getr += "(";
810 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
811 if (i) Getr += ", ";
812 std::string ParamStr = FT->getArgType(i).getAsString(
813 Context->PrintingPolicy);
814 Getr += ParamStr;
815 }
816 if (FT->isVariadic()) {
817 if (FT->getNumArgs()) Getr += ", ";
818 Getr += "...";
819 }
820 Getr += ")";
821 } else
822 Getr += "()";
823 }
824 Getr += ";\n";
825 Getr += "return (_TYPE)";
826 Getr += "objc_getProperty(self, _cmd, ";
827 SynthesizeIvarOffsetComputation(OID, Getr);
828 Getr += ", 1)";
829 }
830 else
831 Getr += "return " + getIvarAccessString(OID);
832 Getr += "; }";
833 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000834 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000835
836 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000837 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Steve Naroffeb0646c2008-12-02 15:48:25 +0000839 // Generate the 'setter' function.
840 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000841 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
842 ObjCPropertyDecl::OBJC_PR_copy);
843 if (GenSetProperty && !objcSetPropertyDefined) {
844 objcSetPropertyDefined = true;
845 // FIXME. Is this attribute correct in all cases?
846 Setr = "\nextern \"C\" __declspec(dllimport) "
847 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
848 }
849
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000850 RewriteObjCMethodDecl(OID->getContainingInterface(),
851 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000852 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000853 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000854 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000855 if (GenSetProperty) {
856 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000857 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000858 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000859 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000860 Setr += ", ";
861 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
862 Setr += "0, ";
863 else
864 Setr += "1, ";
865 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
866 Setr += "1)";
867 else
868 Setr += "0)";
869 }
870 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000871 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000872 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000873 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000874 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000875 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000876}
Chris Lattner8a12c272007-10-11 18:38:32 +0000877
Steve Naroffb29b4272008-04-14 22:03:09 +0000878void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000879 // Get the start location and compute the semi location.
880 SourceLocation startLoc = ClassDecl->getLocation();
881 const char *startBuf = SM->getCharacterData(startLoc);
882 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Chris Lattnerf04da132007-10-24 17:06:59 +0000884 // Translate to typedef's that forward reference structs with the same name
885 // as the class. As a convenience, we include the original declaration
886 // as a comment.
887 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000888 typedefString += "// @class ";
889 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
890 I != E; ++I) {
891 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
892 typedefString += ForwardDecl->getNameAsString();
893 if (I+1 != E)
894 typedefString += ", ";
895 else
896 typedefString += ";\n";
897 }
898
Chris Lattner67956052009-02-20 18:04:31 +0000899 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
900 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000901 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000902 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000903 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000904 typedefString += "\n";
905 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000906 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000907 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000908 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000909 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000910 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000911 }
Mike Stump1eb44332009-09-09 15:08:12 +0000912
Steve Naroff934f2762007-10-24 22:48:43 +0000913 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000914 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000915}
916
Steve Naroffb29b4272008-04-14 22:03:09 +0000917void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000918 // When method is a synthesized one, such as a getter/setter there is
919 // nothing to rewrite.
920 if (Method->isSynthesized())
921 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000922 SourceLocation LocStart = Method->getLocStart();
923 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000924
Chris Lattner30fc9332009-02-04 01:06:56 +0000925 if (SM->getInstantiationLineNumber(LocEnd) >
926 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000927 InsertText(LocStart, "#if 0\n");
928 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000929 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000930 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000931 }
932}
933
Mike Stump1eb44332009-09-09 15:08:12 +0000934void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000935 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Benjamin Kramerd999b372010-02-14 14:14:16 +0000937 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000938 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000939}
940
Steve Naroffb29b4272008-04-14 22:03:09 +0000941void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000942 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Steve Naroff423cb562007-10-30 13:30:57 +0000944 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000945 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000947 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
948 E = CatDecl->prop_end(); I != E; ++I)
949 RewriteProperty(*I);
950
Mike Stump1eb44332009-09-09 15:08:12 +0000951 for (ObjCCategoryDecl::instmeth_iterator
952 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000953 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000954 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000955 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000956 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000957 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000958 RewriteMethodDeclaration(*I);
959
Steve Naroff423cb562007-10-30 13:30:57 +0000960 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000961 ReplaceText(CatDecl->getAtEndRange().getBegin(),
962 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000963}
964
Steve Naroffb29b4272008-04-14 22:03:09 +0000965void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000966 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Steve Naroff752d6ef2007-10-30 16:42:30 +0000968 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000969 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000970
971 for (ObjCProtocolDecl::instmeth_iterator
972 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000973 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000974 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000975 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000976 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000977 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000978 RewriteMethodDeclaration(*I);
979
Fariborz Jahanian07acdf42010-09-24 18:36:58 +0000980 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
981 E = PDecl->prop_end(); I != E; ++I)
982 RewriteProperty(*I);
983
Steve Naroff752d6ef2007-10-30 16:42:30 +0000984 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000985 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000986 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000987
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000988 // Must comment out @optional/@required
989 const char *startBuf = SM->getCharacterData(LocStart);
990 const char *endBuf = SM->getCharacterData(LocEnd);
991 for (const char *p = startBuf; p < endBuf; p++) {
992 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000993 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000994 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000996 }
997 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000998 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000999 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001001 }
1002 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001003}
1004
Steve Naroffb29b4272008-04-14 22:03:09 +00001005void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001006 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001007 if (LocStart.isInvalid())
1008 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001009 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001010 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001011}
1012
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001013void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1014 const FunctionType *&FPRetType) {
1015 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001016 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001017 else if (T->isFunctionPointerType() ||
1018 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001019 // needs special handling, since pointer-to-functions have special
1020 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001021 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001022 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001023 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001024 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001025 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001026 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001027 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001028 ResultStr += FPRetType->getResultType().getAsString(
1029 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001030 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001031 }
1032 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001033 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001034}
1035
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001036void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1037 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001038 std::string &ResultStr) {
1039 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1040 const FunctionType *FPRetType = 0;
1041 ResultStr += "\nstatic ";
1042 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001043 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001045 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001046 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001048 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001049 NameStr += "_I_";
1050 else
1051 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001053 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001054 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001055
1056 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001057 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001058 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001059 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001060 }
Mike Stump1eb44332009-09-09 15:08:12 +00001061 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001062 {
1063 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001064 int len = selString.size();
1065 for (int i = 0; i < len; i++)
1066 if (selString[i] == ':')
1067 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001068 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001069 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001070 // Remember this name for metadata emission
1071 MethodInternalNames[OMD] = NameStr;
1072 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001074 // Rewrite arguments
1075 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001076
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001077 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001078 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001079 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001080 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001081 if (!LangOpts.Microsoft) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001082 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001083 ResultStr += "struct ";
1084 }
1085 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001086 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001087 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001088 }
1089 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001090 ResultStr += Context->getObjCClassType().getAsString(
1091 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001093 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001094 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001095 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001097 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001098 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1099 E = OMD->param_end(); PI != E; ++PI) {
1100 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001101 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001102 if (PDecl->getType()->isObjCQualifiedIdType()) {
1103 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001104 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001105 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001106 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001107 QualType QT = PDecl->getType();
1108 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1109 if (convertBlockPointerToFunctionPointer(QT))
1110 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1111 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001112 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001113 ResultStr += Name;
1114 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001115 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001116 if (OMD->isVariadic())
1117 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001118 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Steve Naroff76e429d2008-07-16 14:40:40 +00001120 if (FPRetType) {
1121 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Steve Naroff76e429d2008-07-16 14:40:40 +00001123 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001124 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001125 ResultStr += "(";
1126 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1127 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001128 std::string ParamStr = FT->getArgType(i).getAsString(
1129 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001130 ResultStr += ParamStr;
1131 }
1132 if (FT->isVariadic()) {
1133 if (FT->getNumArgs()) ResultStr += ", ";
1134 ResultStr += "...";
1135 }
1136 ResultStr += ")";
1137 } else {
1138 ResultStr += "()";
1139 }
1140 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001141}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001142void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001143 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1144 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001146 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001148 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001149 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1150 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001151 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001152 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001153 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001154 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001155 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001156 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001157
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001158 const char *startBuf = SM->getCharacterData(LocStart);
1159 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001160 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001161 }
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001163 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001164 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1165 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001166 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001167 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001168 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001169 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001170 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001171 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001173 const char *startBuf = SM->getCharacterData(LocStart);
1174 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001175 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001176 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001177 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001178 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001179 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001180 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001181 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001182 }
1183
Benjamin Kramerd999b372010-02-14 14:14:16 +00001184 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001185}
1186
Steve Naroffb29b4272008-04-14 22:03:09 +00001187void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001188 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001189 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001190 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001191 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001192 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001193 ResultStr += "\n";
1194 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001195 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001196 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001197 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001198 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001199 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001200 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001201 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001202 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001203 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001204
1205 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001206 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001207 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001208 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001209 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001210 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001211 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001212 for (ObjCInterfaceDecl::classmeth_iterator
1213 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001214 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001215 RewriteMethodDeclaration(*I);
1216
Steve Naroff2feac5e2007-10-30 03:43:13 +00001217 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001218 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1219 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001220}
1221
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001222Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001223 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001224 ObjCMethodDecl *OMD = 0;
1225 QualType Ty;
1226 Selector Sel;
Duncan Sands54bd4572010-10-20 08:21:16 +00001227 Stmt *Receiver = 0;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001228 bool Super = false;
1229 QualType SuperTy;
1230 SourceLocation SuperLocation;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001231 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001232 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCall12f78a62010-12-02 01:19:52 +00001233 if (ObjCPropertyRefExpr *PropRefExpr =
1234 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
1235 if (PropRefExpr->isExplicitProperty()) {
1236 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1237 OMD = PDecl->getSetterMethodDecl();
1238 Ty = PDecl->getType();
1239 Sel = PDecl->getSetterName();
1240 } else {
1241 OMD = PropRefExpr->getImplicitPropertySetter();
1242 Sel = OMD->getSelector();
1243 Ty = PropRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001244 }
John McCall12f78a62010-12-02 01:19:52 +00001245 Super = PropRefExpr->isSuperReceiver();
1246 if (!Super) {
1247 Receiver = PropRefExpr->getBase();
1248 } else {
1249 SuperTy = PropRefExpr->getSuperReceiverType();
1250 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001251 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001252 }
1253
1254 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Steve Naroffc77a6362008-12-04 16:24:46 +00001255 llvm::SmallVector<Expr *, 1> ExprVec;
1256 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001257
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001258 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001259 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001260 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001261 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001262 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001263 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001264 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001265 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001266 SuperTy,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001267 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001268 &ExprVec[0], 1,
1269 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001270 else {
1271 // FIXME. Refactor this into common code with that in
1272 // RewritePropertyOrImplicitGetter
1273 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1274 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1275 if (PropGetters[Exp])
1276 // This allows us to handle chain/nested property/implicit getters.
1277 Receiver = PropGetters[Exp];
1278
Douglas Gregor04badcf2010-04-21 00:45:42 +00001279 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001280 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001281 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001282 /*FIXME: */SourceLocation(),
1283 cast<Expr>(Receiver),
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001284 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001285 &ExprVec[0], 1,
1286 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001287 }
Steve Naroffc77a6362008-12-04 16:24:46 +00001288 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Steve Naroffc77a6362008-12-04 16:24:46 +00001290 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001291 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001292 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001293 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1294 // to things that stay around.
1295 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001296 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001297}
1298
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001299Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1300 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001301 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001302 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001303 ObjCMethodDecl *OMD = 0;
1304 QualType Ty;
1305 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001306 bool Super = false;
1307 QualType SuperTy;
1308 SourceLocation SuperLocation;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001309 if (ObjCPropertyRefExpr *PropRefExpr =
1310 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
John McCall12f78a62010-12-02 01:19:52 +00001311 if (PropRefExpr->isExplicitProperty()) {
1312 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1313 OMD = PDecl->getGetterMethodDecl();
1314 Ty = PDecl->getType();
1315 Sel = PDecl->getGetterName();
1316 } else {
1317 OMD = PropRefExpr->getImplicitPropertyGetter();
1318 Sel = OMD->getSelector();
1319 Ty = PropRefExpr->getType();
1320 }
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001321 Super = PropRefExpr->isSuperReceiver();
1322 if (!Super)
1323 Receiver = PropRefExpr->getBase();
1324 else {
John McCall12f78a62010-12-02 01:19:52 +00001325 SuperTy = PropRefExpr->getSuperReceiverType();
1326 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001327 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001328 }
1329
1330 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1331
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001332 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001333 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001334 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001335 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001336 Expr::getValueKindForType(Ty),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001337 /*FIXME?*/SourceLocation(),
1338 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001339 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001340 SuperTy,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001341 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001342 0, 0,
1343 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001344 else {
1345 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1346 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1347 if (PropGetters[Exp])
1348 // This allows us to handle chain/nested property/implicit getters.
1349 Receiver = PropGetters[Exp];
Douglas Gregor04badcf2010-04-21 00:45:42 +00001350 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001351 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001352 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001353 /*FIXME:*/SourceLocation(),
1354 cast<Expr>(Receiver),
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001355 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001356 0, 0,
1357 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001358 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001359
Steve Naroff4c3580e2008-12-04 23:50:32 +00001360 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001361
1362 if (!PropParentMap)
1363 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001364 bool NestedPropertyRef = false;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001365 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001366 ImplicitCastExpr*ICE=0;
1367 if (Parent)
1368 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1369 assert((ICE->getCastKind() == CK_GetObjCProperty)
1370 && "RewritePropertyOrImplicitGetter");
1371 Parent = PropParentMap->getParent(Parent);
1372 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1373 }
1374 if (NestedPropertyRef) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001375 // We stash away the ReplacingStmt since actually doing the
1376 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001377 PropGetters[ICE] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001378 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1379 // to things that stay around.
1380 Context->Deallocate(MsgExpr);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001381 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001382 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001383 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001384 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001385 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1386 // to things that stay around.
1387 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001388 return ReplacingStmt;
1389 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001390}
1391
Mike Stump1eb44332009-09-09 15:08:12 +00001392Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001393 SourceLocation OrigStart,
1394 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001395 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001396 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001397 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001398 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001399 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001400 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001401 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001402 // lookup which class implements the instance variable.
1403 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001404 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001405 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001406 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Steve Narofff0757612008-05-08 17:52:16 +00001408 // Synthesize an explicit cast to gain access to the ivar.
1409 std::string RecName = clsDeclared->getIdentifier()->getName();
1410 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001411 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001412 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001413 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001414 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1415 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001416 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001417 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001418 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001419 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001420 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCallf89e55a2010-11-18 06:31:45 +00001421 IV->getBase()->getLocEnd(),
1422 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001423 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001424 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001425 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001426 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001427 IV->getLocation(),
1428 D->getType(),
1429 VK_LValue, OK_Ordinary);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001430 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001431 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001432 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001433 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001434 // Cannot delete IV->getBase(), since PE points to it.
1435 // Replace the old base with the cast. This is important when doing
1436 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001437 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001438 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001439 }
Steve Naroff84472a82008-04-18 21:55:08 +00001440 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001441 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Steve Naroff9f525972008-05-06 23:20:07 +00001443 // Explicit ivar refs need to have a cast inserted.
1444 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001445 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001446 ObjCInterfaceType *iFaceDecl =
1447 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001448 // lookup which class implements the instance variable.
1449 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001450 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001451 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001452 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Steve Naroff9f525972008-05-06 23:20:07 +00001454 // Synthesize an explicit cast to gain access to the ivar.
1455 std::string RecName = clsDeclared->getIdentifier()->getName();
1456 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001457 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001458 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001459 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001460 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1461 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001462 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001463 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001464 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001465 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001466 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001467 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001468 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001469 // Cannot delete IV->getBase(), since PE points to it.
1470 // Replace the old base with the cast. This is important when doing
1471 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001472 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001473 return IV;
1474 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001475 }
Steve Naroff84472a82008-04-18 21:55:08 +00001476 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001477}
1478
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001479Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1480 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1481 CI != E; ++CI) {
1482 if (*CI) {
1483 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1484 if (newStmt)
1485 *CI = newStmt;
1486 }
1487 }
1488 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1489 SourceRange OrigStmtRange = S->getSourceRange();
1490 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1491 replaced);
1492 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001493 }
1494 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1495 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1496 return newStmt;
1497 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001498 return S;
1499}
1500
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001501/// SynthCountByEnumWithState - To print:
1502/// ((unsigned int (*)
1503/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001504/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001505/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001506/// "countByEnumeratingWithState:objects:count:"),
1507/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001508/// (id *)items, (unsigned int)16)
1509///
Steve Naroffb29b4272008-04-14 22:03:09 +00001510void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001511 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1512 "id *, unsigned int))(void *)objc_msgSend)";
1513 buf += "\n\t\t";
1514 buf += "((id)l_collection,\n\t\t";
1515 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1516 buf += "\n\t\t";
1517 buf += "&enumState, "
1518 "(id *)items, (unsigned int)16)";
1519}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001520
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001521/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1522/// statement to exit to its outer synthesized loop.
1523///
Steve Naroffb29b4272008-04-14 22:03:09 +00001524Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001525 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1526 return S;
1527 // replace break with goto __break_label
1528 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001530 SourceLocation startLoc = S->getLocStart();
1531 buf = "goto __break_label_";
1532 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001533 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001534
1535 return 0;
1536}
1537
1538/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1539/// statement to continue with its inner synthesized loop.
1540///
Steve Naroffb29b4272008-04-14 22:03:09 +00001541Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001542 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1543 return S;
1544 // replace continue with goto __continue_label
1545 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001547 SourceLocation startLoc = S->getLocStart();
1548 buf = "goto __continue_label_";
1549 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001550 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001552 return 0;
1553}
1554
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001555/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001556/// It rewrites:
1557/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001559/// Into:
1560/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001561/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001562/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001563/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001564/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001565/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001566/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001567/// if (limit) {
1568/// unsigned long startMutations = *enumState.mutationsPtr;
1569/// do {
1570/// unsigned long counter = 0;
1571/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001572/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001573/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001574/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001575/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001576/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001577/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001578/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001579/// objects:items count:16]);
1580/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001581/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001582/// }
1583/// else
1584/// elem = nil;
1585/// }
1586///
Steve Naroffb29b4272008-04-14 22:03:09 +00001587Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001588 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001589 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001590 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001591 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001592 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001593 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001594
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001595 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001596 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar4087f272010-08-17 22:39:59 +00001597 llvm::StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001598 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001599 std::string buf;
1600 buf = "\n{\n\t";
1601 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1602 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001603 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001604 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001605 if (ElementType->isObjCQualifiedIdType() ||
1606 ElementType->isObjCQualifiedInterfaceType())
1607 // Simply use 'id' for all qualified types.
1608 elementTypeAsString = "id";
1609 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001610 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001611 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001612 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001613 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001614 buf += elementName;
1615 buf += ";\n\t";
1616 }
Chris Lattner06767512008-04-08 05:52:18 +00001617 else {
1618 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001619 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001620 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1621 if (VD->getType()->isObjCQualifiedIdType() ||
1622 VD->getType()->isObjCQualifiedInterfaceType())
1623 // Simply use 'id' for all qualified types.
1624 elementTypeAsString = "id";
1625 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001626 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001627 }
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001629 // struct __objcFastEnumerationState enumState = { 0 };
1630 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1631 // id items[16];
1632 buf += "id items[16];\n\t";
1633 // id l_collection = (id)
1634 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001635 // Find start location of 'collection' the hard way!
1636 const char *startCollectionBuf = startBuf;
1637 startCollectionBuf += 3; // skip 'for'
1638 startCollectionBuf = strchr(startCollectionBuf, '(');
1639 startCollectionBuf++; // skip '('
1640 // find 'in' and skip it.
1641 while (*startCollectionBuf != ' ' ||
1642 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1643 (*(startCollectionBuf+3) != ' ' &&
1644 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1645 startCollectionBuf++;
1646 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001647
1648 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001649 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001650 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001651 SourceLocation rightParenLoc = S->getRParenLoc();
1652 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1653 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001654 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001656 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1657 // objects:items count:16];
1658 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001659 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001660 // ((unsigned int (*)
1661 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001662 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001663 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001664 // "countByEnumeratingWithState:objects:count:"),
1665 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001666 // (id *)items, (unsigned int)16);
1667 buf += "unsigned long limit =\n\t\t";
1668 SynthCountByEnumWithState(buf);
1669 buf += ";\n\t";
1670 /// if (limit) {
1671 /// unsigned long startMutations = *enumState.mutationsPtr;
1672 /// do {
1673 /// unsigned long counter = 0;
1674 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001675 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001676 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001677 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001678 buf += "if (limit) {\n\t";
1679 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1680 buf += "do {\n\t\t";
1681 buf += "unsigned long counter = 0;\n\t\t";
1682 buf += "do {\n\t\t\t";
1683 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1684 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1685 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001686 buf += " = (";
1687 buf += elementTypeAsString;
1688 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001689 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001690 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001691
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001692 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001693 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001694 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001695 /// objects:items count:16]);
1696 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001697 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001698 /// }
1699 /// else
1700 /// elem = nil;
1701 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001702 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001703 buf = ";\n\t";
1704 buf += "__continue_label_";
1705 buf += utostr(ObjCBcLabelNo.back());
1706 buf += ": ;";
1707 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001708 buf += "} while (counter < limit);\n\t";
1709 buf += "} while (limit = ";
1710 SynthCountByEnumWithState(buf);
1711 buf += ");\n\t";
1712 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001713 buf += " = ((";
1714 buf += elementTypeAsString;
1715 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001716 buf += "__break_label_";
1717 buf += utostr(ObjCBcLabelNo.back());
1718 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001719 buf += "}\n\t";
1720 buf += "else\n\t\t";
1721 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001722 buf += " = ((";
1723 buf += elementTypeAsString;
1724 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001725 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001727 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001728 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001729 if (isa<CompoundStmt>(S->getBody())) {
1730 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001731 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001732 } else {
1733 /* Need to treat single statements specially. For example:
1734 *
1735 * for (A *a in b) if (stuff()) break;
1736 * for (A *a in b) xxxyy;
1737 *
1738 * The following code simply scans ahead to the semi to find the actual end.
1739 */
1740 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1741 const char *semiBuf = strchr(stmtBuf, ';');
1742 assert(semiBuf && "Can't find ';'");
1743 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001744 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001745 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001746 Stmts.pop_back();
1747 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001748 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001749}
1750
Mike Stump1eb44332009-09-09 15:08:12 +00001751/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001752/// This routine rewrites @synchronized(expr) stmt;
1753/// into:
1754/// objc_sync_enter(expr);
1755/// @try stmt @finally { objc_sync_exit(expr); }
1756///
Steve Naroffb29b4272008-04-14 22:03:09 +00001757Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001758 // Get the start location and compute the semi location.
1759 SourceLocation startLoc = S->getLocStart();
1760 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001762 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001763
1764 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001765 buf = "objc_sync_enter((id)";
1766 const char *lparenBuf = startBuf;
1767 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001768 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001769 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1770 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001771 // been rewritten! (which implies the SourceLocation's are invalid).
1772 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001773 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001774 while (*endBuf != ')') endBuf--;
1775 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001776 buf = ");\n";
1777 // declare a new scope with two variables, _stack and _rethrow.
1778 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1779 buf += "int buf[18/*32-bit i386*/];\n";
1780 buf += "char *pointers[4];} _stack;\n";
1781 buf += "id volatile _rethrow = 0;\n";
1782 buf += "objc_exception_try_enter(&_stack);\n";
1783 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001784 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001785 startLoc = S->getSynchBody()->getLocEnd();
1786 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Steve Naroffc7089f12008-08-19 13:04:19 +00001788 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001789 SourceLocation lastCurlyLoc = startLoc;
1790 buf = "}\nelse {\n";
1791 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001792 buf += "}\n";
1793 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001794 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001795
1796 std::string syncBuf;
1797 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001798 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00001799 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001800 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001801 std::string syncExprBufS;
1802 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001803 syncExpr->printPretty(syncExprBuf, *Context, 0,
1804 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001805 syncBuf += syncExprBuf.str();
1806 syncBuf += ");";
1807
1808 buf += syncBuf;
1809 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001810 buf += "}\n";
1811 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Benjamin Kramerd999b372010-02-14 14:14:16 +00001813 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001814
1815 bool hasReturns = false;
1816 HasReturnStmts(S->getSynchBody(), hasReturns);
1817 if (hasReturns)
1818 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1819
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001820 return 0;
1821}
1822
Steve Naroffb85e77a2009-12-05 21:43:12 +00001823void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1824{
Steve Naroff8c565152008-12-05 17:03:39 +00001825 // Perform a bottom up traversal of all children.
1826 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1827 CI != E; ++CI)
1828 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001829 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001830
Steve Naroffb85e77a2009-12-05 21:43:12 +00001831 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001832 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001833 TryFinallyContainsReturnDiag);
1834 }
1835 return;
1836}
1837
Steve Naroffb85e77a2009-12-05 21:43:12 +00001838void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1839{
1840 // Perform a bottom up traversal of all children.
1841 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1842 CI != E; ++CI)
1843 if (*CI)
1844 HasReturnStmts(*CI, hasReturns);
1845
1846 if (isa<ReturnStmt>(S))
1847 hasReturns = true;
1848 return;
1849}
1850
1851void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1852 // Perform a bottom up traversal of all children.
1853 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1854 CI != E; ++CI)
1855 if (*CI) {
1856 RewriteTryReturnStmts(*CI);
1857 }
1858 if (isa<ReturnStmt>(S)) {
1859 SourceLocation startLoc = S->getLocStart();
1860 const char *startBuf = SM->getCharacterData(startLoc);
1861
1862 const char *semiBuf = strchr(startBuf, ';');
1863 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1864 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1865
1866 std::string buf;
1867 buf = "{ objc_exception_try_exit(&_stack); return";
1868
Benjamin Kramerd999b372010-02-14 14:14:16 +00001869 ReplaceText(startLoc, 6, buf);
1870 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001871 }
1872 return;
1873}
1874
1875void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1876 // Perform a bottom up traversal of all children.
1877 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1878 CI != E; ++CI)
1879 if (*CI) {
1880 RewriteSyncReturnStmts(*CI, syncExitBuf);
1881 }
1882 if (isa<ReturnStmt>(S)) {
1883 SourceLocation startLoc = S->getLocStart();
1884 const char *startBuf = SM->getCharacterData(startLoc);
1885
1886 const char *semiBuf = strchr(startBuf, ';');
1887 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1888 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1889
1890 std::string buf;
1891 buf = "{ objc_exception_try_exit(&_stack);";
1892 buf += syncExitBuf;
1893 buf += " return";
1894
Benjamin Kramerd999b372010-02-14 14:14:16 +00001895 ReplaceText(startLoc, 6, buf);
1896 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001897 }
1898 return;
1899}
1900
Steve Naroffb29b4272008-04-14 22:03:09 +00001901Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001902 // Get the start location and compute the semi location.
1903 SourceLocation startLoc = S->getLocStart();
1904 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Steve Naroff75730982007-11-07 04:08:17 +00001906 assert((*startBuf == '@') && "bogus @try location");
1907
1908 std::string buf;
1909 // declare a new scope with two variables, _stack and _rethrow.
1910 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1911 buf += "int buf[18/*32-bit i386*/];\n";
1912 buf += "char *pointers[4];} _stack;\n";
1913 buf += "id volatile _rethrow = 0;\n";
1914 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001915 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001916
Benjamin Kramerd999b372010-02-14 14:14:16 +00001917 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Steve Naroff75730982007-11-07 04:08:17 +00001919 startLoc = S->getTryBody()->getLocEnd();
1920 startBuf = SM->getCharacterData(startLoc);
1921
1922 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Steve Naroff75730982007-11-07 04:08:17 +00001924 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001925 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001926 startLoc = startLoc.getFileLocWithOffset(1);
1927 buf = " /* @catch begin */ else {\n";
1928 buf += " id _caught = objc_exception_extract(&_stack);\n";
1929 buf += " objc_exception_try_enter (&_stack);\n";
1930 buf += " if (_setjmp(_stack.buf))\n";
1931 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1932 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Benjamin Kramerd999b372010-02-14 14:14:16 +00001934 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001935 } else { /* no catch list */
1936 buf = "}\nelse {\n";
1937 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1938 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001939 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001940 }
Steve Naroff75730982007-11-07 04:08:17 +00001941 bool sawIdTypedCatch = false;
1942 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001943 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1944 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001945 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001946
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001947 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001948 buf = "if ("; // we are generating code for the first catch clause
1949 else
1950 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001951 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001952 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Steve Naroff75730982007-11-07 04:08:17 +00001954 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Steve Naroff75730982007-11-07 04:08:17 +00001956 const char *lParenLoc = strchr(startBuf, '(');
1957
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001958 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001959 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001960 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001961 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1962 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001963 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001964 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001965 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Steve Naroffe12e6922008-02-01 20:02:07 +00001967 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001968 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001969 } else if (catchDecl) {
1970 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001971 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001972 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001973 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001974 sawIdTypedCatch = true;
John McCall506b57e2010-05-17 21:00:27 +00001975 } else if (const ObjCObjectPointerType *Ptr =
1976 t->getAs<ObjCObjectPointerType>()) {
1977 // Should be a pointer to a class.
1978 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1979 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001980 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001981 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001982 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001983 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001984 }
1985 }
1986 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001987 lastCatchBody = Catch->getCatchBody();
1988 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001989 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1990 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1991 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1992 assert((*rParenBuf == ')') && "bogus @catch paren location");
1993 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Mike Stump1eb44332009-09-09 15:08:12 +00001995 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001996 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001997 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001998 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001999 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002000 }
Steve Naroff75730982007-11-07 04:08:17 +00002001 }
2002 // Complete the catch list...
2003 if (lastCatchBody) {
2004 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002005 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2006 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002007
Steve Naroff378f47a2008-09-11 15:29:03 +00002008 // Insert the last (implicit) else clause *before* the right curly brace.
2009 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2010 buf = "} /* last catch end */\n";
2011 buf += "else {\n";
2012 buf += " _rethrow = _caught;\n";
2013 buf += " objc_exception_try_exit(&_stack);\n";
2014 buf += "} } /* @catch end */\n";
2015 if (!S->getFinallyStmt())
2016 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002017 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Steve Naroff75730982007-11-07 04:08:17 +00002019 // Set lastCurlyLoc
2020 lastCurlyLoc = lastCatchBody->getLocEnd();
2021 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002022 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002023 startLoc = finalStmt->getLocStart();
2024 startBuf = SM->getCharacterData(startLoc);
2025 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Benjamin Kramerd999b372010-02-14 14:14:16 +00002027 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Steve Naroff75730982007-11-07 04:08:17 +00002029 Stmt *body = finalStmt->getFinallyBody();
2030 SourceLocation startLoc = body->getLocStart();
2031 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002032 assert(*SM->getCharacterData(startLoc) == '{' &&
2033 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002034 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002035 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002036
Steve Naroff75730982007-11-07 04:08:17 +00002037 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002038 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00002039 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002040 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Steve Naroff75730982007-11-07 04:08:17 +00002042 // Set lastCurlyLoc
2043 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Steve Naroff8c565152008-12-05 17:03:39 +00002045 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002046 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002047 } else { /* no finally clause - make sure we synthesize an implicit one */
2048 buf = "{ /* implicit finally clause */\n";
2049 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2050 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2051 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002052 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002053
2054 // Now check for any return/continue/go statements within the @try.
2055 // The implicit finally clause won't called if the @try contains any
2056 // jump statements.
2057 bool hasReturns = false;
2058 HasReturnStmts(S->getTryBody(), hasReturns);
2059 if (hasReturns)
2060 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002061 }
2062 // Now emit the final closing curly brace...
2063 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002064 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002065 return 0;
2066}
2067
Mike Stump1eb44332009-09-09 15:08:12 +00002068// This can't be done with ReplaceStmt(S, ThrowExpr), since
2069// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002070// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002071Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002072 // Get the start location and compute the semi location.
2073 SourceLocation startLoc = S->getLocStart();
2074 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Steve Naroff2bd03922007-11-07 15:32:26 +00002076 assert((*startBuf == '@') && "bogus @throw location");
2077
2078 std::string buf;
2079 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002080 if (S->getThrowExpr())
2081 buf = "objc_exception_throw(";
2082 else // add an implicit argument
2083 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002085 // handle "@ throw" correctly.
2086 const char *wBuf = strchr(startBuf, 'w');
2087 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002088 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Steve Naroff2bd03922007-11-07 15:32:26 +00002090 const char *semiBuf = strchr(startBuf, ';');
2091 assert((*semiBuf == ';') && "@throw: can't find ';'");
2092 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002093 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002094 return 0;
2095}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002096
Steve Naroffb29b4272008-04-14 22:03:09 +00002097Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002098 // Create a new string expression.
2099 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002100 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002101 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00002102 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2103 StrEncoding.length(), false,StrType,
2104 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002105 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Chris Lattner07506182007-11-30 22:53:43 +00002107 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002108 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002109 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002110}
2111
Steve Naroffb29b4272008-04-14 22:03:09 +00002112Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002113 if (!SelGetUidFunctionDecl)
2114 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002115 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2116 // Create a call to sel_registerName("selName").
2117 llvm::SmallVector<Expr*, 8> SelExprs;
2118 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002119 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002120 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002121 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002122 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002123 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2124 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002125 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002126 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002127 return SelExp;
2128}
2129
Steve Naroffb29b4272008-04-14 22:03:09 +00002130CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002131 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2132 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002133 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002134 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002135
Steve Naroffebf2b562007-10-23 23:50:29 +00002136 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002137 DeclRefExpr *DRE =
2138 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002139
Steve Naroffebf2b562007-10-23 23:50:29 +00002140 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002141 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002142 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002143 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002144 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002145
John McCall183700f2009-09-21 23:43:11 +00002146 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002148 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002149 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002150 FT->getCallResultType(*Context),
2151 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002152 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002153}
2154
Steve Naroffd5255f52007-11-01 13:24:47 +00002155static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2156 const char *&startRef, const char *&endRef) {
2157 while (startBuf < endBuf) {
2158 if (*startBuf == '<')
2159 startRef = startBuf; // mark the start.
2160 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002161 if (startRef && *startRef == '<') {
2162 endRef = startBuf; // mark the end.
2163 return true;
2164 }
2165 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002166 }
2167 startBuf++;
2168 }
2169 return false;
2170}
2171
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002172static void scanToNextArgument(const char *&argRef) {
2173 int angle = 0;
2174 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2175 if (*argRef == '<')
2176 angle++;
2177 else if (*argRef == '>')
2178 angle--;
2179 argRef++;
2180 }
2181 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2182}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002183
Steve Naroffb29b4272008-04-14 22:03:09 +00002184bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002185 if (T->isObjCQualifiedIdType())
2186 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002187 if (const PointerType *PT = T->getAs<PointerType>()) {
2188 if (PT->getPointeeType()->isObjCQualifiedIdType())
2189 return true;
2190 }
2191 if (T->isObjCObjectPointerType()) {
2192 T = T->getPointeeType();
2193 return T->isObjCQualifiedInterfaceType();
2194 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002195 if (T->isArrayType()) {
2196 QualType ElemTy = Context->getBaseElementType(T);
2197 return needToScanForQualifiers(ElemTy);
2198 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002199 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002200}
2201
Steve Naroff4f95b752008-07-29 18:15:38 +00002202void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2203 QualType Type = E->getType();
2204 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002205 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Steve Naroffcda658e2008-11-19 21:15:47 +00002207 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2208 Loc = ECE->getLParenLoc();
2209 EndLoc = ECE->getRParenLoc();
2210 } else {
2211 Loc = E->getLocStart();
2212 EndLoc = E->getLocEnd();
2213 }
2214 // This will defend against trying to rewrite synthesized expressions.
2215 if (Loc.isInvalid() || EndLoc.isInvalid())
2216 return;
2217
Steve Naroff4f95b752008-07-29 18:15:38 +00002218 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002219 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002220 const char *startRef = 0, *endRef = 0;
2221 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2222 // Get the locations of the startRef, endRef.
2223 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2224 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2225 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002226 InsertText(LessLoc, "/*");
2227 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002228 }
2229 }
2230}
2231
Steve Naroffb29b4272008-04-14 22:03:09 +00002232void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002233 SourceLocation Loc;
2234 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002235 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002236 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2237 Loc = VD->getLocation();
2238 Type = VD->getType();
2239 }
2240 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2241 Loc = FD->getLocation();
2242 // Check for ObjC 'id' and class types that have been adorned with protocol
2243 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002244 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002245 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002246 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002247 if (!proto)
2248 return;
2249 Type = proto->getResultType();
2250 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002251 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2252 Loc = FD->getLocation();
2253 Type = FD->getType();
2254 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002255 else
2256 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002257
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002258 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002259 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002260
Steve Naroffd5255f52007-11-01 13:24:47 +00002261 const char *endBuf = SM->getCharacterData(Loc);
2262 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002263 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002264 startBuf--; // scan backward (from the decl location) for return type.
2265 const char *startRef = 0, *endRef = 0;
2266 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2267 // Get the locations of the startRef, endRef.
2268 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2269 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2270 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002271 InsertText(LessLoc, "/*");
2272 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002273 }
2274 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002275 if (!proto)
2276 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002277 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002278 const char *startBuf = SM->getCharacterData(Loc);
2279 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002280 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2281 if (needToScanForQualifiers(proto->getArgType(i))) {
2282 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002283
Steve Naroffd5255f52007-11-01 13:24:47 +00002284 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002285 // scan forward (from the decl location) for argument types.
2286 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002287 const char *startRef = 0, *endRef = 0;
2288 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2289 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002290 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002291 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002292 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002293 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002294 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002295 InsertText(LessLoc, "/*");
2296 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002297 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002298 startBuf = ++endBuf;
2299 }
2300 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002301 // If the function name is derived from a macro expansion, then the
2302 // argument buffer will not follow the name. Need to speak with Chris.
2303 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002304 startBuf++; // scan forward (from the decl location) for argument types.
2305 startBuf++;
2306 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002307 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002308}
2309
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002310void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2311 QualType QT = ND->getType();
2312 const Type* TypePtr = QT->getAs<Type>();
2313 if (!isa<TypeOfExprType>(TypePtr))
2314 return;
2315 while (isa<TypeOfExprType>(TypePtr)) {
2316 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2317 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2318 TypePtr = QT->getAs<Type>();
2319 }
2320 // FIXME. This will not work for multiple declarators; as in:
2321 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002322 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002323 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2324 const char *startBuf = SM->getCharacterData(DeclLoc);
2325 if (ND->getInit()) {
2326 std::string Name(ND->getNameAsString());
2327 TypeAsString += " " + Name + " = ";
2328 Expr *E = ND->getInit();
2329 SourceLocation startLoc;
2330 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2331 startLoc = ECE->getLParenLoc();
2332 else
2333 startLoc = E->getLocStart();
2334 startLoc = SM->getInstantiationLoc(startLoc);
2335 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002336 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002337 }
2338 else {
2339 SourceLocation X = ND->getLocEnd();
2340 X = SM->getInstantiationLoc(X);
2341 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002342 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002343 }
2344}
2345
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002346// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002347void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002348 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2349 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002350 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002351 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002352 &ArgTys[0], ArgTys.size(),
2353 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002354 false, false, 0, 0,
2355 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002356 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002357 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002358 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002359 SC_Extern,
2360 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002361}
2362
Steve Naroffb29b4272008-04-14 22:03:09 +00002363void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002364 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002365 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002366 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002367 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002368 return;
2369 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002370 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002371}
2372
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002373void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2374 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002375 const char *argPtr = TypeString.c_str();
2376 if (!strchr(argPtr, '^')) {
2377 Str += TypeString;
2378 return;
2379 }
2380 while (*argPtr) {
2381 Str += (*argPtr == '^' ? '*' : *argPtr);
2382 argPtr++;
2383 }
2384}
2385
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002386// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002387void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2388 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002389 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002390 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002391 const char *argPtr = TypeString.c_str();
2392 int paren = 0;
2393 while (*argPtr) {
2394 switch (*argPtr) {
2395 case '(':
2396 Str += *argPtr;
2397 paren++;
2398 break;
2399 case ')':
2400 Str += *argPtr;
2401 paren--;
2402 break;
2403 case '^':
2404 Str += '*';
2405 if (paren == 1)
2406 Str += VD->getNameAsString();
2407 break;
2408 default:
2409 Str += *argPtr;
2410 break;
2411 }
2412 argPtr++;
2413 }
2414}
2415
2416
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002417void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2418 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2419 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2420 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2421 if (!proto)
2422 return;
2423 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002424 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002425 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002426 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002427 FdStr += "(";
2428 unsigned numArgs = proto->getNumArgs();
2429 for (unsigned i = 0; i < numArgs; i++) {
2430 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002431 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002432 if (i+1 < numArgs)
2433 FdStr += ", ";
2434 }
2435 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002436 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002437 CurFunctionDeclToDeclareForBlock = 0;
2438}
2439
Steve Naroffc0a123c2008-03-11 17:37:02 +00002440// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002441void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002442 if (SuperContructorFunctionDecl)
2443 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002444 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002445 llvm::SmallVector<QualType, 16> ArgTys;
2446 QualType argT = Context->getObjCIdType();
2447 assert(!argT.isNull() && "Can't find 'id' type");
2448 ArgTys.push_back(argT);
2449 ArgTys.push_back(argT);
2450 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2451 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002452 false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002453 false, false, 0, 0,
2454 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002455 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002456 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002457 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002458 SC_Extern,
2459 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002460}
2461
Steve Naroff09b266e2007-10-30 23:14:51 +00002462// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002463void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002464 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2465 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002466 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002467 assert(!argT.isNull() && "Can't find 'id' type");
2468 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002469 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002470 assert(!argT.isNull() && "Can't find 'SEL' type");
2471 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002472 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002473 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002474 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002475 false, false, 0, 0,
2476 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002477 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002478 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002479 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002480 SC_Extern,
2481 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002482}
2483
Steve Naroff874e2322007-11-15 10:28:18 +00002484// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002485void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002486 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2487 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002488 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002489 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002490 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002491 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2492 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2493 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002494 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002495 assert(!argT.isNull() && "Can't find 'SEL' type");
2496 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002497 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002498 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002499 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002500 false, false, 0, 0,
2501 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002502 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002503 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002504 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002505 SC_Extern,
2506 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002507}
2508
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002509// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002510void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002511 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2512 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002513 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002514 assert(!argT.isNull() && "Can't find 'id' type");
2515 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002516 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002517 assert(!argT.isNull() && "Can't find 'SEL' type");
2518 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002519 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002520 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002521 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002522 false, false, 0, 0,
2523 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002524 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002525 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002526 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002527 SC_Extern,
2528 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002529}
2530
Mike Stump1eb44332009-09-09 15:08:12 +00002531// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002532// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002533void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002534 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002535 &Context->Idents.get("objc_msgSendSuper_stret");
2536 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002537 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002538 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002539 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002540 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2541 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2542 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002543 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002544 assert(!argT.isNull() && "Can't find 'SEL' type");
2545 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002546 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002547 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002548 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002549 false, false, 0, 0,
2550 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002551 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002552 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002553 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002554 SC_Extern,
2555 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002556}
2557
Steve Naroff1284db82008-05-08 22:02:18 +00002558// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002559void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002560 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2561 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002562 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002563 assert(!argT.isNull() && "Can't find 'id' type");
2564 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002565 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002566 assert(!argT.isNull() && "Can't find 'SEL' type");
2567 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002568 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002569 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002570 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002571 false, false, 0, 0,
2572 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002573 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002574 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002575 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002576 SC_Extern,
2577 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002578}
2579
Steve Naroff09b266e2007-10-30 23:14:51 +00002580// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002581void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002582 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2583 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002584 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002585 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002586 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002587 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002588 false, false, 0, 0,
2589 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002590 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002591 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002592 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002593 SC_Extern,
2594 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002595}
2596
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002597// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2598void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2599 IdentifierInfo *getSuperClassIdent =
2600 &Context->Idents.get("class_getSuperclass");
2601 llvm::SmallVector<QualType, 16> ArgTys;
2602 ArgTys.push_back(Context->getObjCClassType());
2603 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2604 &ArgTys[0], ArgTys.size(),
2605 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002606 false, false, 0, 0,
2607 FunctionType::ExtInfo());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002608 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002609 SourceLocation(),
2610 getSuperClassIdent,
2611 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002612 SC_Extern,
2613 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002614 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002615}
2616
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002617// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002618void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002619 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2620 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002621 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002622 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002623 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002624 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002625 false, false, 0, 0,
2626 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002627 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002628 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002629 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002630 SC_Extern,
2631 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002632}
2633
Steve Naroffb29b4272008-04-14 22:03:09 +00002634Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002635 QualType strType = getConstantStringStructType();
2636
2637 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002638
2639 std::string tmpName = InFileName;
2640 unsigned i;
2641 for (i=0; i < tmpName.length(); i++) {
2642 char c = tmpName.at(i);
2643 // replace any non alphanumeric characters with '_'.
2644 if (!isalpha(c) && (c < '0' || c > '9'))
2645 tmpName[i] = '_';
2646 }
2647 S += tmpName;
2648 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002649 S += utostr(NumObjCStringLiterals++);
2650
Steve Naroffba92b2e2008-03-27 22:29:16 +00002651 Preamble += "static __NSConstantStringImpl " + S;
2652 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2653 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002654 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002655 std::string prettyBufS;
2656 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002657 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2658 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002659 Preamble += prettyBuf.str();
2660 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002661 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002662
2663 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002664 &Context->Idents.get(S), strType, 0,
John McCalld931b082010-08-26 03:08:43 +00002665 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002666 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2667 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002668 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002669 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002670 VK_RValue, OK_Ordinary,
2671 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002672 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002673 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00002674 CK_BitCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002675 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002676 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002677 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002678}
2679
Steve Naroff874e2322007-11-15 10:28:18 +00002680// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002681QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002682 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002683 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002684 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002685 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002686 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002687
Steve Naroff874e2322007-11-15 10:28:18 +00002688 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002689 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002690 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002691 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002692
Steve Naroff874e2322007-11-15 10:28:18 +00002693 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002694 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002695 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2696 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002697 FieldTypes[i], 0,
2698 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002699 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002700 }
Mike Stump1eb44332009-09-09 15:08:12 +00002701
Douglas Gregor838db382010-02-11 01:19:42 +00002702 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002703 }
2704 return Context->getTagDeclType(SuperStructDecl);
2705}
2706
Steve Naroffb29b4272008-04-14 22:03:09 +00002707QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002708 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002709 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002710 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002711 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002712 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002713
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002714 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002715 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002716 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002717 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002718 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002719 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002720 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002721 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002722
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002723 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002724 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002725 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2726 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002727 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002728 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002729 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002730 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002731 }
2732
Douglas Gregor838db382010-02-11 01:19:42 +00002733 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002734 }
2735 return Context->getTagDeclType(ConstantStringDecl);
2736}
2737
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002738Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2739 SourceLocation StartLoc,
2740 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002741 if (!SelGetUidFunctionDecl)
2742 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002743 if (!MsgSendFunctionDecl)
2744 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002745 if (!MsgSendSuperFunctionDecl)
2746 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002747 if (!MsgSendStretFunctionDecl)
2748 SynthMsgSendStretFunctionDecl();
2749 if (!MsgSendSuperStretFunctionDecl)
2750 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002751 if (!MsgSendFpretFunctionDecl)
2752 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002753 if (!GetClassFunctionDecl)
2754 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002755 if (!GetSuperClassFunctionDecl)
2756 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002757 if (!GetMetaClassFunctionDecl)
2758 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002759
Steve Naroff874e2322007-11-15 10:28:18 +00002760 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002761 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2762 // May need to use objc_msgSend_stret() as well.
2763 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002764 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2765 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002766 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002767 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002768 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002769 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002770 }
Mike Stump1eb44332009-09-09 15:08:12 +00002771
Steve Naroff934f2762007-10-24 22:48:43 +00002772 // Synthesize a call to objc_msgSend().
2773 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002774 switch (Exp->getReceiverKind()) {
2775 case ObjCMessageExpr::SuperClass: {
2776 MsgSendFlavor = MsgSendSuperFunctionDecl;
2777 if (MsgSendStretFlavor)
2778 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2779 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002780
Douglas Gregor04badcf2010-04-21 00:45:42 +00002781 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002782
Douglas Gregor04badcf2010-04-21 00:45:42 +00002783 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002784
Douglas Gregor04badcf2010-04-21 00:45:42 +00002785 // set the receiver to self, the first argument to all methods.
2786 InitExprs.push_back(
2787 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002788 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002789 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002790 Context->getObjCIdType(),
2791 VK_RValue,
2792 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002793 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002794
Douglas Gregor04badcf2010-04-21 00:45:42 +00002795 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2796 llvm::SmallVector<Expr*, 8> ClsExprs;
2797 QualType argType = Context->getPointerType(Context->CharTy);
2798 ClsExprs.push_back(StringLiteral::Create(*Context,
2799 ClassDecl->getIdentifier()->getNameStart(),
2800 ClassDecl->getIdentifier()->getLength(),
2801 false, argType, SourceLocation()));
2802 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2803 &ClsExprs[0],
2804 ClsExprs.size(),
2805 StartLoc,
2806 EndLoc);
2807 // (Class)objc_getClass("CurrentClass")
2808 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2809 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002810 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002811 ClsExprs.clear();
2812 ClsExprs.push_back(ArgExpr);
2813 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2814 &ClsExprs[0], ClsExprs.size(),
2815 StartLoc, EndLoc);
2816
2817 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2818 // To turn off a warning, type-cast to 'id'
2819 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2820 NoTypeInfoCStyleCastExpr(Context,
2821 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002822 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002823 // struct objc_super
2824 QualType superType = getSuperStructType();
2825 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002826
Douglas Gregor04badcf2010-04-21 00:45:42 +00002827 if (LangOpts.Microsoft) {
2828 SynthSuperContructorFunctionDecl();
2829 // Simulate a contructor call...
2830 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002831 superType, VK_LValue,
2832 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002833 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2834 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002835 superType, VK_LValue,
2836 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002837 // The code for super is a little tricky to prevent collision with
2838 // the structure definition in the header. The rewriter has it's own
2839 // internal definition (__rw_objc_super) that is uses. This is why
2840 // we need the cast below. For example:
2841 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2842 //
John McCall2de56d12010-08-25 11:45:40 +00002843 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002844 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002845 VK_RValue, OK_Ordinary,
2846 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002847 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2848 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002849 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002850 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002851 // (struct objc_super) { <exprs from above> }
2852 InitListExpr *ILE =
2853 new (Context) InitListExpr(*Context, SourceLocation(),
2854 &InitExprs[0], InitExprs.size(),
2855 SourceLocation());
2856 TypeSourceInfo *superTInfo
2857 = Context->getTrivialTypeSourceInfo(superType);
2858 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002859 superType, VK_LValue,
2860 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002861 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002862 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002863 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002864 VK_RValue, OK_Ordinary,
2865 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002866 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002867 MsgExprs.push_back(SuperRep);
2868 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002869 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002870
2871 case ObjCMessageExpr::Class: {
2872 llvm::SmallVector<Expr*, 8> ClsExprs;
2873 QualType argType = Context->getPointerType(Context->CharTy);
2874 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002875 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002876 IdentifierInfo *clsName = Class->getIdentifier();
2877 ClsExprs.push_back(StringLiteral::Create(*Context,
2878 clsName->getNameStart(),
2879 clsName->getLength(),
2880 false, argType,
2881 SourceLocation()));
2882 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2883 &ClsExprs[0],
2884 ClsExprs.size(),
2885 StartLoc, EndLoc);
2886 MsgExprs.push_back(Cls);
2887 break;
2888 }
2889
2890 case ObjCMessageExpr::SuperInstance:{
2891 MsgSendFlavor = MsgSendSuperFunctionDecl;
2892 if (MsgSendStretFlavor)
2893 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2894 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2895 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2896 llvm::SmallVector<Expr*, 4> InitExprs;
2897
2898 InitExprs.push_back(
2899 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002900 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002901 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002902 Context->getObjCIdType(),
2903 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002904 ); // set the 'receiver'.
2905
2906 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2907 llvm::SmallVector<Expr*, 8> ClsExprs;
2908 QualType argType = Context->getPointerType(Context->CharTy);
2909 ClsExprs.push_back(StringLiteral::Create(*Context,
2910 ClassDecl->getIdentifier()->getNameStart(),
2911 ClassDecl->getIdentifier()->getLength(),
2912 false, argType, SourceLocation()));
2913 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2914 &ClsExprs[0],
2915 ClsExprs.size(),
2916 StartLoc, EndLoc);
2917 // (Class)objc_getClass("CurrentClass")
2918 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2919 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002920 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002921 ClsExprs.clear();
2922 ClsExprs.push_back(ArgExpr);
2923 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2924 &ClsExprs[0], ClsExprs.size(),
2925 StartLoc, EndLoc);
2926
2927 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2928 // To turn off a warning, type-cast to 'id'
2929 InitExprs.push_back(
2930 // set 'super class', using class_getSuperclass().
2931 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002932 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002933 // struct objc_super
2934 QualType superType = getSuperStructType();
2935 Expr *SuperRep;
2936
2937 if (LangOpts.Microsoft) {
2938 SynthSuperContructorFunctionDecl();
2939 // Simulate a contructor call...
2940 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002941 superType, VK_LValue,
2942 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002943 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2944 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002945 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002946 // The code for super is a little tricky to prevent collision with
2947 // the structure definition in the header. The rewriter has it's own
2948 // internal definition (__rw_objc_super) that is uses. This is why
2949 // we need the cast below. For example:
2950 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2951 //
John McCall2de56d12010-08-25 11:45:40 +00002952 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002953 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002954 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002955 SourceLocation());
2956 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2957 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002958 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002959 } else {
2960 // (struct objc_super) { <exprs from above> }
2961 InitListExpr *ILE =
2962 new (Context) InitListExpr(*Context, SourceLocation(),
2963 &InitExprs[0], InitExprs.size(),
2964 SourceLocation());
2965 TypeSourceInfo *superTInfo
2966 = Context->getTrivialTypeSourceInfo(superType);
2967 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002968 superType, VK_RValue, ILE,
2969 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002970 }
2971 MsgExprs.push_back(SuperRep);
2972 break;
2973 }
2974
2975 case ObjCMessageExpr::Instance: {
2976 // Remove all type-casts because it may contain objc-style types; e.g.
2977 // Foo<Proto> *.
2978 Expr *recExpr = Exp->getInstanceReceiver();
2979 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2980 recExpr = CE->getSubExpr();
2981 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002982 CK_BitCast, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002983 MsgExprs.push_back(recExpr);
2984 break;
2985 }
2986 }
2987
Steve Naroffbeaf2992007-11-03 11:27:19 +00002988 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002989 llvm::SmallVector<Expr*, 8> SelExprs;
2990 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002991 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002992 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002993 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002994 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002995 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002996 &SelExprs[0], SelExprs.size(),
2997 StartLoc,
2998 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002999 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003000
Steve Naroff934f2762007-10-24 22:48:43 +00003001 // Now push any user supplied arguments.
3002 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00003003 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00003004 // Make all implicit casts explicit...ICE comes in handy:-)
3005 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3006 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00003007 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003008 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00003009 : ICE->getType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003010 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003011 (void)convertBlockPointerToFunctionPointer(type);
John McCalla5bbc502010-11-15 09:46:46 +00003012 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003013 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003014 }
3015 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003016 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003017 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003018 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003019 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00003020 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00003021 CK_BitCast, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003022 }
Mike Stump1eb44332009-09-09 15:08:12 +00003023 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003024 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003025 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3026 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003027 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003028 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003029 }
Steve Naroffab972d32007-11-04 22:37:50 +00003030 // Generate the funky cast.
3031 CastExpr *cast;
3032 llvm::SmallVector<QualType, 8> ArgTypes;
3033 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003034
Steve Naroffab972d32007-11-04 22:37:50 +00003035 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003036 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3037 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3038 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003039 ArgTypes.push_back(Context->getObjCIdType());
3040 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003041 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003042 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003043 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3044 E = OMD->param_end(); PI != E; ++PI) {
3045 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003046 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003047 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003048 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003049 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003050 ArgTypes.push_back(t);
3051 }
Chris Lattner89951a82009-02-20 18:43:26 +00003052 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3053 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003054 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003055 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003056 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003057 }
3058 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003059 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003060
Steve Naroffab972d32007-11-04 22:37:50 +00003061 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003062 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003063 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003064
Mike Stump1eb44332009-09-09 15:08:12 +00003065 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003066 // If we don't do this cast, we get the following bizarre warning/note:
3067 // xx.m:13: warning: function called through a non-compatible type
3068 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003069 cast = NoTypeInfoCStyleCastExpr(Context,
3070 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003071 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003072
Steve Naroffab972d32007-11-04 22:37:50 +00003073 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003074 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003075 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00003076 // If we don't have a method decl, force a variadic cast.
Douglas Gregorce056bc2010-02-21 22:15:06 +00003077 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003078 false, false, 0, 0,
3079 FunctionType::ExtInfo());
Steve Naroffab972d32007-11-04 22:37:50 +00003080 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003081 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003082 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003083
3084 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003085 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003086
John McCall183700f2009-09-21 23:43:11 +00003087 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003088 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003089 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003090 FT->getResultType(), VK_RValue,
3091 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003092 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003093 if (MsgSendStretFlavor) {
3094 // We have the method which returns a struct/union. Must also generate
3095 // call to objc_msgSend_stret and hang both varieties on a conditional
3096 // expression which dictate which one to envoke depending on size of
3097 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003098
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003099 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003100 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003101 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003102 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003103 cast = NoTypeInfoCStyleCastExpr(Context,
3104 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003105 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003106 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003107 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003108 &ArgTypes[0], ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00003109 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003110 false, false, 0, 0,
3111 FunctionType::ExtInfo());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003112 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003113 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003114 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003115
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003116 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003117 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003118
John McCall183700f2009-09-21 23:43:11 +00003119 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003120 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003121 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003122 FT->getResultType(), VK_RValue,
3123 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003124
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003125 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00003126 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00003127 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00003128 Context->getSizeType(),
3129 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003130 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3131 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3132 // For X86 it is more complicated and some kind of target specific routine
3133 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003134 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003135 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003136 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3137 llvm::APInt(IntSize, 8),
3138 Context->IntTy,
3139 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003140 BinaryOperator *lessThanExpr =
3141 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3142 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003143 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003144 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003145 new (Context) ConditionalOperator(lessThanExpr,
3146 SourceLocation(), CE,
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003147 SourceLocation(), STCE, (Expr*)0,
John McCall09431682010-11-18 19:01:18 +00003148 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003149 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3150 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003151 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003152 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003153 return ReplacingStmt;
3154}
3155
Steve Naroffb29b4272008-04-14 22:03:09 +00003156Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003157 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3158 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003159
Steve Naroff934f2762007-10-24 22:48:43 +00003160 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003161 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003162
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003163 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003164 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003165}
3166
Steve Naroff621edce2009-04-29 16:37:50 +00003167// typedef struct objc_object Protocol;
3168QualType RewriteObjC::getProtocolType() {
3169 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003170 TypeSourceInfo *TInfo
3171 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003172 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003173 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003174 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003175 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003176 }
3177 return Context->getTypeDeclType(ProtocolTypeDecl);
3178}
3179
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003180/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003181/// a synthesized/forward data reference (to the protocol's metadata).
3182/// The forward references (and metadata) are generated in
3183/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003184Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003185 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3186 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003187 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00003188 ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003189 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003190 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3191 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003192 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003193 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003194 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003195 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003196 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003197 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003198 ReplaceStmt(Exp, castExpr);
3199 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003200 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003201 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003202
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003203}
3204
Mike Stump1eb44332009-09-09 15:08:12 +00003205bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003206 const char *endBuf) {
3207 while (startBuf < endBuf) {
3208 if (*startBuf == '#') {
3209 // Skip whitespace.
3210 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3211 ;
3212 if (!strncmp(startBuf, "if", strlen("if")) ||
3213 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3214 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3215 !strncmp(startBuf, "define", strlen("define")) ||
3216 !strncmp(startBuf, "undef", strlen("undef")) ||
3217 !strncmp(startBuf, "else", strlen("else")) ||
3218 !strncmp(startBuf, "elif", strlen("elif")) ||
3219 !strncmp(startBuf, "endif", strlen("endif")) ||
3220 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3221 !strncmp(startBuf, "include", strlen("include")) ||
3222 !strncmp(startBuf, "import", strlen("import")) ||
3223 !strncmp(startBuf, "include_next", strlen("include_next")))
3224 return true;
3225 }
3226 startBuf++;
3227 }
3228 return false;
3229}
3230
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003231/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003232/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003233void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003234 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003235 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003236 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003237 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003238 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003239 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003240 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003241 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003242 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003243 SourceLocation LocStart = CDecl->getLocStart();
3244 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003245
Steve Narofffea763e82007-11-14 19:25:57 +00003246 const char *startBuf = SM->getCharacterData(LocStart);
3247 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003248
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003249 // If no ivars and no root or if its root, directly or indirectly,
3250 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003251 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3252 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003253 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003254 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003255 return;
3256 }
Mike Stump1eb44332009-09-09 15:08:12 +00003257
3258 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003259 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003260 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003261 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003262 if (LangOpts.Microsoft)
3263 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003264
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003265 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003266 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003267 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003268 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003269 // If the buffer contains preprocessor directives, we do more fine-grained
3270 // rewrites. This is intended to fix code that looks like (which occurs in
3271 // NSURL.h, for example):
3272 //
3273 // #ifdef XYZ
3274 // @interface Foo : NSObject
3275 // #else
3276 // @interface FooBar : NSObject
3277 // #endif
3278 // {
3279 // int i;
3280 // }
3281 // @end
3282 //
3283 // This clause is segregated to avoid breaking the common case.
3284 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003285 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003286 CDecl->getClassLoc();
3287 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003288 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003289
Chris Lattnercafeb352009-02-20 18:18:36 +00003290 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003291 // advance to the end of the referenced protocols.
3292 while (endHeader < cursor && *endHeader != '>') endHeader++;
3293 endHeader++;
3294 }
3295 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003296 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003297 } else {
3298 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003299 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003300 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003301 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003302 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003303 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003304 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003305 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003306 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003307
Steve Narofffea763e82007-11-14 19:25:57 +00003308 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003309 SourceLocation OnePastCurly =
3310 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003311 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003312 }
3313 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003314
Steve Narofffea763e82007-11-14 19:25:57 +00003315 // Now comment out any visibility specifiers.
3316 while (cursor < endBuf) {
3317 if (*cursor == '@') {
3318 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003319 // Skip whitespace.
3320 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3321 /*scan*/;
3322
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003323 // FIXME: presence of @public, etc. inside comment results in
3324 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003325 if (!strncmp(cursor, "public", strlen("public")) ||
3326 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003327 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003328 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003329 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003330 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003331 // FIXME: If there are cases where '<' is used in ivar declaration part
3332 // of user code, then scan the ivar list and use needToScanForQualifiers
3333 // for type checking.
3334 else if (*cursor == '<') {
3335 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003336 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003337 cursor = strchr(cursor, '>');
3338 cursor++;
3339 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003340 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003341 } else if (*cursor == '^') { // rewrite block specifier.
3342 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003343 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003344 }
Steve Narofffea763e82007-11-14 19:25:57 +00003345 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003346 }
Steve Narofffea763e82007-11-14 19:25:57 +00003347 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003348 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003349 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003350 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003351 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003352 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003353 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003354 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003355 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003356 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003357 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003358 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003359 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003360 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003361}
3362
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003363// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003364/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003365template<typename MethodIterator>
3366void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3367 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003368 bool IsInstanceMethod,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003369 llvm::StringRef prefix,
3370 llvm::StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003371 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003372 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003373
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003374 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003375 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003376 SEL _cmd;
3377 char *method_types;
3378 void *_imp;
3379 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003380 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003381 Result += "\nstruct _objc_method {\n";
3382 Result += "\tSEL _cmd;\n";
3383 Result += "\tchar *method_types;\n";
3384 Result += "\tvoid *_imp;\n";
3385 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003386
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003387 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003388 }
Mike Stump1eb44332009-09-09 15:08:12 +00003389
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003390 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003391
Steve Naroff946a6932008-03-11 00:12:29 +00003392 /* struct {
3393 struct _objc_method_list *next_method;
3394 int method_count;
3395 struct _objc_method method_list[];
3396 }
3397 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003398 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003399 Result += "\nstatic struct {\n";
3400 Result += "\tstruct _objc_method_list *next_method;\n";
3401 Result += "\tint method_count;\n";
3402 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003403 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003404 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003405 Result += prefix;
3406 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3407 Result += "_METHODS_";
3408 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003409 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003410 Result += IsInstanceMethod ? "inst" : "cls";
3411 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003412 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003413
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003414 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003415 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003416 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003417 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003418 Result += "\", \"";
3419 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003420 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003421 Result += MethodInternalNames[*MethodBegin];
3422 Result += "}\n";
3423 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3424 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003425 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003426 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003427 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003428 Result += "\", \"";
3429 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003430 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003431 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003432 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003433 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003434 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003435}
3436
Steve Naroff621edce2009-04-29 16:37:50 +00003437/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003438void RewriteObjC::
Daniel Dunbar4087f272010-08-17 22:39:59 +00003439RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3440 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003441 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003442
3443 // Output struct protocol_methods holder of method selector and type.
3444 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3445 /* struct protocol_methods {
3446 SEL _cmd;
3447 char *method_types;
3448 }
3449 */
3450 Result += "\nstruct _protocol_methods {\n";
3451 Result += "\tstruct objc_selector *_cmd;\n";
3452 Result += "\tchar *method_types;\n";
3453 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003454
Steve Naroff621edce2009-04-29 16:37:50 +00003455 objc_protocol_methods = true;
3456 }
3457 // Do not synthesize the protocol more than once.
3458 if (ObjCSynthesizedProtocols.count(PDecl))
3459 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003460
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003461 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3462 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3463 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003464 /* struct _objc_protocol_method_list {
3465 int protocol_method_count;
3466 struct protocol_methods protocols[];
3467 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003468 */
Steve Naroff621edce2009-04-29 16:37:50 +00003469 Result += "\nstatic struct {\n";
3470 Result += "\tint protocol_method_count;\n";
3471 Result += "\tstruct _protocol_methods protocol_methods[";
3472 Result += utostr(NumMethods);
3473 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3474 Result += PDecl->getNameAsString();
3475 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3476 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003477
Steve Naroff621edce2009-04-29 16:37:50 +00003478 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003479 for (ObjCProtocolDecl::instmeth_iterator
3480 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003481 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003482 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003483 Result += "\t ,{{(struct objc_selector *)\"";
3484 else
3485 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003486 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003487 std::string MethodTypeString;
3488 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3489 Result += "\", \"";
3490 Result += MethodTypeString;
3491 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003492 }
Steve Naroff621edce2009-04-29 16:37:50 +00003493 Result += "\t }\n};\n";
3494 }
Mike Stump1eb44332009-09-09 15:08:12 +00003495
Steve Naroff621edce2009-04-29 16:37:50 +00003496 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003497 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3498 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003499 if (NumMethods > 0) {
3500 /* struct _objc_protocol_method_list {
3501 int protocol_method_count;
3502 struct protocol_methods protocols[];
3503 }
3504 */
3505 Result += "\nstatic struct {\n";
3506 Result += "\tint protocol_method_count;\n";
3507 Result += "\tstruct _protocol_methods protocol_methods[";
3508 Result += utostr(NumMethods);
3509 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3510 Result += PDecl->getNameAsString();
3511 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3512 "{\n\t";
3513 Result += utostr(NumMethods);
3514 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003515
Steve Naroff621edce2009-04-29 16:37:50 +00003516 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003517 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003518 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003519 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003520 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003521 Result += "\t ,{{(struct objc_selector *)\"";
3522 else
3523 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003524 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003525 std::string MethodTypeString;
3526 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3527 Result += "\", \"";
3528 Result += MethodTypeString;
3529 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003530 }
Steve Naroff621edce2009-04-29 16:37:50 +00003531 Result += "\t }\n};\n";
3532 }
3533
3534 // Output:
3535 /* struct _objc_protocol {
3536 // Objective-C 1.0 extensions
3537 struct _objc_protocol_extension *isa;
3538 char *protocol_name;
3539 struct _objc_protocol **protocol_list;
3540 struct _objc_protocol_method_list *instance_methods;
3541 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003542 };
Steve Naroff621edce2009-04-29 16:37:50 +00003543 */
3544 static bool objc_protocol = false;
3545 if (!objc_protocol) {
3546 Result += "\nstruct _objc_protocol {\n";
3547 Result += "\tstruct _objc_protocol_extension *isa;\n";
3548 Result += "\tchar *protocol_name;\n";
3549 Result += "\tstruct _objc_protocol **protocol_list;\n";
3550 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3551 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003552 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003553
Steve Naroff621edce2009-04-29 16:37:50 +00003554 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003555 }
Mike Stump1eb44332009-09-09 15:08:12 +00003556
Steve Naroff621edce2009-04-29 16:37:50 +00003557 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3558 Result += PDecl->getNameAsString();
3559 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3560 "{\n\t0, \"";
3561 Result += PDecl->getNameAsString();
3562 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003563 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003564 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3565 Result += PDecl->getNameAsString();
3566 Result += ", ";
3567 }
3568 else
3569 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003570 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003571 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3572 Result += PDecl->getNameAsString();
3573 Result += "\n";
3574 }
3575 else
3576 Result += "0\n";
3577 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003578
Steve Naroff621edce2009-04-29 16:37:50 +00003579 // Mark this protocol as having been generated.
3580 if (!ObjCSynthesizedProtocols.insert(PDecl))
3581 assert(false && "protocol already synthesized");
3582
3583}
3584
3585void RewriteObjC::
3586RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003587 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003588 std::string &Result) {
3589 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003590
Steve Naroff621edce2009-04-29 16:37:50 +00003591 for (unsigned i = 0; i != Protocols.size(); i++)
3592 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3593
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003594 // Output the top lovel protocol meta-data for the class.
3595 /* struct _objc_protocol_list {
3596 struct _objc_protocol_list *next;
3597 int protocol_count;
3598 struct _objc_protocol *class_protocols[];
3599 }
3600 */
3601 Result += "\nstatic struct {\n";
3602 Result += "\tstruct _objc_protocol_list *next;\n";
3603 Result += "\tint protocol_count;\n";
3604 Result += "\tstruct _objc_protocol *class_protocols[";
3605 Result += utostr(Protocols.size());
3606 Result += "];\n} _OBJC_";
3607 Result += prefix;
3608 Result += "_PROTOCOLS_";
3609 Result += ClassName;
3610 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3611 "{\n\t0, ";
3612 Result += utostr(Protocols.size());
3613 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003614
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003615 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003616 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003617 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003618
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003619 for (unsigned i = 1; i != Protocols.size(); i++) {
3620 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003621 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003622 Result += "\n";
3623 }
3624 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003625}
3626
Steve Naroff621edce2009-04-29 16:37:50 +00003627
Mike Stump1eb44332009-09-09 15:08:12 +00003628/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003629/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003630void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003631 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003632 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003633 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003634 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003635 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003636 CDecl = CDecl->getNextClassCategory())
3637 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3638 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003639
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003640 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003641 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003642 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003643
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003644 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003645 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003646 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003647
3648 // If any of our property implementations have associated getters or
3649 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003650 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3651 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003652 Prop != PropEnd; ++Prop) {
3653 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3654 continue;
3655 if (!(*Prop)->getPropertyIvarDecl())
3656 continue;
3657 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3658 if (!PD)
3659 continue;
3660 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3661 InstanceMethods.push_back(Getter);
3662 if (PD->isReadOnly())
3663 continue;
3664 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3665 InstanceMethods.push_back(Setter);
3666 }
3667 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003668 true, "CATEGORY_", FullCategoryName.c_str(),
3669 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003670
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003671 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003672 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003673 false, "CATEGORY_", FullCategoryName.c_str(),
3674 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003675
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003676 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003677 // Null CDecl is case of a category implementation with no category interface
3678 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003679 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003680 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003681 /* struct _objc_category {
3682 char *category_name;
3683 char *class_name;
3684 struct _objc_method_list *instance_methods;
3685 struct _objc_method_list *class_methods;
3686 struct _objc_protocol_list *protocols;
3687 // Objective-C 1.0 extensions
3688 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003689 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003690 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003691 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003692 */
Mike Stump1eb44332009-09-09 15:08:12 +00003693
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003694 static bool objc_category = false;
3695 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003696 Result += "\nstruct _objc_category {\n";
3697 Result += "\tchar *category_name;\n";
3698 Result += "\tchar *class_name;\n";
3699 Result += "\tstruct _objc_method_list *instance_methods;\n";
3700 Result += "\tstruct _objc_method_list *class_methods;\n";
3701 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003702 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003703 Result += "\tstruct _objc_property_list *instance_properties;\n";
3704 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003705 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003706 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003707 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3708 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003709 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003710 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003711 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003712 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003713 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003714
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003715 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003716 Result += "\t, (struct _objc_method_list *)"
3717 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3718 Result += FullCategoryName;
3719 Result += "\n";
3720 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003721 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003722 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003723 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003724 Result += "\t, (struct _objc_method_list *)"
3725 "&_OBJC_CATEGORY_CLASS_METHODS_";
3726 Result += FullCategoryName;
3727 Result += "\n";
3728 }
3729 else
3730 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003731
Chris Lattnercafeb352009-02-20 18:18:36 +00003732 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003733 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003734 Result += FullCategoryName;
3735 Result += "\n";
3736 }
3737 else
3738 Result += "\t, 0\n";
3739 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003740}
3741
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003742/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3743/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003744void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003745 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003746 if (ivar->isBitField()) {
3747 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3748 // place all bitfields at offset 0.
3749 Result += "0";
3750 } else {
3751 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003752 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003753 if (LangOpts.Microsoft)
3754 Result += "_IMPL";
3755 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003756 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003757 Result += ")";
3758 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003759}
3760
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003761//===----------------------------------------------------------------------===//
3762// Meta Data Emission
3763//===----------------------------------------------------------------------===//
3764
Steve Naroffb29b4272008-04-14 22:03:09 +00003765void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003766 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003767 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003768
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003769 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003770 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003771 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003772 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003773 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003774 }
Mike Stump1eb44332009-09-09 15:08:12 +00003775
Chris Lattnerbe6df082007-12-12 07:56:42 +00003776 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003777 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003778 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003779 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003780 if (NumIvars > 0) {
3781 static bool objc_ivar = false;
3782 if (!objc_ivar) {
3783 /* struct _objc_ivar {
3784 char *ivar_name;
3785 char *ivar_type;
3786 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003787 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003788 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003789 Result += "\nstruct _objc_ivar {\n";
3790 Result += "\tchar *ivar_name;\n";
3791 Result += "\tchar *ivar_type;\n";
3792 Result += "\tint ivar_offset;\n";
3793 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003794
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003795 objc_ivar = true;
3796 }
3797
Steve Naroff946a6932008-03-11 00:12:29 +00003798 /* struct {
3799 int ivar_count;
3800 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003801 };
Steve Naroff946a6932008-03-11 00:12:29 +00003802 */
Mike Stump1eb44332009-09-09 15:08:12 +00003803 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003804 Result += "\tint ivar_count;\n";
3805 Result += "\tstruct _objc_ivar ivar_list[";
3806 Result += utostr(NumIvars);
3807 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003808 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003809 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003810 "{\n\t";
3811 Result += utostr(NumIvars);
3812 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003813
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003814 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003815 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003816 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003817 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003818 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003819 IV != IVEnd; ++IV)
3820 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003821 IVI = IDecl->ivar_begin();
3822 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003823 } else {
3824 IVI = CDecl->ivar_begin();
3825 IVE = CDecl->ivar_end();
3826 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003827 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003828 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003829 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003830 std::string TmpString, StrEncoding;
3831 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3832 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003833 Result += StrEncoding;
3834 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003835 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003836 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003837 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003838 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003839 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003840 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003841 std::string TmpString, StrEncoding;
3842 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3843 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003844 Result += StrEncoding;
3845 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003846 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003847 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003848 }
Mike Stump1eb44332009-09-09 15:08:12 +00003849
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003850 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003851 }
Mike Stump1eb44332009-09-09 15:08:12 +00003852
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003853 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003854 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003855 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003856
3857 // If any of our property implementations have associated getters or
3858 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003859 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3860 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003861 Prop != PropEnd; ++Prop) {
3862 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3863 continue;
3864 if (!(*Prop)->getPropertyIvarDecl())
3865 continue;
3866 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3867 if (!PD)
3868 continue;
3869 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003870 if (!Getter->isDefined())
3871 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003872 if (PD->isReadOnly())
3873 continue;
3874 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003875 if (!Setter->isDefined())
3876 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003877 }
3878 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003879 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003880
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003881 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003882 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003883 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003884
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003885 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003886 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003887 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003888
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003889 // Declaration of class/meta-class metadata
3890 /* struct _objc_class {
3891 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003892 const char *super_class_name;
3893 char *name;
3894 long version;
3895 long info;
3896 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003897 struct _objc_ivar_list *ivars;
3898 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003899 struct objc_cache *cache;
3900 struct objc_protocol_list *protocols;
3901 const char *ivar_layout;
3902 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003903 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003904 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003905 static bool objc_class = false;
3906 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003907 Result += "\nstruct _objc_class {\n";
3908 Result += "\tstruct _objc_class *isa;\n";
3909 Result += "\tconst char *super_class_name;\n";
3910 Result += "\tchar *name;\n";
3911 Result += "\tlong version;\n";
3912 Result += "\tlong info;\n";
3913 Result += "\tlong instance_size;\n";
3914 Result += "\tstruct _objc_ivar_list *ivars;\n";
3915 Result += "\tstruct _objc_method_list *methods;\n";
3916 Result += "\tstruct objc_cache *cache;\n";
3917 Result += "\tstruct _objc_protocol_list *protocols;\n";
3918 Result += "\tconst char *ivar_layout;\n";
3919 Result += "\tstruct _objc_class_ext *ext;\n";
3920 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003921 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003922 }
Mike Stump1eb44332009-09-09 15:08:12 +00003923
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003924 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003925 ObjCInterfaceDecl *RootClass = 0;
3926 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003927 while (SuperClass) {
3928 RootClass = SuperClass;
3929 SuperClass = SuperClass->getSuperClass();
3930 }
3931 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003932
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003933 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003934 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003935 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003936 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003937 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003938 Result += "\"";
3939
3940 if (SuperClass) {
3941 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003942 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003943 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003944 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003945 Result += "\"";
3946 }
3947 else {
3948 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003949 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003950 Result += "\"";
3951 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003952 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003953 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003954 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003955 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003956 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003957 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003958 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003959 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003960 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003961 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003962 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003963 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003964 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003965 Result += ",0,0\n";
3966 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003967 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003968 Result += "\t,0,0,0,0\n";
3969 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003970
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003971 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003972 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003973 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003974 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003975 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003976 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003977 if (SuperClass) {
3978 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003979 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003980 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003981 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003982 Result += "\"";
3983 }
3984 else {
3985 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003986 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003987 Result += "\"";
3988 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003989 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003990 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003991 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003992 Result += ",0";
3993 else {
3994 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003995 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003996 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003997 if (LangOpts.Microsoft)
3998 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003999 Result += ")";
4000 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004001 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00004002 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004003 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004004 Result += "\n\t";
4005 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004006 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004007 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004008 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00004009 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004010 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004011 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004012 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004013 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004014 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00004015 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004016 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004017 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004018 Result += ", 0,0\n";
4019 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004020 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004021 Result += ",0,0,0\n";
4022 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004023}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004024
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004025/// RewriteImplementations - This routine rewrites all method implementations
4026/// and emits meta-data.
4027
Steve Narofface66252008-11-13 20:07:04 +00004028void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004029 int ClsDefCount = ClassImplementation.size();
4030 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004031
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004032 // Rewrite implemented methods
4033 for (int i = 0; i < ClsDefCount; i++)
4034 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004035
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004036 for (int i = 0; i < CatDefCount; i++)
4037 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004038}
Mike Stump1eb44332009-09-09 15:08:12 +00004039
Steve Narofface66252008-11-13 20:07:04 +00004040void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4041 int ClsDefCount = ClassImplementation.size();
4042 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004043
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004044 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004045 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004046 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004047
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004048 // For each implemented category, write out all its meta data.
4049 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004050 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004051
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004052 // Write objc_symtab metadata
4053 /*
4054 struct _objc_symtab
4055 {
4056 long sel_ref_cnt;
4057 SEL *refs;
4058 short cls_def_cnt;
4059 short cat_def_cnt;
4060 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004061 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004062 */
Mike Stump1eb44332009-09-09 15:08:12 +00004063
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004064 Result += "\nstruct _objc_symtab {\n";
4065 Result += "\tlong sel_ref_cnt;\n";
4066 Result += "\tSEL *refs;\n";
4067 Result += "\tshort cls_def_cnt;\n";
4068 Result += "\tshort cat_def_cnt;\n";
4069 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4070 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004071
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004072 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004073 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004074 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004075 + ", " + utostr(CatDefCount) + "\n";
4076 for (int i = 0; i < ClsDefCount; i++) {
4077 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004078 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004079 Result += "\n";
4080 }
Mike Stump1eb44332009-09-09 15:08:12 +00004081
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004082 for (int i = 0; i < CatDefCount; i++) {
4083 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004084 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004085 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004086 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004087 Result += "\n";
4088 }
Mike Stump1eb44332009-09-09 15:08:12 +00004089
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004090 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004091
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004092 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004093
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004094 /*
4095 struct _objc_module {
4096 long version;
4097 long size;
4098 const char *name;
4099 struct _objc_symtab *symtab;
4100 }
4101 */
Mike Stump1eb44332009-09-09 15:08:12 +00004102
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004103 Result += "\nstruct _objc_module {\n";
4104 Result += "\tlong version;\n";
4105 Result += "\tlong size;\n";
4106 Result += "\tconst char *name;\n";
4107 Result += "\tstruct _objc_symtab *symtab;\n";
4108 Result += "};\n\n";
4109 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004110 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004111 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004112 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004113 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004114
4115 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004116 if (ProtocolExprDecls.size()) {
4117 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4118 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004119 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004120 E = ProtocolExprDecls.end(); I != E; ++I) {
4121 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4122 Result += (*I)->getNameAsString();
4123 Result += " = &_OBJC_PROTOCOL_";
4124 Result += (*I)->getNameAsString();
4125 Result += ";\n";
4126 }
4127 Result += "#pragma data_seg(pop)\n\n";
4128 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004129 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004130 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004131 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4132 Result += "&_OBJC_MODULES;\n";
4133 Result += "#pragma data_seg(pop)\n\n";
4134 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004135}
Chris Lattner311ff022007-10-16 22:36:42 +00004136
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004137void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4138 const std::string &Name,
4139 ValueDecl *VD) {
4140 assert(BlockByRefDeclNo.count(VD) &&
4141 "RewriteByRefString: ByRef decl missing");
4142 ResultStr += "struct __Block_byref_" + Name +
4143 "_" + utostr(BlockByRefDeclNo[VD]) ;
4144}
4145
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004146static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4147 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4148 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4149 return false;
4150}
4151
Steve Naroff54055232008-10-27 17:20:55 +00004152std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004153 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004154 std::string Tag) {
4155 const FunctionType *AFT = CE->getFunctionType();
4156 QualType RT = AFT->getResultType();
4157 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004158 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004159 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004160
Steve Naroff54055232008-10-27 17:20:55 +00004161 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004162
Douglas Gregor72564e72009-02-26 23:50:07 +00004163 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004164 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004165 // block (to reference imported block decl refs).
4166 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004167 } else if (BD->param_empty()) {
4168 S += "(" + StructRef + " *__cself)";
4169 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004170 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004171 assert(FT && "SynthesizeBlockFunc: No function proto");
4172 S += '(';
4173 // first add the implicit argument.
4174 S += StructRef + " *__cself, ";
4175 std::string ParamStr;
4176 for (BlockDecl::param_iterator AI = BD->param_begin(),
4177 E = BD->param_end(); AI != E; ++AI) {
4178 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004179 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004180 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004181 if (convertBlockPointerToFunctionPointer(QT))
4182 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004183 else
4184 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004185 S += ParamStr;
4186 }
4187 if (FT->isVariadic()) {
4188 if (!BD->param_empty()) S += ", ";
4189 S += "...";
4190 }
4191 S += ')';
4192 }
4193 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004194
Steve Naroff54055232008-10-27 17:20:55 +00004195 // Create local declarations to avoid rewriting all closure decl ref exprs.
4196 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004197 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004198 E = BlockByRefDecls.end(); I != E; ++I) {
4199 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004200 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004201 std::string TypeString;
4202 RewriteByRefString(TypeString, Name, (*I));
4203 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004204 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004205 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004206 }
Steve Naroff54055232008-10-27 17:20:55 +00004207 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004208 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004209 E = BlockByCopyDecls.end(); I != E; ++I) {
4210 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004211 // Handle nested closure invocation. For example:
4212 //
4213 // void (^myImportedClosure)(void);
4214 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004215 //
Steve Naroff54055232008-10-27 17:20:55 +00004216 // void (^anotherClosure)(void);
4217 // anotherClosure = ^(void) {
4218 // myImportedClosure(); // import and invoke the closure
4219 // };
4220 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004221 if (isTopLevelBlockPointerType((*I)->getType())) {
4222 RewriteBlockPointerTypeVariable(S, (*I));
4223 S += " = (";
4224 RewriteBlockPointerType(S, (*I)->getType());
4225 S += ")";
4226 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4227 }
4228 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004229 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004230 QualType QT = (*I)->getType();
4231 if (HasLocalVariableExternalStorage(*I))
4232 QT = Context->getPointerType(QT);
4233 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004234 S += Name + " = __cself->" +
4235 (*I)->getNameAsString() + "; // bound by copy\n";
4236 }
Steve Naroff54055232008-10-27 17:20:55 +00004237 }
4238 std::string RewrittenStr = RewrittenBlockExprs[CE];
4239 const char *cstr = RewrittenStr.c_str();
4240 while (*cstr++ != '{') ;
4241 S += cstr;
4242 S += "\n";
4243 return S;
4244}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004245
Steve Naroff54055232008-10-27 17:20:55 +00004246std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004247 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004248 std::string Tag) {
4249 std::string StructRef = "struct " + Tag;
4250 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004251
Steve Naroff54055232008-10-27 17:20:55 +00004252 S += funcName;
4253 S += "_block_copy_" + utostr(i);
4254 S += "(" + StructRef;
4255 S += "*dst, " + StructRef;
4256 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004257 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004258 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004259 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004260 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004261 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004262 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004263 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004264 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004265 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004266 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004267 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004268 S += "}\n";
4269
Steve Naroff54055232008-10-27 17:20:55 +00004270 S += "\nstatic void __";
4271 S += funcName;
4272 S += "_block_dispose_" + utostr(i);
4273 S += "(" + StructRef;
4274 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004275 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004276 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004277 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004278 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004279 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004280 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004281 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004282 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004283 }
Mike Stump1eb44332009-09-09 15:08:12 +00004284 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004285 return S;
4286}
4287
Steve Naroff01aec112009-12-06 21:14:13 +00004288std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4289 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004290 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004291 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004292
Steve Naroff54055232008-10-27 17:20:55 +00004293 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004294 S += " struct " + Desc;
4295 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004296
Steve Naroff01aec112009-12-06 21:14:13 +00004297 Constructor += "(void *fp, "; // Invoke function pointer.
4298 Constructor += "struct " + Desc; // Descriptor pointer.
4299 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004300
Steve Naroff54055232008-10-27 17:20:55 +00004301 if (BlockDeclRefs.size()) {
4302 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004303 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004304 E = BlockByCopyDecls.end(); I != E; ++I) {
4305 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004306 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004307 std::string ArgName = "_" + FieldName;
4308 // Handle nested closure invocation. For example:
4309 //
4310 // void (^myImportedBlock)(void);
4311 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004312 //
Steve Naroff54055232008-10-27 17:20:55 +00004313 // void (^anotherBlock)(void);
4314 // anotherBlock = ^(void) {
4315 // myImportedBlock(); // import and invoke the closure
4316 // };
4317 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004318 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004319 S += "struct __block_impl *";
4320 Constructor += ", void *" + ArgName;
4321 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004322 QualType QT = (*I)->getType();
4323 if (HasLocalVariableExternalStorage(*I))
4324 QT = Context->getPointerType(QT);
4325 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4326 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004327 Constructor += ", " + ArgName;
4328 }
4329 S += FieldName + ";\n";
4330 }
4331 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004332 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004333 E = BlockByRefDecls.end(); I != E; ++I) {
4334 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004335 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004336 std::string ArgName = "_" + FieldName;
4337 // Handle nested closure invocation. For example:
4338 //
4339 // void (^myImportedBlock)(void);
4340 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004341 //
Steve Naroff54055232008-10-27 17:20:55 +00004342 // void (^anotherBlock)(void);
4343 // anotherBlock = ^(void) {
4344 // myImportedBlock(); // import and invoke the closure
4345 // };
4346 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004347 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004348 S += "struct __block_impl *";
4349 Constructor += ", void *" + ArgName;
4350 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004351 std::string TypeString;
4352 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004353 TypeString += " *";
4354 FieldName = TypeString + FieldName;
4355 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004356 Constructor += ", " + ArgName;
4357 }
4358 S += FieldName + "; // by ref\n";
4359 }
4360 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004361 Constructor += ", int flags=0)";
4362 // Initialize all "by copy" arguments.
4363 bool firsTime = true;
4364 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4365 E = BlockByCopyDecls.end(); I != E; ++I) {
4366 std::string Name = (*I)->getNameAsString();
4367 if (firsTime) {
4368 Constructor += " : ";
4369 firsTime = false;
4370 }
4371 else
4372 Constructor += ", ";
4373 if (isTopLevelBlockPointerType((*I)->getType()))
4374 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4375 else
4376 Constructor += Name + "(_" + Name + ")";
4377 }
4378 // Initialize all "by ref" arguments.
4379 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4380 E = BlockByRefDecls.end(); I != E; ++I) {
4381 std::string Name = (*I)->getNameAsString();
4382 if (firsTime) {
4383 Constructor += " : ";
4384 firsTime = false;
4385 }
4386 else
4387 Constructor += ", ";
4388 if (isTopLevelBlockPointerType((*I)->getType()))
4389 Constructor += Name + "((struct __block_impl *)_"
4390 + Name + "->__forwarding)";
4391 else
4392 Constructor += Name + "(_" + Name + "->__forwarding)";
4393 }
4394
4395 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004396 if (GlobalVarDecl)
4397 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4398 else
4399 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004400 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004401
Steve Naroff01aec112009-12-06 21:14:13 +00004402 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004403 } else {
4404 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004405 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004406 if (GlobalVarDecl)
4407 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4408 else
4409 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004410 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4411 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004412 }
4413 Constructor += " ";
4414 Constructor += "}\n";
4415 S += Constructor;
4416 S += "};\n";
4417 return S;
4418}
4419
Steve Naroff01aec112009-12-06 21:14:13 +00004420std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4421 std::string ImplTag, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004422 llvm::StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004423 unsigned hasCopy) {
4424 std::string S = "\nstatic struct " + DescTag;
4425
4426 S += " {\n unsigned long reserved;\n";
4427 S += " unsigned long Block_size;\n";
4428 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004429 S += " void (*copy)(struct ";
4430 S += ImplTag; S += "*, struct ";
4431 S += ImplTag; S += "*);\n";
4432
4433 S += " void (*dispose)(struct ";
4434 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004435 }
4436 S += "} ";
4437
4438 S += DescTag + "_DATA = { 0, sizeof(struct ";
4439 S += ImplTag + ")";
4440 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004441 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4442 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004443 }
4444 S += "};\n";
4445 return S;
4446}
4447
Steve Naroff54055232008-10-27 17:20:55 +00004448void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004449 llvm::StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004450 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004451 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004452 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004453 bool RewriteSC = (GlobalVarDecl &&
4454 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004455 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004456 GlobalVarDecl->getType().getCVRQualifiers());
4457 if (RewriteSC) {
4458 std::string SC(" void __");
4459 SC += GlobalVarDecl->getNameAsString();
4460 SC += "() {}";
4461 InsertText(FunLocStart, SC);
4462 }
4463
Steve Naroff54055232008-10-27 17:20:55 +00004464 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004465 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4466 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004467 // Need to copy-in the inner copied-in variables not actually used in this
4468 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004469 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4470 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4471 ValueDecl *VD = Exp->getDecl();
4472 BlockDeclRefs.push_back(Exp);
4473 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4474 BlockByCopyDeclsPtrSet.insert(VD);
4475 BlockByCopyDecls.push_back(VD);
4476 }
4477 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4478 BlockByRefDeclsPtrSet.insert(VD);
4479 BlockByRefDecls.push_back(VD);
4480 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004481 // imported objects in the inner blocks not used in the outer
4482 // blocks must be copied/disposed in the outer block as well.
4483 if (Exp->isByRef() ||
4484 VD->getType()->isObjCObjectPointerType() ||
4485 VD->getType()->isBlockPointerType())
4486 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004487 }
Steve Naroff54055232008-10-27 17:20:55 +00004488
Daniel Dunbar4087f272010-08-17 22:39:59 +00004489 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4490 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004491
Steve Naroff01aec112009-12-06 21:14:13 +00004492 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004493
Benjamin Kramerd999b372010-02-14 14:14:16 +00004494 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004495
Steve Naroff01aec112009-12-06 21:14:13 +00004496 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004497
Benjamin Kramerd999b372010-02-14 14:14:16 +00004498 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004499
4500 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004501 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004502 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004503 }
Steve Naroff01aec112009-12-06 21:14:13 +00004504 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4505 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004506 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004507
Steve Naroff54055232008-10-27 17:20:55 +00004508 BlockDeclRefs.clear();
4509 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004510 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004511 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004512 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004513 ImportedBlockDecls.clear();
4514 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004515 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004516 // Must insert any 'const/volatile/static here. Since it has been
4517 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004518 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004519 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004520 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004521 if (GlobalVarDecl->getType().isConstQualified())
4522 SC += "const ";
4523 if (GlobalVarDecl->getType().isVolatileQualified())
4524 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004525 if (GlobalVarDecl->getType().isRestrictQualified())
4526 SC += "restrict ";
4527 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004528 }
4529
Steve Naroff54055232008-10-27 17:20:55 +00004530 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004531 InnerDeclRefsCount.clear();
4532 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004533 RewrittenBlockExprs.clear();
4534}
4535
4536void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4537 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004538 llvm::StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004539
Steve Naroff54055232008-10-27 17:20:55 +00004540 SynthesizeBlockLiterals(FunLocStart, FuncName);
4541}
4542
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004543static void BuildUniqueMethodName(std::string &Name,
4544 ObjCMethodDecl *MD) {
4545 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004546 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004547 Name += "__" + MD->getSelector().getAsString();
4548 // Convert colons to underscores.
4549 std::string::size_type loc = 0;
4550 while ((loc = Name.find(":", loc)) != std::string::npos)
4551 Name.replace(loc, 1, "_");
4552}
4553
Steve Naroff54055232008-10-27 17:20:55 +00004554void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004555 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4556 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004557 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004558 std::string FuncName;
4559 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004560 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004561}
4562
4563void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4564 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4565 CI != E; ++CI)
4566 if (*CI) {
4567 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4568 GetBlockDeclRefExprs(CBE->getBody());
4569 else
4570 GetBlockDeclRefExprs(*CI);
4571 }
4572 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004573 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004574 // FIXME: Handle enums.
4575 if (!isa<FunctionDecl>(CDRE->getDecl()))
4576 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004577 }
4578 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4579 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4580 BlockDeclRefExpr *BDRE =
4581 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004582 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004583 BlockDeclRefs.push_back(BDRE);
4584 }
4585
Steve Naroff54055232008-10-27 17:20:55 +00004586 return;
4587}
4588
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004589void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4590 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004591 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004592 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4593 CI != E; ++CI)
4594 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004595 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4596 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004597 GetInnerBlockDeclRefExprs(CBE->getBody(),
4598 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004599 InnerContexts);
4600 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004601 else
4602 GetInnerBlockDeclRefExprs(*CI,
4603 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004604 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004605
4606 }
4607 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004608 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004609 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004610 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004611 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004612 }
4613 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4614 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4615 if (Var->isFunctionOrMethodVarDecl())
4616 ImportedLocalExternalDecls.insert(Var);
4617 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004618
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004619 return;
4620}
4621
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004622/// convertFunctionTypeOfBlocks - This routine converts a function type
4623/// whose result type may be a block pointer or whose argument type(s)
4624/// might be block pointers to an equivalent funtion type replacing
4625/// all block pointers to function pointers.
4626QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4627 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4628 // FTP will be null for closures that don't take arguments.
4629 // Generate a funky cast.
4630 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004631 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004632 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004633
4634 if (FTP) {
4635 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4636 E = FTP->arg_type_end(); I && (I != E); ++I) {
4637 QualType t = *I;
4638 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004639 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004640 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004641 ArgTypes.push_back(t);
4642 }
4643 }
4644 QualType FuncType;
4645 // FIXME. Does this work if block takes no argument but has a return type
4646 // which is of block type?
4647 if (HasBlockType)
4648 FuncType = Context->getFunctionType(Res,
4649 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4650 false, false, 0, 0, FunctionType::ExtInfo());
4651 else FuncType = QualType(FT, 0);
4652 return FuncType;
4653}
4654
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004655Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004656 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004657 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004658
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004659 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004660 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004661 } else if (const BlockDeclRefExpr *CDRE =
4662 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004663 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004664 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004665 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004666 }
4667 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4668 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4669 }
4670 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4671 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4672 else if (const ConditionalOperator *CEXPR =
4673 dyn_cast<ConditionalOperator>(BlockExp)) {
4674 Expr *LHSExp = CEXPR->getLHS();
4675 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4676 Expr *RHSExp = CEXPR->getRHS();
4677 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4678 Expr *CONDExp = CEXPR->getCond();
4679 ConditionalOperator *CondExpr =
4680 new (Context) ConditionalOperator(CONDExp,
4681 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004682 SourceLocation(), cast<Expr>(RHSStmt),
4683 (Expr*)0,
John McCall09431682010-11-18 19:01:18 +00004684 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004685 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004686 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4687 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004688 } else {
4689 assert(1 && "RewriteBlockClass: Bad type");
4690 }
4691 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004692 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004693 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004694 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004695 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004696
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004697 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004698 SourceLocation(),
4699 &Context->Idents.get("__block_impl"));
4700 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004701
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004702 // Generate a funky cast.
4703 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004704
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004705 // Push the block argument type.
4706 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004707 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004708 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004709 E = FTP->arg_type_end(); I && (I != E); ++I) {
4710 QualType t = *I;
4711 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004712 if (!convertBlockPointerToFunctionPointer(t))
4713 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004714 ArgTypes.push_back(t);
4715 }
Steve Naroff54055232008-10-27 17:20:55 +00004716 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004717 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004718 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004719 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4720 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00004721 FunctionType::ExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00004722
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004723 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004724
John McCall9d125032010-01-15 18:39:57 +00004725 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004726 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004727 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004728 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004729 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4730 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004731 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004732
Douglas Gregor44b43212008-12-11 16:49:14 +00004733 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004734 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004735 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004736 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004737 FD->getType(), VK_LValue,
4738 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004739
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004740
John McCall9d125032010-01-15 18:39:57 +00004741 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004742 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004743 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004744
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004745 llvm::SmallVector<Expr*, 8> BlkExprs;
4746 // Add the implicit argument.
4747 BlkExprs.push_back(BlkCast);
4748 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004749 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004750 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004751 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004752 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004753 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4754 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004755 Exp->getType(), VK_RValue,
4756 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004757 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004758}
4759
Steve Naroff621edce2009-04-29 16:37:50 +00004760// We need to return the rewritten expression to handle cases where the
4761// BlockDeclRefExpr is embedded in another expression being rewritten.
4762// For example:
4763//
4764// int main() {
4765// __block Foo *f;
4766// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004767//
Steve Naroff621edce2009-04-29 16:37:50 +00004768// void (^myblock)() = ^() {
4769// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4770// i = 77;
4771// };
4772//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004773Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004774 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004775 // for each DeclRefExp where BYREFVAR is name of the variable.
4776 ValueDecl *VD;
4777 bool isArrow = true;
4778 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4779 VD = BDRE->getDecl();
4780 else {
4781 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4782 isArrow = false;
4783 }
4784
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004785 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4786 &Context->Idents.get("__forwarding"),
4787 Context->VoidPtrTy, 0,
4788 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004789 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4790 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004791 FD->getType(), VK_LValue,
4792 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004793
Daniel Dunbar4087f272010-08-17 22:39:59 +00004794 llvm::StringRef Name = VD->getName();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004795 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4796 &Context->Idents.get(Name),
4797 Context->VoidPtrTy, 0,
4798 /*BitWidth=*/0, /*Mutable=*/true);
4799 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004800 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004801
4802
4803
Steve Naroffdf8570d2009-02-02 17:19:26 +00004804 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004805 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4806 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004807 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004808 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004809}
4810
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004811// Rewrites the imported local variable V with external storage
4812// (static, extern, etc.) as *V
4813//
4814Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4815 ValueDecl *VD = DRE->getDecl();
4816 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4817 if (!ImportedLocalExternalDecls.count(Var))
4818 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004819 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4820 VK_LValue, OK_Ordinary,
4821 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004822 // Need parens to enforce precedence.
4823 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4824 Exp);
4825 ReplaceStmt(DRE, PE);
4826 return PE;
4827}
4828
Steve Naroffb2f9e512008-11-03 23:29:32 +00004829void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4830 SourceLocation LocStart = CE->getLParenLoc();
4831 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004832
4833 // Need to avoid trying to rewrite synthesized casts.
4834 if (LocStart.isInvalid())
4835 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004836 // Need to avoid trying to rewrite casts contained in macros.
4837 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4838 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004839
Steve Naroff54055232008-10-27 17:20:55 +00004840 const char *startBuf = SM->getCharacterData(LocStart);
4841 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004842 QualType QT = CE->getType();
4843 const Type* TypePtr = QT->getAs<Type>();
4844 if (isa<TypeOfExprType>(TypePtr)) {
4845 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4846 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4847 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004848 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004849 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004850 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004851 return;
4852 }
Steve Naroff54055232008-10-27 17:20:55 +00004853 // advance the location to startArgList.
4854 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004855
Steve Naroff54055232008-10-27 17:20:55 +00004856 while (*argPtr++ && (argPtr < endBuf)) {
4857 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004858 case '^':
4859 // Replace the '^' with '*'.
4860 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004861 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004862 break;
Steve Naroff54055232008-10-27 17:20:55 +00004863 }
4864 }
4865 return;
4866}
4867
4868void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4869 SourceLocation DeclLoc = FD->getLocation();
4870 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004871
Steve Naroff54055232008-10-27 17:20:55 +00004872 // We have 1 or more arguments that have closure pointers.
4873 const char *startBuf = SM->getCharacterData(DeclLoc);
4874 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004875
Steve Naroff54055232008-10-27 17:20:55 +00004876 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004877
Steve Naroff54055232008-10-27 17:20:55 +00004878 parenCount++;
4879 // advance the location to startArgList.
4880 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4881 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004882
Steve Naroff54055232008-10-27 17:20:55 +00004883 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004884
Steve Naroff54055232008-10-27 17:20:55 +00004885 while (*argPtr++ && parenCount) {
4886 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004887 case '^':
4888 // Replace the '^' with '*'.
4889 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004890 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004891 break;
4892 case '(':
4893 parenCount++;
4894 break;
4895 case ')':
4896 parenCount--;
4897 break;
Steve Naroff54055232008-10-27 17:20:55 +00004898 }
4899 }
4900 return;
4901}
4902
4903bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004904 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004905 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004906 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004907 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004908 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004909 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004910 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004911 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004912 }
4913 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004914 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004915 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004916 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004917 return true;
4918 }
4919 return false;
4920}
4921
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004922bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4923 const FunctionProtoType *FTP;
4924 const PointerType *PT = QT->getAs<PointerType>();
4925 if (PT) {
4926 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4927 } else {
4928 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4929 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4930 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4931 }
4932 if (FTP) {
4933 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004934 E = FTP->arg_type_end(); I != E; ++I) {
4935 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004936 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004937 if ((*I)->isObjCObjectPointerType() &&
4938 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4939 return true;
4940 }
4941
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004942 }
4943 return false;
4944}
4945
Ted Kremenek8189cde2009-02-07 01:47:29 +00004946void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4947 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004948 const char *argPtr = strchr(Name, '(');
4949 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004950
Steve Naroff54055232008-10-27 17:20:55 +00004951 LParen = argPtr; // output the start.
4952 argPtr++; // skip past the left paren.
4953 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004954
Steve Naroff54055232008-10-27 17:20:55 +00004955 while (*argPtr && parenCount) {
4956 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004957 case '(': parenCount++; break;
4958 case ')': parenCount--; break;
4959 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004960 }
4961 if (parenCount) argPtr++;
4962 }
4963 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4964 RParen = argPtr; // output the end
4965}
4966
4967void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4968 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4969 RewriteBlockPointerFunctionArgs(FD);
4970 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004971 }
Steve Naroff54055232008-10-27 17:20:55 +00004972 // Handle Variables and Typedefs.
4973 SourceLocation DeclLoc = ND->getLocation();
4974 QualType DeclT;
4975 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4976 DeclT = VD->getType();
4977 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4978 DeclT = TDD->getUnderlyingType();
4979 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4980 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004981 else
Steve Naroff54055232008-10-27 17:20:55 +00004982 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004983
Steve Naroff54055232008-10-27 17:20:55 +00004984 const char *startBuf = SM->getCharacterData(DeclLoc);
4985 const char *endBuf = startBuf;
4986 // scan backward (from the decl location) for the end of the previous decl.
4987 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4988 startBuf--;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004989 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4990 std::string buf;
4991 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004992 // *startBuf != '^' if we are dealing with a pointer to function that
4993 // may take block argument types (which will be handled below).
4994 if (*startBuf == '^') {
4995 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004996 buf = '*';
4997 startBuf++;
4998 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004999 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005000 while (*startBuf != ')') {
5001 buf += *startBuf;
5002 startBuf++;
5003 OrigLength++;
5004 }
5005 buf += ')';
5006 OrigLength++;
5007
5008 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5009 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00005010 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005011 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00005012 DeclLoc = ND->getLocation();
5013 startBuf = SM->getCharacterData(DeclLoc);
5014 const char *argListBegin, *argListEnd;
5015 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5016 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005017 if (*argListBegin == '^')
5018 buf += '*';
5019 else if (*argListBegin == '<') {
5020 buf += "/*";
5021 buf += *argListBegin++;
5022 OrigLength++;;
5023 while (*argListBegin != '>') {
5024 buf += *argListBegin++;
5025 OrigLength++;
5026 }
5027 buf += *argListBegin;
5028 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005029 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005030 else
5031 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005032 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005033 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005034 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005035 buf += ')';
5036 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005037 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005038 ReplaceText(Start, OrigLength, buf);
5039
Steve Naroff54055232008-10-27 17:20:55 +00005040 return;
5041}
5042
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005043
5044/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5045/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5046/// struct Block_byref_id_object *src) {
5047/// _Block_object_assign (&_dest->object, _src->object,
5048/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5049/// [|BLOCK_FIELD_IS_WEAK]) // object
5050/// _Block_object_assign(&_dest->object, _src->object,
5051/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5052/// [|BLOCK_FIELD_IS_WEAK]) // block
5053/// }
5054/// And:
5055/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5056/// _Block_object_dispose(_src->object,
5057/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5058/// [|BLOCK_FIELD_IS_WEAK]) // object
5059/// _Block_object_dispose(_src->object,
5060/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5061/// [|BLOCK_FIELD_IS_WEAK]) // block
5062/// }
5063
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005064std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5065 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005066 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005067 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005068 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005069 CopyDestroyCache.insert(flag);
5070 S = "static void __Block_byref_id_object_copy_";
5071 S += utostr(flag);
5072 S += "(void *dst, void *src) {\n";
5073
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005074 // offset into the object pointer is computed as:
5075 // void * + void* + int + int + void* + void *
5076 unsigned IntSize =
5077 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5078 unsigned VoidPtrSize =
5079 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5080
5081 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
5082 S += " _Block_object_assign((char*)dst + ";
5083 S += utostr(offset);
5084 S += ", *(void * *) ((char*)src + ";
5085 S += utostr(offset);
5086 S += "), ";
5087 S += utostr(flag);
5088 S += ");\n}\n";
5089
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005090 S += "static void __Block_byref_id_object_dispose_";
5091 S += utostr(flag);
5092 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005093 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5094 S += utostr(offset);
5095 S += "), ";
5096 S += utostr(flag);
5097 S += ");\n}\n";
5098 return S;
5099}
5100
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005101/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5102/// the declaration into:
5103/// struct __Block_byref_ND {
5104/// void *__isa; // NULL for everything except __weak pointers
5105/// struct __Block_byref_ND *__forwarding;
5106/// int32_t __flags;
5107/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005108/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5109/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005110/// typex ND;
5111/// };
5112///
5113/// It then replaces declaration of ND variable with:
5114/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5115/// __size=sizeof(struct __Block_byref_ND),
5116/// ND=initializer-if-any};
5117///
5118///
5119void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005120 // Insert declaration for the function in which block literal is
5121 // used.
5122 if (CurFunctionDeclToDeclareForBlock)
5123 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005124 int flag = 0;
5125 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005126 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005127 if (DeclLoc.isInvalid())
5128 // If type location is missing, it is because of missing type (a warning).
5129 // Use variable's location which is good for this case.
5130 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005131 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005132 SourceLocation X = ND->getLocEnd();
5133 X = SM->getInstantiationLoc(X);
5134 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005135 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005136 std::string ByrefType;
5137 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005138 ByrefType += " {\n";
5139 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005140 RewriteByRefString(ByrefType, Name, ND);
5141 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005142 ByrefType += " int __flags;\n";
5143 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005144 // Add void *__Block_byref_id_object_copy;
5145 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005146 QualType Ty = ND->getType();
5147 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5148 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005149 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5150 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005151 }
5152
5153 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005154 ByrefType += " " + Name + ";\n";
5155 ByrefType += "};\n";
5156 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005157 SourceLocation FunLocStart;
5158 if (CurFunctionDef)
5159 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5160 else {
5161 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5162 FunLocStart = CurMethodDef->getLocStart();
5163 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005164 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005165 if (Ty.isObjCGCWeak()) {
5166 flag |= BLOCK_FIELD_IS_WEAK;
5167 isa = 1;
5168 }
5169
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005170 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005171 flag = BLOCK_BYREF_CALLER;
5172 QualType Ty = ND->getType();
5173 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5174 if (Ty->isBlockPointerType())
5175 flag |= BLOCK_FIELD_IS_BLOCK;
5176 else
5177 flag |= BLOCK_FIELD_IS_OBJECT;
5178 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005179 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005180 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005181 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005182
5183 // struct __Block_byref_ND ND =
5184 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5185 // initializer-if-any};
5186 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005187 unsigned flags = 0;
5188 if (HasCopyAndDispose)
5189 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005190 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005191 ByrefType.clear();
5192 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005193 std::string ForwardingCastType("(");
5194 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005195 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005196 ByrefType += " " + Name + " = {(void*)";
5197 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005198 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005199 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005200 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005201 ByrefType += "sizeof(";
5202 RewriteByRefString(ByrefType, Name, ND);
5203 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005204 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005205 ByrefType += ", __Block_byref_id_object_copy_";
5206 ByrefType += utostr(flag);
5207 ByrefType += ", __Block_byref_id_object_dispose_";
5208 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005209 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005210 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00005211 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005212 }
5213 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005214 SourceLocation startLoc;
5215 Expr *E = ND->getInit();
5216 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5217 startLoc = ECE->getLParenLoc();
5218 else
5219 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00005220 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005221 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005222 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005223 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005224 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005225 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005226 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005227 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005228 ByrefType += "sizeof(";
5229 RewriteByRefString(ByrefType, Name, ND);
5230 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005231 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005232 ByrefType += "__Block_byref_id_object_copy_";
5233 ByrefType += utostr(flag);
5234 ByrefType += ", __Block_byref_id_object_dispose_";
5235 ByrefType += utostr(flag);
5236 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005237 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005238 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005239
5240 // Complete the newly synthesized compound expression by inserting a right
5241 // curly brace before the end of the declaration.
5242 // FIXME: This approach avoids rewriting the initializer expression. It
5243 // also assumes there is only one declarator. For example, the following
5244 // isn't currently supported by this routine (in general):
5245 //
5246 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5247 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005248 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5249 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005250 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5251 SourceLocation semiLoc =
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005252 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005253
Benjamin Kramerd999b372010-02-14 14:14:16 +00005254 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005255 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005256 return;
5257}
5258
Mike Stump1eb44332009-09-09 15:08:12 +00005259void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005260 // Add initializers for any closure decl refs.
5261 GetBlockDeclRefExprs(Exp->getBody());
5262 if (BlockDeclRefs.size()) {
5263 // Unique all "by copy" declarations.
5264 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005265 if (!BlockDeclRefs[i]->isByRef()) {
5266 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5267 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5268 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5269 }
5270 }
Steve Naroff54055232008-10-27 17:20:55 +00005271 // Unique all "by ref" declarations.
5272 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5273 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005274 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5275 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5276 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5277 }
Steve Naroff54055232008-10-27 17:20:55 +00005278 }
5279 // Find any imported blocks...they will need special attention.
5280 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005281 if (BlockDeclRefs[i]->isByRef() ||
5282 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005283 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005284 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005285 }
5286}
5287
Daniel Dunbar4087f272010-08-17 22:39:59 +00005288FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005289 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005290 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00005291 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCalld931b082010-08-26 03:08:43 +00005292 ID, FType, 0, SC_Extern,
5293 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005294}
5295
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005296Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5297 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005298 Blocks.push_back(Exp);
5299
5300 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005301
5302 // Add inner imported variables now used in current block.
5303 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005304 if (!InnerBlockDeclRefs.empty()) {
5305 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5306 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5307 ValueDecl *VD = Exp->getDecl();
5308 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005309 // We need to save the copied-in variables in nested
5310 // blocks because it is needed at the end for some of the API generations.
5311 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005312 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5313 BlockDeclRefs.push_back(Exp);
5314 BlockByCopyDeclsPtrSet.insert(VD);
5315 BlockByCopyDecls.push_back(VD);
5316 }
5317 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5318 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5319 BlockDeclRefs.push_back(Exp);
5320 BlockByRefDeclsPtrSet.insert(VD);
5321 BlockByRefDecls.push_back(VD);
5322 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005323 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005324 // Find any imported blocks...they will need special attention.
5325 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5326 if (InnerBlockDeclRefs[i]->isByRef() ||
5327 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5328 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5329 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005330 }
5331 InnerDeclRefsCount.push_back(countOfInnerDecls);
5332
Steve Narofffa15fd92008-10-28 20:29:00 +00005333 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005334
Steve Narofffa15fd92008-10-28 20:29:00 +00005335 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005336 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005337 else if (CurMethodDef)
5338 BuildUniqueMethodName(FuncName, CurMethodDef);
5339 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005340 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005341
Steve Narofffa15fd92008-10-28 20:29:00 +00005342 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005343
Steve Narofffa15fd92008-10-28 20:29:00 +00005344 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5345 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005346
Steve Narofffa15fd92008-10-28 20:29:00 +00005347 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005348 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5349 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005350
5351 FunctionDecl *FD;
5352 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005353
Steve Narofffa15fd92008-10-28 20:29:00 +00005354 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005355 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005356 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5357 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005358
Steve Narofffa15fd92008-10-28 20:29:00 +00005359 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005360
Steve Narofffdc03722008-10-29 21:23:59 +00005361 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005362 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005363 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005364 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005365 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005366 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005367 InitExprs.push_back(castExpr);
5368
Steve Naroff01aec112009-12-06 21:14:13 +00005369 // Initialize the block descriptor.
5370 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005371
Steve Naroff01aec112009-12-06 21:14:13 +00005372 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5373 &Context->Idents.get(DescData.c_str()),
5374 Context->VoidPtrTy, 0,
John McCalld931b082010-08-26 03:08:43 +00005375 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005376 UnaryOperator *DescRefExpr =
5377 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5378 Context->VoidPtrTy,
5379 VK_LValue,
5380 SourceLocation()),
5381 UO_AddrOf,
5382 Context->getPointerType(Context->VoidPtrTy),
5383 VK_RValue, OK_Ordinary,
5384 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005385 InitExprs.push_back(DescRefExpr);
5386
Steve Narofffa15fd92008-10-28 20:29:00 +00005387 // Add initializers for any closure decl refs.
5388 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005389 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005390 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005391 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005392 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005393 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005394 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005395 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005396 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5397 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005398 if (HasLocalVariableExternalStorage(*I)) {
5399 QualType QT = (*I)->getType();
5400 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005401 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5402 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005403 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005404 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005405 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005406 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5407 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005408 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005409 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005410 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005411 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005412 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5413 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005414 if (HasLocalVariableExternalStorage(*I)) {
5415 QualType QT = (*I)->getType();
5416 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005417 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5418 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005419 }
5420
Steve Narofffa15fd92008-10-28 20:29:00 +00005421 }
Mike Stump1eb44332009-09-09 15:08:12 +00005422 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005423 }
5424 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005425 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005426 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005427 ValueDecl *ND = (*I);
5428 std::string Name(ND->getNameAsString());
5429 std::string RecName;
5430 RewriteByRefString(RecName, Name, ND);
5431 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5432 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005433 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005434 SourceLocation(), II);
5435 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5436 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5437
Daniel Dunbar4087f272010-08-17 22:39:59 +00005438 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005439 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5440 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005441 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005442 Context->getPointerType(Exp->getType()),
5443 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005444 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005445 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005446 }
5447 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005448 if (ImportedBlockDecls.size()) {
5449 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5450 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005451 unsigned IntSize =
5452 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005453 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5454 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005455 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005456 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005457 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005458 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005459 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005460 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005461 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005462 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005463 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005464 BlockDeclRefs.clear();
5465 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005466 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005467 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005468 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005469 ImportedBlockDecls.clear();
5470 return NewRep;
5471}
5472
5473//===----------------------------------------------------------------------===//
5474// Function Body / Expression rewriting
5475//===----------------------------------------------------------------------===//
5476
Steve Naroffc77a6362008-12-04 16:24:46 +00005477// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5478// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5479// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5480// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5481// Since the rewriter isn't capable of rewriting rewritten code, it's important
5482// we get this right.
5483void RewriteObjC::CollectPropertySetters(Stmt *S) {
5484 // Perform a bottom up traversal of all children.
5485 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5486 CI != E; ++CI)
5487 if (*CI)
5488 CollectPropertySetters(*CI);
5489
5490 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5491 if (BinOp->isAssignmentOp()) {
John McCall12f78a62010-12-02 01:19:52 +00005492 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5493 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005494 }
5495 }
5496}
5497
Steve Narofffa15fd92008-10-28 20:29:00 +00005498Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005499 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005500 isa<DoStmt>(S) || isa<ForStmt>(S))
5501 Stmts.push_back(S);
5502 else if (isa<ObjCForCollectionStmt>(S)) {
5503 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005504 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005505 }
Mike Stump1eb44332009-09-09 15:08:12 +00005506
Steve Narofffa15fd92008-10-28 20:29:00 +00005507 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005508
Steve Narofffa15fd92008-10-28 20:29:00 +00005509 // Perform a bottom up rewrite of all children.
5510 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5511 CI != E; ++CI)
5512 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005513 Stmt *newStmt;
5514 Stmt *S = (*CI);
5515 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5516 Expr *OldBase = IvarRefExpr->getBase();
5517 bool replaced = false;
5518 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5519 if (replaced) {
5520 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5521 ReplaceStmt(OldBase, IRE->getBase());
5522 else
5523 ReplaceStmt(S, newStmt);
5524 }
5525 }
5526 else
5527 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005528 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005529 *CI = newStmt;
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005530 // If dealing with an assignment with LHS being a property reference
5531 // expression, the entire assignment tree is rewritten into a property
5532 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5533 // RHS again.
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005534 if (Expr *Exp = dyn_cast<Expr>(S))
John McCall12f78a62010-12-02 01:19:52 +00005535 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005536 if (PropSetters[Exp]) {
5537 ++CI;
5538 continue;
5539 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005540 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005541 }
Mike Stump1eb44332009-09-09 15:08:12 +00005542
Steve Narofffa15fd92008-10-28 20:29:00 +00005543 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005544 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005545 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5546 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005547 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005548 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005549 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005550 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005551 Stmt *SaveCurrentBody = CurrentBody;
5552 CurrentBody = BE->getBody();
5553 PropParentMap = 0;
Steve Narofffa15fd92008-10-28 20:29:00 +00005554 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005555 CurrentBody = SaveCurrentBody;
5556 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005557 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005558 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005559 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005560 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005561
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005562 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5563
Steve Narofffa15fd92008-10-28 20:29:00 +00005564 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005565 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005566 return blockTranscribed;
5567 }
5568 // Handle specific things.
5569 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5570 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005571
John McCall12f78a62010-12-02 01:19:52 +00005572 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005573 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5574 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5575
5576 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005577 if (BinOp) {
5578 // Because the rewriter doesn't allow us to rewrite rewritten code,
5579 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005580 DisableReplaceStmt = true;
5581 // Save the source range. Even if we disable the replacement, the
5582 // rewritten node will have been inserted into the tree. If the synthesized
5583 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005584 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005585 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5586 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005587 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005588 // Need to rewrite the ivar access expression if need be.
5589 if (isa<ObjCIvarRefExpr>(newStmt)) {
5590 bool replaced = false;
5591 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5592 }
5593
Steve Naroffb619d952008-12-09 12:56:34 +00005594 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005595 //
5596 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5597 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5598 // to see the original expression). Consider this example:
5599 //
5600 // Foo *obj1, *obj2;
5601 //
5602 // obj1.i = [obj2 rrrr];
5603 //
5604 // 'BinOp' for the previous expression looks like:
5605 //
5606 // (BinaryOperator 0x231ccf0 'int' '='
5607 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5608 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5609 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5610 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5611 //
5612 // 'newStmt' represents the rewritten message expression. For example:
5613 //
5614 // (CallExpr 0x231d300 'id':'struct objc_object *'
5615 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5616 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5617 // (CStyleCastExpr 0x231d220 'void *'
5618 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5619 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005620 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005621 // can be used as the setter argument. ReplaceStmt() will still 'see'
5622 // the original RHS (since we haven't altered BinOp).
5623 //
Mike Stump1eb44332009-09-09 15:08:12 +00005624 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005625 // node. As a result, we now leak the original AST nodes.
5626 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005627 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005628 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005629 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005630 }
5631 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005632
Steve Narofffa15fd92008-10-28 20:29:00 +00005633 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5634 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005635
Steve Narofffa15fd92008-10-28 20:29:00 +00005636 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5637 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005638
Steve Narofffa15fd92008-10-28 20:29:00 +00005639 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005640#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005641 // Before we rewrite it, put the original message expression in a comment.
5642 SourceLocation startLoc = MessExpr->getLocStart();
5643 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005644
Steve Narofffa15fd92008-10-28 20:29:00 +00005645 const char *startBuf = SM->getCharacterData(startLoc);
5646 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005647
Steve Narofffa15fd92008-10-28 20:29:00 +00005648 std::string messString;
5649 messString += "// ";
5650 messString.append(startBuf, endBuf-startBuf+1);
5651 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005652
5653 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005654 // InsertText(clang::SourceLocation, char const*, unsigned int).
5655 // InsertText(startLoc, messString.c_str(), messString.size());
5656 // Tried this, but it didn't work either...
5657 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005658#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005659 return RewriteMessageExpr(MessExpr);
5660 }
Mike Stump1eb44332009-09-09 15:08:12 +00005661
Steve Narofffa15fd92008-10-28 20:29:00 +00005662 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5663 return RewriteObjCTryStmt(StmtTry);
5664
5665 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5666 return RewriteObjCSynchronizedStmt(StmtTry);
5667
5668 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5669 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005670
Steve Narofffa15fd92008-10-28 20:29:00 +00005671 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5672 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005673
5674 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005675 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005676 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005677 OrigStmtRange.getEnd());
5678 if (BreakStmt *StmtBreakStmt =
5679 dyn_cast<BreakStmt>(S))
5680 return RewriteBreakStmt(StmtBreakStmt);
5681 if (ContinueStmt *StmtContinueStmt =
5682 dyn_cast<ContinueStmt>(S))
5683 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005684
5685 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005686 // and cast exprs.
5687 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5688 // FIXME: What we're doing here is modifying the type-specifier that
5689 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005690 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005691 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5692 // the context of an ObjCForCollectionStmt. For example:
5693 // NSArray *someArray;
5694 // for (id <FooProtocol> index in someArray) ;
5695 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5696 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005697 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005698 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005699
Steve Narofffa15fd92008-10-28 20:29:00 +00005700 // Blocks rewrite rules.
5701 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5702 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005703 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005704 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005705 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005706 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005707 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005708 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005709 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005710 if (VD->hasAttr<BlocksAttr>()) {
5711 static unsigned uniqueByrefDeclCount = 0;
5712 assert(!BlockByRefDeclNo.count(ND) &&
5713 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5714 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005715 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005716 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005717 else
5718 RewriteTypeOfDecl(VD);
5719 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005720 }
5721 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005722 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005723 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005724 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005725 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5726 }
5727 }
5728 }
Mike Stump1eb44332009-09-09 15:08:12 +00005729
Steve Narofffa15fd92008-10-28 20:29:00 +00005730 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5731 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005732
5733 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005734 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5735 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005736 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5737 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005738 && "Statement stack mismatch");
5739 Stmts.pop_back();
5740 }
5741 // Handle blocks rewriting.
5742 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5743 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005744 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005745 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005746 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5747 ValueDecl *VD = DRE->getDecl();
5748 if (VD->hasAttr<BlocksAttr>())
5749 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005750 if (HasLocalVariableExternalStorage(VD))
5751 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005752 }
5753
Steve Narofffa15fd92008-10-28 20:29:00 +00005754 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005755 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005756 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005757 ReplaceStmt(S, BlockCall);
5758 return BlockCall;
5759 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005760 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005761 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005762 RewriteCastExpr(CE);
5763 }
5764#if 0
5765 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005766 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5767 ICE->getSubExpr(),
5768 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005769 // Get the new text.
5770 std::string SStr;
5771 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005772 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005773 const std::string &Str = Buf.str();
5774
5775 printf("CAST = %s\n", &Str[0]);
5776 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5777 delete S;
5778 return Replacement;
5779 }
5780#endif
5781 // Return this stmt unmodified.
5782 return S;
5783}
5784
Steve Naroff3d7e7862009-12-05 15:55:59 +00005785void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5786 for (RecordDecl::field_iterator i = RD->field_begin(),
5787 e = RD->field_end(); i != e; ++i) {
5788 FieldDecl *FD = *i;
5789 if (isTopLevelBlockPointerType(FD->getType()))
5790 RewriteBlockPointerDecl(FD);
5791 if (FD->getType()->isObjCQualifiedIdType() ||
5792 FD->getType()->isObjCQualifiedInterfaceType())
5793 RewriteObjCQualifiedInterfaceTypes(FD);
5794 }
5795}
5796
Steve Narofffa15fd92008-10-28 20:29:00 +00005797/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5798/// main file of the input.
5799void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5800 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005801 if (FD->isOverloadedOperator())
5802 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005803
Steve Narofffa15fd92008-10-28 20:29:00 +00005804 // Since function prototypes don't have ParmDecl's, we check the function
5805 // prototype. This enables us to rewrite function declarations and
5806 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005807 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005808
Sebastian Redld3a413d2009-04-26 20:35:05 +00005809 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005810 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005811 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005812 CurFunctionDeclToDeclareForBlock = FD;
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 FD->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 // This synthesizes and inserts the block "impl" struct, invoke function,
5824 // and any copy/dispose helper functions.
5825 InsertBlockLiteralsWithinFunction(FD);
5826 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005827 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005828 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005829 return;
5830 }
5831 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005832 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005833 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005834 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005835 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005836 Body =
5837 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5838 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005839 CurrentBody = 0;
5840 if (PropParentMap) {
5841 delete PropParentMap;
5842 PropParentMap = 0;
5843 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005844 InsertBlockLiteralsWithinMethod(MD);
5845 CurMethodDef = 0;
5846 }
5847 }
5848 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5849 ClassImplementation.push_back(CI);
5850 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5851 CategoryImplementation.push_back(CI);
5852 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5853 RewriteForwardClassDecl(CD);
5854 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5855 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005856 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005857 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005858 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005859 CheckFunctionPointerDecl(VD->getType(), VD);
5860 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005861 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005862 RewriteCastExpr(CE);
5863 }
5864 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005865 } else if (VD->getType()->isRecordType()) {
5866 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5867 if (RD->isDefinition())
5868 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005869 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005870 if (VD->getInit()) {
5871 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005872 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005873 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005874 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005875 CurrentBody = 0;
5876 if (PropParentMap) {
5877 delete PropParentMap;
5878 PropParentMap = 0;
5879 }
Mike Stump1eb44332009-09-09 15:08:12 +00005880 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005881 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005882 GlobalVarDecl = 0;
5883
5884 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005885 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005886 RewriteCastExpr(CE);
5887 }
5888 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005889 return;
5890 }
5891 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005892 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005893 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005894 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005895 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5896 return;
5897 }
5898 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005899 if (RD->isDefinition())
5900 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005901 return;
5902 }
5903 // Nothing yet.
5904}
5905
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005906void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005907 if (Diags.hasErrorOccurred())
5908 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005909
Steve Narofffa15fd92008-10-28 20:29:00 +00005910 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005911
Steve Naroff621edce2009-04-29 16:37:50 +00005912 // Here's a great place to add any extra declarations that may be needed.
5913 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005914 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005915 E = ProtocolExprDecls.end(); I != E; ++I)
5916 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5917
Benjamin Kramerd999b372010-02-14 14:14:16 +00005918 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005919 if (ClassImplementation.size() || CategoryImplementation.size())
5920 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005921
Steve Narofffa15fd92008-10-28 20:29:00 +00005922 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5923 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005924 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005925 Rewrite.getRewriteBufferFor(MainFileID)) {
5926 //printf("Changed:\n");
5927 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5928 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005929 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005930 }
Steve Narofface66252008-11-13 20:07:04 +00005931
Steve Naroff621edce2009-04-29 16:37:50 +00005932 if (ClassImplementation.size() || CategoryImplementation.size() ||
5933 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005934 // Rewrite Objective-c meta data*
5935 std::string ResultStr;
5936 SynthesizeMetaDataIntoBuffer(ResultStr);
5937 // Emit metadata.
5938 *OutFile << ResultStr;
5939 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005940 OutFile->flush();
5941}