blob: 57d1210f31b7e036138633a2154e17553707ec57 [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;
David Blaikied6471f72011-09-25 23:23:43 +000058 DiagnosticsEngine &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattner01c57482007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner5f9e2722011-07-23 10:55:15 +000070 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000072 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +000076 SmallVector<Stmt *, 32> Stmts;
77 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffd82a9ab2008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000084
Steve Naroffebf2b562007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Fariborz Jahanianb586cce2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Steve Naroff874e2322007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Steve Naroff621edce2009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Steve Naroffa7b402d2008-03-28 22:26:09 +0000115 std::string InFileName;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000116 raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000120
Steve Naroffba92b2e2008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000122
123 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000124 SmallVector<BlockExpr *, 32> Blocks;
125 SmallVector<int, 32> InnerDeclRefsCount;
126 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000127
Chris Lattner5f9e2722011-07-23 10:55:15 +0000128 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Steve Naroff54055232008-10-27 17:20:55 +0000130 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000131 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000133 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff54055232008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroffc77a6362008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000142 llvm::DenseMap<Expr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000145 llvm::DenseMap<Expr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Steve Naroff4c3580e2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000151
Steve Naroff54055232008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Steve Naroffb619d952008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Nick Lewycky7e749242010-10-31 21:07:24 +0000158 static const int OBJC_ABI_VERSION = 7;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000159 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattnerf04da132007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
165 if (isa<ObjCClassDecl>((*I))) {
166 RewriteForwardClassDecl(D);
167 break;
168 }
Chris Lattner682bf922009-03-29 16:50:03 +0000169 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000170 }
Chris Lattner682bf922009-03-29 16:50:03 +0000171 }
172 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000173 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000174 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000175 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000176 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000177
178 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000180 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000182 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000183 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Steve Naroff4c3580e2008-12-04 23:50:32 +0000185 if (ReplacingStmt)
186 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000187
Steve Naroffb619d952008-12-09 12:56:34 +0000188 if (DisableReplaceStmt)
189 return; // Used when rewriting the assignment of a property setter.
190
Steve Naroff4c3580e2008-12-04 23:50:32 +0000191 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000192 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000193 ReplacedNodes[Old] = New;
194 return;
195 }
196 if (SilenceRewriteMacroWarning)
197 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000198 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
199 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000200 }
Steve Naroffb619d952008-12-09 12:56:34 +0000201
202 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Nick Lewycky7e749242010-10-31 21:07:24 +0000203 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000204 int Size = Rewrite.getRangeSize(SrcRange);
205 if (Size == -1) {
206 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
207 << Old->getSourceRange();
208 return;
209 }
210 // Get the new text.
211 std::string SStr;
212 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000213 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000214 const std::string &Str = S.str();
215
216 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000217 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000218 ReplacedNodes[Old] = New;
219 return;
220 }
221 if (SilenceRewriteMacroWarning)
222 return;
223 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
224 << Old->getSourceRange();
225 }
226
Chris Lattner5f9e2722011-07-23 10:55:15 +0000227 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000228 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000229 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000230 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000231 SilenceRewriteMacroWarning)
232 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000234 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
235 }
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Chris Lattneraadaf782008-01-31 19:51:04 +0000237 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000238 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000240 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000241 SilenceRewriteMacroWarning)
242 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Chris Lattneraadaf782008-01-31 19:51:04 +0000244 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
245 }
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattnerf04da132007-10-24 17:06:59 +0000247 // Syntactic Rewriting.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000248 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000249 void RewriteForwardClassDecl(DeclGroupRef D);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000250 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
251 void RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
252 const std::string &typedefString);
253
Steve Naroffa0876e82008-12-02 17:36:43 +0000254 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
255 ObjCImplementationDecl *IMD,
256 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000257 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000258 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000259 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
260 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000261 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
262 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000263 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000264 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
266 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
267 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
268 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000269 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000270 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000271 void RewriteBlockPointerType(std::string& Str, QualType Type);
272 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000273 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000274 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000275 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000276 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000277 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000278 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000279 QualType getConstantStringStructType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +0000280 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffbaf58c32008-05-31 14:15:04 +0000281 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Chris Lattnerf04da132007-10-24 17:06:59 +0000283 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000284 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000285 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Steve Naroff8599e7a2008-12-08 16:43:47 +0000287 Stmt *CurrentBody;
288 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Chris Lattnere64b7772007-10-24 16:57:36 +0000290 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000291 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
292 bool &replaced);
293 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000294 Stmt *RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr);
295 Stmt *RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000296 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000297 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000298 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000299 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000300 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000301 void WarnAboutReturnGotoStmts(Stmt *S);
302 void HasReturnStmts(Stmt *S, bool &hasReturns);
303 void RewriteTryReturnStmts(Stmt *S);
304 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000306 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000307 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000308 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
309 SourceLocation OrigEnd);
Fariborz Jahanian42f1e652011-02-24 21:29:21 +0000310 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Mike Stump1eb44332009-09-09 15:08:12 +0000311 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000312 Expr **args, unsigned nargs,
313 SourceLocation StartLoc=SourceLocation(),
314 SourceLocation EndLoc=SourceLocation());
315 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
316 SourceLocation StartLoc=SourceLocation(),
317 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000318 Stmt *RewriteBreakStmt(BreakStmt *S);
319 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000320 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Steve Naroff09b266e2007-10-30 23:14:51 +0000322 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000323 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000324 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000325 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000326 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000327 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000328 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000329 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000330 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000331 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chris Lattnerf04da132007-10-24 17:06:59 +0000333 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000334 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000335 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000337 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000338 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Douglas Gregor653f1b12009-04-23 01:02:12 +0000340 template<typename MethodIterator>
341 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
342 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000343 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000344 StringRef prefix,
345 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +0000346 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Steve Naroff621edce2009-04-29 16:37:50 +0000348 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000349 StringRef prefix,
350 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000351 std::string &Result);
352 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000353 StringRef prefix,
354 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000355 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000356 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000357 std::string &Result);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000358 void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000359 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000360 void RewriteImplementations();
361 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Steve Naroff54055232008-10-27 17:20:55 +0000363 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000364 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000365 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Steve Naroff54055232008-10-27 17:20:55 +0000367 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
368 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000369
370 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000371 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000372 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000373 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000374 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000375 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000376 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000377
378 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000379 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000380 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000381 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000382 std::string SynthesizeBlockImpl(BlockExpr *CE,
383 std::string Tag, std::string Desc);
384 std::string SynthesizeBlockDescriptor(std::string DescTag,
385 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000386 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000387 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000388 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000389 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000390 StringRef FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000391 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Steve Naroff54055232008-10-27 17:20:55 +0000393 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000394 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000395 void GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000396 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000397 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Steve Naroff54055232008-10-27 17:20:55 +0000399 // We avoid calling Type::isBlockPointerType(), since it operates on the
400 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000401 bool isTopLevelBlockPointerType(QualType T) {
402 return isa<BlockPointerType>(T);
403 }
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000405 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
406 /// to a function pointer type and upon success, returns true; false
407 /// otherwise.
408 bool convertBlockPointerToFunctionPointer(QualType &T) {
409 if (isTopLevelBlockPointerType(T)) {
410 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
411 T = Context->getPointerType(BPT->getPointeeType());
412 return true;
413 }
414 return false;
415 }
416
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000417 void convertToUnqualifiedObjCType(QualType &T) {
418 if (T->isObjCQualifiedIdType())
419 T = Context->getObjCIdType();
420 else if (T->isObjCQualifiedClassType())
421 T = Context->getObjCClassType();
422 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000423 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
424 if (const ObjCObjectPointerType * OBJPT =
425 T->getAsObjCInterfacePointerType()) {
426 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
427 T = QualType(IFaceT, 0);
428 T = Context->getPointerType(T);
429 }
430 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000431 }
432
Steve Naroff54055232008-10-27 17:20:55 +0000433 // FIXME: This predicate seems like it would be useful to add to ASTContext.
434 bool isObjCType(QualType T) {
435 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
436 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Steve Naroff54055232008-10-27 17:20:55 +0000438 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Steve Naroff54055232008-10-27 17:20:55 +0000440 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
441 OCT == Context->getCanonicalType(Context->getObjCClassType()))
442 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Ted Kremenek6217b802009-07-29 21:53:49 +0000444 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000445 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000446 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000447 return true;
448 }
449 return false;
450 }
451 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000452 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000453 void GetExtentOfArgList(const char *Name, const char *&LParen,
454 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000455 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Chris Lattner5f9e2722011-07-23 10:55:15 +0000457 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000458 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000459 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Steve Naroff621edce2009-04-29 16:37:50 +0000461 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000462 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000463 if (From[i] == '"')
464 To += "\\\"";
465 else
466 To += From[i];
467 }
468 }
John McCalle23cf432010-12-14 08:05:40 +0000469
470 QualType getSimpleFunctionType(QualType result,
471 const QualType *args,
472 unsigned numArgs,
473 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000474 if (result == Context->getObjCInstanceType())
475 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000476 FunctionProtoType::ExtProtoInfo fpi;
477 fpi.Variadic = variadic;
478 return Context->getFunctionType(result, args, numArgs, fpi);
479 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000480 };
John McCall9d125032010-01-15 18:39:57 +0000481
482 // Helper function: create a CStyleCastExpr with trivial type source info.
483 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000484 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000485 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +0000486 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallf871d0c2010-08-07 06:22:56 +0000487 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000488 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000489}
490
Mike Stump1eb44332009-09-09 15:08:12 +0000491void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
492 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000493 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000494 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000495 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000496 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000497 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000498 // All the args are checked/rewritten. Don't call twice!
499 RewriteBlockPointerDecl(D);
500 break;
501 }
502 }
503}
504
505void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000506 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000507 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000508 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000509}
510
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000511static bool IsHeaderFile(const std::string &Filename) {
512 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000514 if (DotPos == std::string::npos) {
515 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000516 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000517 }
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000519 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
520 // C header: .h
521 // C++ header: .hh or .H;
522 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000523}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000524
Chris Lattner5f9e2722011-07-23 10:55:15 +0000525RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000526 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000527 bool silenceMacroWarn)
528 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
529 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000530 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000531 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000532 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000533 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
534 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000535 "rewriter doesn't support user-specified control flow semantics "
536 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000537}
538
Eli Friedmanbce831b2009-05-18 22:29:17 +0000539ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000540 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000541 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000542 const LangOptions &LOpts,
543 bool SilenceRewriteMacroWarning) {
544 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000545}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000546
Steve Naroffb29b4272008-04-14 22:03:09 +0000547void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000548 Context = &context;
549 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000550 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000551 MsgSendFunctionDecl = 0;
552 MsgSendSuperFunctionDecl = 0;
553 MsgSendStretFunctionDecl = 0;
554 MsgSendSuperStretFunctionDecl = 0;
555 MsgSendFpretFunctionDecl = 0;
556 GetClassFunctionDecl = 0;
557 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000558 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000559 SelGetUidFunctionDecl = 0;
560 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000561 ConstantStringClassReference = 0;
562 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000563 CurMethodDef = 0;
564 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000565 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000566 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000567 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000568 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000569 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000570 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000571 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000572 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000573 PropParentMap = 0;
574 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000575 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000576 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000578 // Get the ID and start/end of the main file.
579 MainFileID = SM->getMainFileID();
580 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
581 MainFileStart = MainBuf->getBufferStart();
582 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Chris Lattner2c78b872009-04-14 23:22:57 +0000584 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000586 // declaring objc_selector outside the parameter list removes a silly
587 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000588 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000589 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000590 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000591 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000592 Preamble += "struct objc_object *superClass; ";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000593 if (LangOpts.MicrosoftExt) {
Steve Naroffc0a123c2008-03-11 17:37:02 +0000594 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000595 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
596 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000597 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000598 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000599 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000600 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
601 Preamble += "typedef struct objc_object Protocol;\n";
602 Preamble += "#define _REWRITER_typedef_Protocol\n";
603 Preamble += "#endif\n";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000604 if (LangOpts.MicrosoftExt) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000605 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
606 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
607 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000608 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000609 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000610 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000611 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000612 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000613 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000614 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000615 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000616 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000617 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000618 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000619 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000620 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000621 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
622 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000623 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000624 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000625 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
626 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
627 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
628 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
629 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000630 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000631 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000632 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
633 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
634 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000635 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
636 Preamble += "struct __objcFastEnumerationState {\n\t";
637 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000638 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000639 Preamble += "unsigned long *mutationsPtr;\n\t";
640 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000641 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000642 Preamble += "#define __FASTENUMERATIONSTATE\n";
643 Preamble += "#endif\n";
644 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
645 Preamble += "struct __NSConstantStringImpl {\n";
646 Preamble += " int *isa;\n";
647 Preamble += " int flags;\n";
648 Preamble += " char *str;\n";
649 Preamble += " long length;\n";
650 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000651 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
652 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
653 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000654 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000655 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000656 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
657 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000658 // Blocks preamble.
659 Preamble += "#ifndef BLOCK_IMPL\n";
660 Preamble += "#define BLOCK_IMPL\n";
661 Preamble += "struct __block_impl {\n";
662 Preamble += " void *isa;\n";
663 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000664 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000665 Preamble += " void *FuncPtr;\n";
666 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000667 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000668 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000669 Preamble += "extern \"C\" __declspec(dllexport) "
670 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000671 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
672 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
673 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
674 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000675 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
676 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000677 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
678 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
679 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000680 Preamble += "#endif\n";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000681 if (LangOpts.MicrosoftExt) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000682 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
683 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000684 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000685 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000686 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000687 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000688 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000689 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000690 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000691 Preamble += "#define __weak\n";
692 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000693 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
694 // as this avoids warning in any 64bit/32bit compilation model.
695 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000696}
697
698
Chris Lattnerf04da132007-10-24 17:06:59 +0000699//===----------------------------------------------------------------------===//
700// Top Level Driver Code
701//===----------------------------------------------------------------------===//
702
Chris Lattner682bf922009-03-29 16:50:03 +0000703void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000704 if (Diags.hasErrorOccurred())
705 return;
706
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000707 // Two cases: either the decl could be in the main file, or it could be in a
708 // #included file. If the former, rewrite it now. If the later, check to see
709 // if we rewrote the #include/#import.
710 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000711 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000713 // If this is for a builtin, ignore it.
714 if (Loc.isInvalid()) return;
715
Steve Naroffebf2b562007-10-23 23:50:29 +0000716 // Look for built-in declarations that we need to refer during the rewrite.
717 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000718 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000719 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000720 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000721 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000722 ConstantStringClassReference = FVD;
723 return;
724 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000725 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000726 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000727 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000728 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000729 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000730 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000731 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000732 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000733 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000734 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
735 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000736 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
737 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000738 DI != DIEnd; ) {
739 if (isa<ObjCClassDecl>((*DI))) {
740 SmallVector<Decl *, 8> DG;
741 Decl *D = (*DI);
742 SourceLocation Loc = D->getLocation();
743 while (DI != DIEnd &&
744 isa<ObjCClassDecl>(D) && D->getLocation() == Loc) {
745 DG.push_back(D);
746 ++DI;
747 D = (*DI);
748 }
749 RewriteForwardClassDecl(DG);
750 continue;
751 }
Chris Lattner682bf922009-03-29 16:50:03 +0000752 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000753 ++DI;
754 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000755 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000756 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000757 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000758 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000759}
760
Chris Lattnerf04da132007-10-24 17:06:59 +0000761//===----------------------------------------------------------------------===//
762// Syntactic (non-AST) Rewriting Code
763//===----------------------------------------------------------------------===//
764
Steve Naroffb29b4272008-04-14 22:03:09 +0000765void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000766 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000767 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000768 const char *MainBufStart = MainBuf.begin();
769 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000770 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000772 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000773 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
774 if (*BufPtr == '#') {
775 if (++BufPtr == MainBufEnd)
776 return;
777 while (*BufPtr == ' ' || *BufPtr == '\t')
778 if (++BufPtr == MainBufEnd)
779 return;
780 if (!strncmp(BufPtr, "import", ImportLen)) {
781 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000782 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000783 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000784 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000785 BufPtr += ImportLen;
786 }
787 }
788 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000789}
790
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000791static std::string getIvarAccessString(ObjCIvarDecl *OID) {
792 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000793 std::string S;
794 S = "((struct ";
795 S += ClassDecl->getIdentifier()->getName();
796 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000797 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000798 return S;
799}
800
Steve Naroffa0876e82008-12-02 17:36:43 +0000801void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
802 ObjCImplementationDecl *IMD,
803 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000804 static bool objcGetPropertyDefined = false;
805 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000806 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000807 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000808 const char *startBuf = SM->getCharacterData(startLoc);
809 assert((*startBuf == '@') && "bogus @synthesize location");
810 const char *semiBuf = strchr(startBuf, ';');
811 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000812 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000813 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000814
815 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
816 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Steve Naroffeb0646c2008-12-02 15:48:25 +0000818 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000819 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000820 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000822 if (!OID)
823 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000824 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000825 if (!PD->getGetterMethodDecl()->isDefined()) {
826 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
827 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
828 ObjCPropertyDecl::OBJC_PR_copy));
829 std::string Getr;
830 if (GenGetProperty && !objcGetPropertyDefined) {
831 objcGetPropertyDefined = true;
832 // FIXME. Is this attribute correct in all cases?
833 Getr = "\nextern \"C\" __declspec(dllimport) "
834 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000835 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000836 RewriteObjCMethodDecl(OID->getContainingInterface(),
837 PD->getGetterMethodDecl(), Getr);
838 Getr += "{ ";
839 // Synthesize an explicit cast to gain access to the ivar.
840 // See objc-act.c:objc_synthesize_new_getter() for details.
841 if (GenGetProperty) {
842 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
843 Getr += "typedef ";
844 const FunctionType *FPRetType = 0;
845 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
846 FPRetType);
847 Getr += " _TYPE";
848 if (FPRetType) {
849 Getr += ")"; // close the precedence "scope" for "*".
850
851 // Now, emit the argument types (if any).
852 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
853 Getr += "(";
854 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
855 if (i) Getr += ", ";
856 std::string ParamStr = FT->getArgType(i).getAsString(
857 Context->PrintingPolicy);
858 Getr += ParamStr;
859 }
860 if (FT->isVariadic()) {
861 if (FT->getNumArgs()) Getr += ", ";
862 Getr += "...";
863 }
864 Getr += ")";
865 } else
866 Getr += "()";
867 }
868 Getr += ";\n";
869 Getr += "return (_TYPE)";
870 Getr += "objc_getProperty(self, _cmd, ";
871 SynthesizeIvarOffsetComputation(OID, Getr);
872 Getr += ", 1)";
873 }
874 else
875 Getr += "return " + getIvarAccessString(OID);
876 Getr += "; }";
877 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000878 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000879
880 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000881 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Steve Naroffeb0646c2008-12-02 15:48:25 +0000883 // Generate the 'setter' function.
884 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000885 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
886 ObjCPropertyDecl::OBJC_PR_copy);
887 if (GenSetProperty && !objcSetPropertyDefined) {
888 objcSetPropertyDefined = true;
889 // FIXME. Is this attribute correct in all cases?
890 Setr = "\nextern \"C\" __declspec(dllimport) "
891 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
892 }
893
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000894 RewriteObjCMethodDecl(OID->getContainingInterface(),
895 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000896 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000897 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000898 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000899 if (GenSetProperty) {
900 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000901 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000902 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000903 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000904 Setr += ", ";
905 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
906 Setr += "0, ";
907 else
908 Setr += "1, ";
909 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
910 Setr += "1)";
911 else
912 Setr += "0)";
913 }
914 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000915 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000916 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000917 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000918 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000919 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000920}
Chris Lattner8a12c272007-10-11 18:38:32 +0000921
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000922static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
923 std::string &typedefString) {
924 typedefString += "#ifndef _REWRITER_typedef_";
925 typedefString += ForwardDecl->getNameAsString();
926 typedefString += "\n";
927 typedefString += "#define _REWRITER_typedef_";
928 typedefString += ForwardDecl->getNameAsString();
929 typedefString += "\n";
930 typedefString += "typedef struct objc_object ";
931 typedefString += ForwardDecl->getNameAsString();
932 typedefString += ";\n#endif\n";
933}
934
935void RewriteObjC::RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
936 const std::string &typedefString) {
937 SourceLocation startLoc = ClassDecl->getLocation();
938 const char *startBuf = SM->getCharacterData(startLoc);
939 const char *semiPtr = strchr(startBuf, ';');
940 // Replace the @class with typedefs corresponding to the classes.
941 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
942}
943
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000944void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000945 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000946 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
947 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(*I);
948 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
949 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000950 // Translate to typedef's that forward reference structs with the same name
951 // as the class. As a convenience, we include the original declaration
952 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000953 typedefString += "// @class ";
954 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000955 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000956 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000957 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000958 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000959 DeclGroupRef::iterator I = D.begin();
960 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(*I), typedefString);
961}
Mike Stump1eb44332009-09-09 15:08:12 +0000962
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000963void RewriteObjC::RewriteForwardClassDecl(
964 const llvm::SmallVector<Decl*, 8> &D) {
965 std::string typedefString;
966 for (unsigned i = 0; i < D.size(); i++) {
967 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(D[i]);
968 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
969 if (i == 0) {
970 typedefString += "// @class ";
971 typedefString += ForwardDecl->getNameAsString();
972 typedefString += ";\n";
973 }
974 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
975 }
976 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000977}
978
Steve Naroffb29b4272008-04-14 22:03:09 +0000979void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000980 // When method is a synthesized one, such as a getter/setter there is
981 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000982 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000983 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000984 SourceLocation LocStart = Method->getLocStart();
985 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Chandler Carruth64211622011-07-25 21:09:52 +0000987 if (SM->getExpansionLineNumber(LocEnd) >
988 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000989 InsertText(LocStart, "#if 0\n");
990 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000991 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000992 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000993 }
994}
995
Mike Stump1eb44332009-09-09 15:08:12 +0000996void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000997 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Benjamin Kramerd999b372010-02-14 14:14:16 +0000999 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +00001000 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001001}
1002
Steve Naroffb29b4272008-04-14 22:03:09 +00001003void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +00001004 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Steve Naroff423cb562007-10-30 13:30:57 +00001006 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001007 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Fariborz Jahanian13751e32010-02-10 01:15:09 +00001009 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1010 E = CatDecl->prop_end(); I != E; ++I)
1011 RewriteProperty(*I);
1012
Mike Stump1eb44332009-09-09 15:08:12 +00001013 for (ObjCCategoryDecl::instmeth_iterator
1014 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001015 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001016 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001017 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001018 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001019 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001020 RewriteMethodDeclaration(*I);
1021
Steve Naroff423cb562007-10-30 13:30:57 +00001022 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001023 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1024 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +00001025}
1026
Steve Naroffb29b4272008-04-14 22:03:09 +00001027void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +00001028 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Steve Naroff752d6ef2007-10-30 16:42:30 +00001030 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001031 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001032
1033 for (ObjCProtocolDecl::instmeth_iterator
1034 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001035 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001036 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001037 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001038 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001039 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001040 RewriteMethodDeclaration(*I);
1041
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001042 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1043 E = PDecl->prop_end(); I != E; ++I)
1044 RewriteProperty(*I);
1045
Steve Naroff752d6ef2007-10-30 16:42:30 +00001046 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001047 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001048 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001049
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001050 // Must comment out @optional/@required
1051 const char *startBuf = SM->getCharacterData(LocStart);
1052 const char *endBuf = SM->getCharacterData(LocEnd);
1053 for (const char *p = startBuf; p < endBuf; p++) {
1054 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001055 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001056 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001058 }
1059 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001060 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001061 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001063 }
1064 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001065}
1066
Steve Naroffb29b4272008-04-14 22:03:09 +00001067void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001068 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001069 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001070 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001071 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001072 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001073}
1074
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001075void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1076 const FunctionType *&FPRetType) {
1077 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001078 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001079 else if (T->isFunctionPointerType() ||
1080 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001081 // needs special handling, since pointer-to-functions have special
1082 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001083 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001084 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001085 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001086 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001087 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001088 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001089 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001090 ResultStr += FPRetType->getResultType().getAsString(
1091 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001092 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001093 }
1094 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001095 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001096}
1097
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001098void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1099 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001100 std::string &ResultStr) {
1101 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1102 const FunctionType *FPRetType = 0;
1103 ResultStr += "\nstatic ";
1104 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001105 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001107 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001108 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001109
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001110 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001111 NameStr += "_I_";
1112 else
1113 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001115 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001116 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001117
1118 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001119 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001120 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001121 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001122 }
Mike Stump1eb44332009-09-09 15:08:12 +00001123 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001124 {
1125 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001126 int len = selString.size();
1127 for (int i = 0; i < len; i++)
1128 if (selString[i] == ':')
1129 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001130 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001131 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001132 // Remember this name for metadata emission
1133 MethodInternalNames[OMD] = NameStr;
1134 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001136 // Rewrite arguments
1137 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001139 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001140 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001141 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001142 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001143 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001144 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001145 ResultStr += "struct ";
1146 }
1147 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001148 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001149 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001150 }
1151 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001152 ResultStr += Context->getObjCClassType().getAsString(
1153 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001155 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001156 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001157 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001159 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001160 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1161 E = OMD->param_end(); PI != E; ++PI) {
1162 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001163 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001164 if (PDecl->getType()->isObjCQualifiedIdType()) {
1165 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001166 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001167 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001168 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001169 QualType QT = PDecl->getType();
1170 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1171 if (convertBlockPointerToFunctionPointer(QT))
1172 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1173 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001174 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001175 ResultStr += Name;
1176 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001177 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001178 if (OMD->isVariadic())
1179 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001180 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Steve Naroff76e429d2008-07-16 14:40:40 +00001182 if (FPRetType) {
1183 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Steve Naroff76e429d2008-07-16 14:40:40 +00001185 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001186 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001187 ResultStr += "(";
1188 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1189 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001190 std::string ParamStr = FT->getArgType(i).getAsString(
1191 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001192 ResultStr += ParamStr;
1193 }
1194 if (FT->isVariadic()) {
1195 if (FT->getNumArgs()) ResultStr += ", ";
1196 ResultStr += "...";
1197 }
1198 ResultStr += ")";
1199 } else {
1200 ResultStr += "()";
1201 }
1202 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001203}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001204void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001205 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1206 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001208 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001209
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001210 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001211 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1212 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001213 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001214 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001215 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001216 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001217 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001218 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001219
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001220 const char *startBuf = SM->getCharacterData(LocStart);
1221 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001222 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001223 }
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001225 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001226 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1227 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001228 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001229 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001230 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001231 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001232 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001233 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001235 const char *startBuf = SM->getCharacterData(LocStart);
1236 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001237 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001238 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001239 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001240 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001241 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001242 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001243 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001244 }
1245
Benjamin Kramerd999b372010-02-14 14:14:16 +00001246 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001247}
1248
Steve Naroffb29b4272008-04-14 22:03:09 +00001249void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001250 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001251 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001252 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001253 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001254 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001255 ResultStr += "\n";
1256 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001257 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001258 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001259 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001260 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001261 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001262 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001263 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001264 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001265 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001266
1267 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001268 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001269 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001270 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001271 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001272 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001273 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001274 for (ObjCInterfaceDecl::classmeth_iterator
1275 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001276 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001277 RewriteMethodDeclaration(*I);
1278
Steve Naroff2feac5e2007-10-30 03:43:13 +00001279 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001280 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1281 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001282}
1283
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001284Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001285 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001286 ObjCMethodDecl *OMD = 0;
1287 QualType Ty;
1288 Selector Sel;
Duncan Sands54bd4572010-10-20 08:21:16 +00001289 Stmt *Receiver = 0;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001290 bool Super = false;
1291 QualType SuperTy;
1292 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001293 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001294 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001295 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCall12f78a62010-12-02 01:19:52 +00001296 if (ObjCPropertyRefExpr *PropRefExpr =
1297 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001298 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001299 if (PropRefExpr->isExplicitProperty()) {
1300 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1301 OMD = PDecl->getSetterMethodDecl();
1302 Ty = PDecl->getType();
1303 Sel = PDecl->getSetterName();
1304 } else {
1305 OMD = PropRefExpr->getImplicitPropertySetter();
1306 Sel = OMD->getSelector();
1307 Ty = PropRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001308 }
John McCall12f78a62010-12-02 01:19:52 +00001309 Super = PropRefExpr->isSuperReceiver();
1310 if (!Super) {
1311 Receiver = PropRefExpr->getBase();
1312 } else {
1313 SuperTy = PropRefExpr->getSuperReceiverType();
1314 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001315 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001316 }
1317
1318 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Chris Lattner5f9e2722011-07-23 10:55:15 +00001319 SmallVector<Expr *, 1> ExprVec;
Steve Naroffc77a6362008-12-04 16:24:46 +00001320 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001321
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001322 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001323 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001324 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001325 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001326 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001327 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001328 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001329 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001330 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001331 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001332 &ExprVec[0], 1,
1333 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001334 else {
1335 // FIXME. Refactor this into common code with that in
1336 // RewritePropertyOrImplicitGetter
1337 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1338 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1339 if (PropGetters[Exp])
1340 // This allows us to handle chain/nested property/implicit getters.
1341 Receiver = PropGetters[Exp];
1342
Douglas Gregor04badcf2010-04-21 00:45:42 +00001343 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001344 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001345 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001346 /*FIXME: */SourceLocation(),
1347 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001348 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001349 &ExprVec[0], 1,
1350 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001351 }
Steve Naroffc77a6362008-12-04 16:24:46 +00001352 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001353
Steve Naroffc77a6362008-12-04 16:24:46 +00001354 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001355 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001356 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001357 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1358 // to things that stay around.
1359 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001360 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001361}
1362
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001363Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1364 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001365 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001366 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001367 ObjCMethodDecl *OMD = 0;
1368 QualType Ty;
1369 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001370 bool Super = false;
1371 QualType SuperTy;
1372 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001373 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001374 if (ObjCPropertyRefExpr *PropRefExpr =
1375 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001376 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001377 if (PropRefExpr->isExplicitProperty()) {
1378 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1379 OMD = PDecl->getGetterMethodDecl();
1380 Ty = PDecl->getType();
1381 Sel = PDecl->getGetterName();
1382 } else {
1383 OMD = PropRefExpr->getImplicitPropertyGetter();
1384 Sel = OMD->getSelector();
1385 Ty = PropRefExpr->getType();
1386 }
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001387 Super = PropRefExpr->isSuperReceiver();
1388 if (!Super)
1389 Receiver = PropRefExpr->getBase();
1390 else {
John McCall12f78a62010-12-02 01:19:52 +00001391 SuperTy = PropRefExpr->getSuperReceiverType();
1392 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001393 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001394 }
1395
1396 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1397
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001398 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001399 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001400 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001401 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001402 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001403 PropOrGetterRefExpr->getLocStart(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001404 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001405 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001406 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001407 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001408 0, 0,
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001409 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001410 else {
1411 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1412 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1413 if (PropGetters[Exp])
1414 // This allows us to handle chain/nested property/implicit getters.
1415 Receiver = PropGetters[Exp];
Douglas Gregor04badcf2010-04-21 00:45:42 +00001416 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001417 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001418 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001419 PropOrGetterRefExpr->getLocStart(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001420 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001421 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001422 0, 0,
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001423 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001424 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001425
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001426 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr, MsgExpr->getLocStart(),
1427 MsgExpr->getLocEnd());
Steve Naroff8599e7a2008-12-08 16:43:47 +00001428
1429 if (!PropParentMap)
1430 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001431 bool NestedPropertyRef = false;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001432 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001433 ImplicitCastExpr*ICE=0;
1434 if (Parent)
1435 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1436 assert((ICE->getCastKind() == CK_GetObjCProperty)
1437 && "RewritePropertyOrImplicitGetter");
1438 Parent = PropParentMap->getParent(Parent);
1439 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1440 }
1441 if (NestedPropertyRef) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001442 // We stash away the ReplacingStmt since actually doing the
1443 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001444 PropGetters[ICE] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001445 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1446 // to things that stay around.
1447 Context->Deallocate(MsgExpr);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001448 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001449 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001450 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001451 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001452 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1453 // to things that stay around.
1454 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001455 return ReplacingStmt;
1456 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001457}
1458
Mike Stump1eb44332009-09-09 15:08:12 +00001459Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001460 SourceLocation OrigStart,
1461 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001462 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001463 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001464 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001465 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001466 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001467 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001468 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001469 // lookup which class implements the instance variable.
1470 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001471 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001472 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001473 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Steve Narofff0757612008-05-08 17:52:16 +00001475 // Synthesize an explicit cast to gain access to the ivar.
1476 std::string RecName = clsDeclared->getIdentifier()->getName();
1477 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001478 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001479 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001480 SourceLocation(), SourceLocation(),
1481 II);
Steve Narofff0757612008-05-08 17:52:16 +00001482 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1483 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001484 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001485 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001486 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001487 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001488 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCallf89e55a2010-11-18 06:31:45 +00001489 IV->getBase()->getLocEnd(),
1490 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001491 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001492 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001493 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001494 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001495 IV->getLocation(),
1496 D->getType(),
1497 VK_LValue, OK_Ordinary);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001498 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001499 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001500 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001501 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001502 // Cannot delete IV->getBase(), since PE points to it.
1503 // Replace the old base with the cast. This is important when doing
1504 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001505 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001506 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001507 }
Steve Naroff84472a82008-04-18 21:55:08 +00001508 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001509 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Steve Naroff9f525972008-05-06 23:20:07 +00001511 // Explicit ivar refs need to have a cast inserted.
1512 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001513 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001514 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001515 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001516 // lookup which class implements the instance variable.
1517 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001518 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001519 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001520 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Steve Naroff9f525972008-05-06 23:20:07 +00001522 // Synthesize an explicit cast to gain access to the ivar.
1523 std::string RecName = clsDeclared->getIdentifier()->getName();
1524 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001525 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001526 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001527 SourceLocation(), SourceLocation(),
1528 II);
Steve Naroff9f525972008-05-06 23:20:07 +00001529 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1530 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001531 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001532 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001533 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001534 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001535 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001536 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001537 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001538 // Cannot delete IV->getBase(), since PE points to it.
1539 // Replace the old base with the cast. This is important when doing
1540 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001541 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001542 return IV;
1543 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001544 }
Steve Naroff84472a82008-04-18 21:55:08 +00001545 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001546}
1547
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001548Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
John McCall7502c1d2011-02-13 04:07:26 +00001549 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001550 if (*CI) {
1551 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1552 if (newStmt)
1553 *CI = newStmt;
1554 }
1555 }
1556 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1557 SourceRange OrigStmtRange = S->getSourceRange();
1558 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1559 replaced);
1560 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001561 }
1562 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1563 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1564 return newStmt;
1565 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001566 return S;
1567}
1568
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001569/// SynthCountByEnumWithState - To print:
1570/// ((unsigned int (*)
1571/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001572/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001573/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001574/// "countByEnumeratingWithState:objects:count:"),
1575/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001576/// (id *)items, (unsigned int)16)
1577///
Steve Naroffb29b4272008-04-14 22:03:09 +00001578void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001579 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1580 "id *, unsigned int))(void *)objc_msgSend)";
1581 buf += "\n\t\t";
1582 buf += "((id)l_collection,\n\t\t";
1583 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1584 buf += "\n\t\t";
1585 buf += "&enumState, "
1586 "(id *)items, (unsigned int)16)";
1587}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001588
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001589/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1590/// statement to exit to its outer synthesized loop.
1591///
Steve Naroffb29b4272008-04-14 22:03:09 +00001592Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001593 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1594 return S;
1595 // replace break with goto __break_label
1596 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001598 SourceLocation startLoc = S->getLocStart();
1599 buf = "goto __break_label_";
1600 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001601 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001602
1603 return 0;
1604}
1605
1606/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1607/// statement to continue with its inner synthesized loop.
1608///
Steve Naroffb29b4272008-04-14 22:03:09 +00001609Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001610 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1611 return S;
1612 // replace continue with goto __continue_label
1613 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001615 SourceLocation startLoc = S->getLocStart();
1616 buf = "goto __continue_label_";
1617 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001618 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001620 return 0;
1621}
1622
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001623/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001624/// It rewrites:
1625/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001627/// Into:
1628/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001629/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001630/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001631/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001632/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001633/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001634/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001635/// if (limit) {
1636/// unsigned long startMutations = *enumState.mutationsPtr;
1637/// do {
1638/// unsigned long counter = 0;
1639/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001640/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001641/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001642/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001643/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001644/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001645/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001646/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001647/// objects:items count:16]);
1648/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001649/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001650/// }
1651/// else
1652/// elem = nil;
1653/// }
1654///
Steve Naroffb29b4272008-04-14 22:03:09 +00001655Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001656 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001657 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001658 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001659 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001660 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001661 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001663 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001664 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001665 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001666 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001667 std::string buf;
1668 buf = "\n{\n\t";
1669 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1670 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001671 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001672 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001673 if (ElementType->isObjCQualifiedIdType() ||
1674 ElementType->isObjCQualifiedInterfaceType())
1675 // Simply use 'id' for all qualified types.
1676 elementTypeAsString = "id";
1677 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001678 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001679 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001680 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001681 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001682 buf += elementName;
1683 buf += ";\n\t";
1684 }
Chris Lattner06767512008-04-08 05:52:18 +00001685 else {
1686 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001687 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001688 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1689 if (VD->getType()->isObjCQualifiedIdType() ||
1690 VD->getType()->isObjCQualifiedInterfaceType())
1691 // Simply use 'id' for all qualified types.
1692 elementTypeAsString = "id";
1693 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001694 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001695 }
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001697 // struct __objcFastEnumerationState enumState = { 0 };
1698 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1699 // id items[16];
1700 buf += "id items[16];\n\t";
1701 // id l_collection = (id)
1702 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001703 // Find start location of 'collection' the hard way!
1704 const char *startCollectionBuf = startBuf;
1705 startCollectionBuf += 3; // skip 'for'
1706 startCollectionBuf = strchr(startCollectionBuf, '(');
1707 startCollectionBuf++; // skip '('
1708 // find 'in' and skip it.
1709 while (*startCollectionBuf != ' ' ||
1710 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1711 (*(startCollectionBuf+3) != ' ' &&
1712 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1713 startCollectionBuf++;
1714 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001715
1716 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001717 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001718 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001719 SourceLocation rightParenLoc = S->getRParenLoc();
1720 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001721 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001722 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001724 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1725 // objects:items count:16];
1726 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001727 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001728 // ((unsigned int (*)
1729 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001730 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001731 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001732 // "countByEnumeratingWithState:objects:count:"),
1733 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001734 // (id *)items, (unsigned int)16);
1735 buf += "unsigned long limit =\n\t\t";
1736 SynthCountByEnumWithState(buf);
1737 buf += ";\n\t";
1738 /// if (limit) {
1739 /// unsigned long startMutations = *enumState.mutationsPtr;
1740 /// do {
1741 /// unsigned long counter = 0;
1742 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001743 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001744 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001745 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001746 buf += "if (limit) {\n\t";
1747 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1748 buf += "do {\n\t\t";
1749 buf += "unsigned long counter = 0;\n\t\t";
1750 buf += "do {\n\t\t\t";
1751 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1752 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1753 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001754 buf += " = (";
1755 buf += elementTypeAsString;
1756 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001757 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001758 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001759
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001760 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001761 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001762 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001763 /// objects:items count:16]);
1764 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001765 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001766 /// }
1767 /// else
1768 /// elem = nil;
1769 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001770 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001771 buf = ";\n\t";
1772 buf += "__continue_label_";
1773 buf += utostr(ObjCBcLabelNo.back());
1774 buf += ": ;";
1775 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001776 buf += "} while (counter < limit);\n\t";
1777 buf += "} while (limit = ";
1778 SynthCountByEnumWithState(buf);
1779 buf += ");\n\t";
1780 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001781 buf += " = ((";
1782 buf += elementTypeAsString;
1783 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001784 buf += "__break_label_";
1785 buf += utostr(ObjCBcLabelNo.back());
1786 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001787 buf += "}\n\t";
1788 buf += "else\n\t\t";
1789 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001790 buf += " = ((";
1791 buf += elementTypeAsString;
1792 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001793 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001795 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001796 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001797 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001798 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001799 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001800 } else {
1801 /* Need to treat single statements specially. For example:
1802 *
1803 * for (A *a in b) if (stuff()) break;
1804 * for (A *a in b) xxxyy;
1805 *
1806 * The following code simply scans ahead to the semi to find the actual end.
1807 */
1808 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1809 const char *semiBuf = strchr(stmtBuf, ';');
1810 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001811 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001812 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001813 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001814 Stmts.pop_back();
1815 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001816 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001817}
1818
Mike Stump1eb44332009-09-09 15:08:12 +00001819/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001820/// This routine rewrites @synchronized(expr) stmt;
1821/// into:
1822/// objc_sync_enter(expr);
1823/// @try stmt @finally { objc_sync_exit(expr); }
1824///
Steve Naroffb29b4272008-04-14 22:03:09 +00001825Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001826 // Get the start location and compute the semi location.
1827 SourceLocation startLoc = S->getLocStart();
1828 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001830 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001831
1832 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001833 buf = "objc_sync_enter((id)";
1834 const char *lparenBuf = startBuf;
1835 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001836 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001837 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1838 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001839 // been rewritten! (which implies the SourceLocation's are invalid).
1840 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001841 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001842 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001843 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001844 buf = ");\n";
1845 // declare a new scope with two variables, _stack and _rethrow.
1846 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1847 buf += "int buf[18/*32-bit i386*/];\n";
1848 buf += "char *pointers[4];} _stack;\n";
1849 buf += "id volatile _rethrow = 0;\n";
1850 buf += "objc_exception_try_enter(&_stack);\n";
1851 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001852 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001853 startLoc = S->getSynchBody()->getLocEnd();
1854 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Steve Naroffc7089f12008-08-19 13:04:19 +00001856 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001857 SourceLocation lastCurlyLoc = startLoc;
1858 buf = "}\nelse {\n";
1859 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001860 buf += "}\n";
1861 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001862 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001863
1864 std::string syncBuf;
1865 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001866
1867 Expr *syncExpr = S->getSynchExpr();
1868 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1869 ? CK_BitCast :
1870 syncExpr->getType()->isBlockPointerType()
1871 ? CK_BlockPointerToObjCPointerCast
1872 : CK_CPointerToObjCPointerCast;
1873 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1874 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001875 std::string syncExprBufS;
1876 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001877 syncExpr->printPretty(syncExprBuf, *Context, 0,
1878 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001879 syncBuf += syncExprBuf.str();
1880 syncBuf += ");";
1881
1882 buf += syncBuf;
1883 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001884 buf += "}\n";
1885 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Benjamin Kramerd999b372010-02-14 14:14:16 +00001887 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001888
1889 bool hasReturns = false;
1890 HasReturnStmts(S->getSynchBody(), hasReturns);
1891 if (hasReturns)
1892 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1893
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001894 return 0;
1895}
1896
Steve Naroffb85e77a2009-12-05 21:43:12 +00001897void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1898{
Steve Naroff8c565152008-12-05 17:03:39 +00001899 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001900 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001901 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001902 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001903
Steve Naroffb85e77a2009-12-05 21:43:12 +00001904 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001905 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001906 TryFinallyContainsReturnDiag);
1907 }
1908 return;
1909}
1910
Steve Naroffb85e77a2009-12-05 21:43:12 +00001911void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1912{
1913 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001914 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001915 if (*CI)
1916 HasReturnStmts(*CI, hasReturns);
1917
1918 if (isa<ReturnStmt>(S))
1919 hasReturns = true;
1920 return;
1921}
1922
1923void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1924 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001925 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001926 if (*CI) {
1927 RewriteTryReturnStmts(*CI);
1928 }
1929 if (isa<ReturnStmt>(S)) {
1930 SourceLocation startLoc = S->getLocStart();
1931 const char *startBuf = SM->getCharacterData(startLoc);
1932
1933 const char *semiBuf = strchr(startBuf, ';');
1934 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001935 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001936
1937 std::string buf;
1938 buf = "{ objc_exception_try_exit(&_stack); return";
1939
Benjamin Kramerd999b372010-02-14 14:14:16 +00001940 ReplaceText(startLoc, 6, buf);
1941 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001942 }
1943 return;
1944}
1945
1946void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1947 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001948 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001949 if (*CI) {
1950 RewriteSyncReturnStmts(*CI, syncExitBuf);
1951 }
1952 if (isa<ReturnStmt>(S)) {
1953 SourceLocation startLoc = S->getLocStart();
1954 const char *startBuf = SM->getCharacterData(startLoc);
1955
1956 const char *semiBuf = strchr(startBuf, ';');
1957 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001958 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001959
1960 std::string buf;
1961 buf = "{ objc_exception_try_exit(&_stack);";
1962 buf += syncExitBuf;
1963 buf += " return";
1964
Benjamin Kramerd999b372010-02-14 14:14:16 +00001965 ReplaceText(startLoc, 6, buf);
1966 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001967 }
1968 return;
1969}
1970
Steve Naroffb29b4272008-04-14 22:03:09 +00001971Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001972 // Get the start location and compute the semi location.
1973 SourceLocation startLoc = S->getLocStart();
1974 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Steve Naroff75730982007-11-07 04:08:17 +00001976 assert((*startBuf == '@') && "bogus @try location");
1977
1978 std::string buf;
1979 // declare a new scope with two variables, _stack and _rethrow.
1980 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1981 buf += "int buf[18/*32-bit i386*/];\n";
1982 buf += "char *pointers[4];} _stack;\n";
1983 buf += "id volatile _rethrow = 0;\n";
1984 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001985 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001986
Benjamin Kramerd999b372010-02-14 14:14:16 +00001987 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001988
Steve Naroff75730982007-11-07 04:08:17 +00001989 startLoc = S->getTryBody()->getLocEnd();
1990 startBuf = SM->getCharacterData(startLoc);
1991
1992 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Steve Naroff75730982007-11-07 04:08:17 +00001994 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001995 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001996 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001997 buf = " /* @catch begin */ else {\n";
1998 buf += " id _caught = objc_exception_extract(&_stack);\n";
1999 buf += " objc_exception_try_enter (&_stack);\n";
2000 buf += " if (_setjmp(_stack.buf))\n";
2001 buf += " _rethrow = objc_exception_extract(&_stack);\n";
2002 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Benjamin Kramerd999b372010-02-14 14:14:16 +00002004 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00002005 } else { /* no catch list */
2006 buf = "}\nelse {\n";
2007 buf += " _rethrow = objc_exception_extract(&_stack);\n";
2008 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002009 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00002010 }
Steve Naroff75730982007-11-07 04:08:17 +00002011 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002012 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
2013 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00002014 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00002015
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002016 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00002017 buf = "if ("; // we are generating code for the first catch clause
2018 else
2019 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002020 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00002021 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Steve Naroff75730982007-11-07 04:08:17 +00002023 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Steve Naroff75730982007-11-07 04:08:17 +00002025 const char *lParenLoc = strchr(startBuf, '(');
2026
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002027 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00002028 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002029 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00002030 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2031 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002032 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00002033 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00002034 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Steve Naroffe12e6922008-02-01 20:02:07 +00002036 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00002037 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002038 } else if (catchDecl) {
2039 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002040 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00002041 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002042 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00002043 } else if (const ObjCObjectPointerType *Ptr =
2044 t->getAs<ObjCObjectPointerType>()) {
2045 // Should be a pointer to a class.
2046 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2047 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00002048 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00002049 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00002050 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002051 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00002052 }
2053 }
2054 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002055 lastCatchBody = Catch->getCatchBody();
2056 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00002057 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2058 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2059 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2060 assert((*rParenBuf == ')') && "bogus @catch paren location");
2061 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Mike Stump1eb44332009-09-09 15:08:12 +00002063 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002064 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002065 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002066 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00002067 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002068 }
Steve Naroff75730982007-11-07 04:08:17 +00002069 }
2070 // Complete the catch list...
2071 if (lastCatchBody) {
2072 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002073 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2074 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Steve Naroff378f47a2008-09-11 15:29:03 +00002076 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002077 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00002078 buf = "} /* last catch end */\n";
2079 buf += "else {\n";
2080 buf += " _rethrow = _caught;\n";
2081 buf += " objc_exception_try_exit(&_stack);\n";
2082 buf += "} } /* @catch end */\n";
2083 if (!S->getFinallyStmt())
2084 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002085 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Steve Naroff75730982007-11-07 04:08:17 +00002087 // Set lastCurlyLoc
2088 lastCurlyLoc = lastCatchBody->getLocEnd();
2089 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002090 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002091 startLoc = finalStmt->getLocStart();
2092 startBuf = SM->getCharacterData(startLoc);
2093 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Benjamin Kramerd999b372010-02-14 14:14:16 +00002095 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Steve Naroff75730982007-11-07 04:08:17 +00002097 Stmt *body = finalStmt->getFinallyBody();
2098 SourceLocation startLoc = body->getLocStart();
2099 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002100 assert(*SM->getCharacterData(startLoc) == '{' &&
2101 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002102 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002103 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002104
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002105 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002106 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002107 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002108 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Steve Naroff75730982007-11-07 04:08:17 +00002110 // Set lastCurlyLoc
2111 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Steve Naroff8c565152008-12-05 17:03:39 +00002113 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002114 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002115 } else { /* no finally clause - make sure we synthesize an implicit one */
2116 buf = "{ /* implicit finally clause */\n";
2117 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2118 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2119 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002120 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002121
2122 // Now check for any return/continue/go statements within the @try.
2123 // The implicit finally clause won't called if the @try contains any
2124 // jump statements.
2125 bool hasReturns = false;
2126 HasReturnStmts(S->getTryBody(), hasReturns);
2127 if (hasReturns)
2128 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002129 }
2130 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002131 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002132 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002133 return 0;
2134}
2135
Mike Stump1eb44332009-09-09 15:08:12 +00002136// This can't be done with ReplaceStmt(S, ThrowExpr), since
2137// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002138// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002139Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002140 // Get the start location and compute the semi location.
2141 SourceLocation startLoc = S->getLocStart();
2142 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002143
Steve Naroff2bd03922007-11-07 15:32:26 +00002144 assert((*startBuf == '@') && "bogus @throw location");
2145
2146 std::string buf;
2147 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002148 if (S->getThrowExpr())
2149 buf = "objc_exception_throw(";
2150 else // add an implicit argument
2151 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002152
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002153 // handle "@ throw" correctly.
2154 const char *wBuf = strchr(startBuf, 'w');
2155 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002156 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002157
Steve Naroff2bd03922007-11-07 15:32:26 +00002158 const char *semiBuf = strchr(startBuf, ';');
2159 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002160 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002161 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002162 return 0;
2163}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002164
Steve Naroffb29b4272008-04-14 22:03:09 +00002165Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002166 // Create a new string expression.
2167 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002168 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002169 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002170 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002171 StringLiteral::Ascii, false,
2172 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002173 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Chris Lattner07506182007-11-30 22:53:43 +00002175 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002176 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002177 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002178}
2179
Steve Naroffb29b4272008-04-14 22:03:09 +00002180Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002181 if (!SelGetUidFunctionDecl)
2182 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002183 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2184 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002185 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002186 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002187 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002188 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002189 StringLiteral::Ascii, false,
2190 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002191 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2192 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002193 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002194 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002195 return SelExp;
2196}
2197
Steve Naroffb29b4272008-04-14 22:03:09 +00002198CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002199 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2200 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002201 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002202 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002203
Steve Naroffebf2b562007-10-23 23:50:29 +00002204 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002205 DeclRefExpr *DRE =
2206 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002207
Steve Naroffebf2b562007-10-23 23:50:29 +00002208 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002209 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002210 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002211 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002212 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002213
John McCall183700f2009-09-21 23:43:11 +00002214 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002215
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002216 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002217 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002218 FT->getCallResultType(*Context),
2219 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002220 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002221}
2222
Steve Naroffd5255f52007-11-01 13:24:47 +00002223static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2224 const char *&startRef, const char *&endRef) {
2225 while (startBuf < endBuf) {
2226 if (*startBuf == '<')
2227 startRef = startBuf; // mark the start.
2228 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002229 if (startRef && *startRef == '<') {
2230 endRef = startBuf; // mark the end.
2231 return true;
2232 }
2233 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002234 }
2235 startBuf++;
2236 }
2237 return false;
2238}
2239
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002240static void scanToNextArgument(const char *&argRef) {
2241 int angle = 0;
2242 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2243 if (*argRef == '<')
2244 angle++;
2245 else if (*argRef == '>')
2246 angle--;
2247 argRef++;
2248 }
2249 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2250}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002251
Steve Naroffb29b4272008-04-14 22:03:09 +00002252bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002253 if (T->isObjCQualifiedIdType())
2254 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002255 if (const PointerType *PT = T->getAs<PointerType>()) {
2256 if (PT->getPointeeType()->isObjCQualifiedIdType())
2257 return true;
2258 }
2259 if (T->isObjCObjectPointerType()) {
2260 T = T->getPointeeType();
2261 return T->isObjCQualifiedInterfaceType();
2262 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002263 if (T->isArrayType()) {
2264 QualType ElemTy = Context->getBaseElementType(T);
2265 return needToScanForQualifiers(ElemTy);
2266 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002267 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002268}
2269
Steve Naroff4f95b752008-07-29 18:15:38 +00002270void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2271 QualType Type = E->getType();
2272 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002273 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002274
Steve Naroffcda658e2008-11-19 21:15:47 +00002275 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2276 Loc = ECE->getLParenLoc();
2277 EndLoc = ECE->getRParenLoc();
2278 } else {
2279 Loc = E->getLocStart();
2280 EndLoc = E->getLocEnd();
2281 }
2282 // This will defend against trying to rewrite synthesized expressions.
2283 if (Loc.isInvalid() || EndLoc.isInvalid())
2284 return;
2285
Steve Naroff4f95b752008-07-29 18:15:38 +00002286 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002287 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002288 const char *startRef = 0, *endRef = 0;
2289 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2290 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002291 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2292 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002293 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002294 InsertText(LessLoc, "/*");
2295 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002296 }
2297 }
2298}
2299
Steve Naroffb29b4272008-04-14 22:03:09 +00002300void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002301 SourceLocation Loc;
2302 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002303 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002304 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2305 Loc = VD->getLocation();
2306 Type = VD->getType();
2307 }
2308 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2309 Loc = FD->getLocation();
2310 // Check for ObjC 'id' and class types that have been adorned with protocol
2311 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002312 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002313 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002314 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002315 if (!proto)
2316 return;
2317 Type = proto->getResultType();
2318 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002319 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2320 Loc = FD->getLocation();
2321 Type = FD->getType();
2322 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002323 else
2324 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002325
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002326 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002327 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002328
Steve Naroffd5255f52007-11-01 13:24:47 +00002329 const char *endBuf = SM->getCharacterData(Loc);
2330 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002331 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002332 startBuf--; // scan backward (from the decl location) for return type.
2333 const char *startRef = 0, *endRef = 0;
2334 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2335 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002336 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2337 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002338 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002339 InsertText(LessLoc, "/*");
2340 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002341 }
2342 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002343 if (!proto)
2344 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002345 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002346 const char *startBuf = SM->getCharacterData(Loc);
2347 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002348 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2349 if (needToScanForQualifiers(proto->getArgType(i))) {
2350 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002351
Steve Naroffd5255f52007-11-01 13:24:47 +00002352 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002353 // scan forward (from the decl location) for argument types.
2354 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002355 const char *startRef = 0, *endRef = 0;
2356 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2357 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002358 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002359 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002360 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002361 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002362 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002363 InsertText(LessLoc, "/*");
2364 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002365 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002366 startBuf = ++endBuf;
2367 }
2368 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002369 // If the function name is derived from a macro expansion, then the
2370 // argument buffer will not follow the name. Need to speak with Chris.
2371 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002372 startBuf++; // scan forward (from the decl location) for argument types.
2373 startBuf++;
2374 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002375 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002376}
2377
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002378void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2379 QualType QT = ND->getType();
2380 const Type* TypePtr = QT->getAs<Type>();
2381 if (!isa<TypeOfExprType>(TypePtr))
2382 return;
2383 while (isa<TypeOfExprType>(TypePtr)) {
2384 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2385 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2386 TypePtr = QT->getAs<Type>();
2387 }
2388 // FIXME. This will not work for multiple declarators; as in:
2389 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002390 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002391 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2392 const char *startBuf = SM->getCharacterData(DeclLoc);
2393 if (ND->getInit()) {
2394 std::string Name(ND->getNameAsString());
2395 TypeAsString += " " + Name + " = ";
2396 Expr *E = ND->getInit();
2397 SourceLocation startLoc;
2398 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2399 startLoc = ECE->getLParenLoc();
2400 else
2401 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002402 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002403 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002404 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002405 }
2406 else {
2407 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002408 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002409 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002410 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002411 }
2412}
2413
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002414// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002415void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002416 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002417 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002418 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002419 QualType getFuncType =
2420 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002421 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002422 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002423 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002424 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002425 SC_Extern,
2426 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002427}
2428
Steve Naroffb29b4272008-04-14 22:03:09 +00002429void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002430 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002431 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002432 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002433 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002434 return;
2435 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002436 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002437}
2438
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002439void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2440 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002441 const char *argPtr = TypeString.c_str();
2442 if (!strchr(argPtr, '^')) {
2443 Str += TypeString;
2444 return;
2445 }
2446 while (*argPtr) {
2447 Str += (*argPtr == '^' ? '*' : *argPtr);
2448 argPtr++;
2449 }
2450}
2451
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002452// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002453void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2454 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002455 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002456 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002457 const char *argPtr = TypeString.c_str();
2458 int paren = 0;
2459 while (*argPtr) {
2460 switch (*argPtr) {
2461 case '(':
2462 Str += *argPtr;
2463 paren++;
2464 break;
2465 case ')':
2466 Str += *argPtr;
2467 paren--;
2468 break;
2469 case '^':
2470 Str += '*';
2471 if (paren == 1)
2472 Str += VD->getNameAsString();
2473 break;
2474 default:
2475 Str += *argPtr;
2476 break;
2477 }
2478 argPtr++;
2479 }
2480}
2481
2482
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002483void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2484 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2485 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2486 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2487 if (!proto)
2488 return;
2489 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002490 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002491 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002492 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002493 FdStr += "(";
2494 unsigned numArgs = proto->getNumArgs();
2495 for (unsigned i = 0; i < numArgs; i++) {
2496 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002497 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002498 if (i+1 < numArgs)
2499 FdStr += ", ";
2500 }
2501 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002502 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002503 CurFunctionDeclToDeclareForBlock = 0;
2504}
2505
Steve Naroffc0a123c2008-03-11 17:37:02 +00002506// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002507void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002508 if (SuperContructorFunctionDecl)
2509 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002510 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002511 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002512 QualType argT = Context->getObjCIdType();
2513 assert(!argT.isNull() && "Can't find 'id' type");
2514 ArgTys.push_back(argT);
2515 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002516 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2517 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002518 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002519 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002520 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002521 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002522 SC_Extern,
2523 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002524}
2525
Steve Naroff09b266e2007-10-30 23:14:51 +00002526// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002527void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002528 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002529 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002530 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002531 assert(!argT.isNull() && "Can't find 'id' type");
2532 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002533 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002534 assert(!argT.isNull() && "Can't find 'SEL' type");
2535 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002536 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2537 &ArgTys[0], ArgTys.size(),
2538 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002539 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002540 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002541 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002542 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002543 SC_Extern,
2544 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002545}
2546
Steve Naroff874e2322007-11-15 10:28:18 +00002547// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002548void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002549 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002550 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002551 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002552 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002553 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002554 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2555 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2556 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002557 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002558 assert(!argT.isNull() && "Can't find 'SEL' type");
2559 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002560 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2561 &ArgTys[0], ArgTys.size(),
2562 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002563 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002564 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002565 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002566 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002567 SC_Extern,
2568 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002569}
2570
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002571// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002572void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002573 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002574 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002575 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002576 assert(!argT.isNull() && "Can't find 'id' type");
2577 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002578 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002579 assert(!argT.isNull() && "Can't find 'SEL' type");
2580 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002581 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2582 &ArgTys[0], ArgTys.size(),
2583 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002584 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002585 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002586 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002587 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002588 SC_Extern,
2589 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002590}
2591
Mike Stump1eb44332009-09-09 15:08:12 +00002592// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002593// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002594void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002595 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002596 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002597 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002598 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002599 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002600 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002601 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2602 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2603 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002604 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002605 assert(!argT.isNull() && "Can't find 'SEL' type");
2606 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002607 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2608 &ArgTys[0], ArgTys.size(),
2609 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002610 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002611 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002612 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002613 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002614 SC_Extern,
2615 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002616}
2617
Steve Naroff1284db82008-05-08 22:02:18 +00002618// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002619void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002620 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002621 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002622 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002623 assert(!argT.isNull() && "Can't find 'id' type");
2624 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002625 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002626 assert(!argT.isNull() && "Can't find 'SEL' type");
2627 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002628 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2629 &ArgTys[0], ArgTys.size(),
2630 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002631 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002632 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002633 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002634 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002635 SC_Extern,
2636 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002637}
2638
Steve Naroff09b266e2007-10-30 23:14:51 +00002639// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002640void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002641 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002642 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002643 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002644 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2645 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002646 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002647 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002648 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002649 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002650 SC_Extern,
2651 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002652}
2653
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002654// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2655void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2656 IdentifierInfo *getSuperClassIdent =
2657 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002658 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002659 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002660 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2661 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002662 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002663 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002664 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002665 getSuperClassIdent,
2666 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002667 SC_Extern,
2668 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002669 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002670}
2671
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002672// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002673void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002674 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002675 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002676 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002677 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2678 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002679 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002680 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002681 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002682 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002683 SC_Extern,
2684 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002685}
2686
Steve Naroffb29b4272008-04-14 22:03:09 +00002687Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002688 QualType strType = getConstantStringStructType();
2689
2690 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002691
2692 std::string tmpName = InFileName;
2693 unsigned i;
2694 for (i=0; i < tmpName.length(); i++) {
2695 char c = tmpName.at(i);
2696 // replace any non alphanumeric characters with '_'.
2697 if (!isalpha(c) && (c < '0' || c > '9'))
2698 tmpName[i] = '_';
2699 }
2700 S += tmpName;
2701 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002702 S += utostr(NumObjCStringLiterals++);
2703
Steve Naroffba92b2e2008-03-27 22:29:16 +00002704 Preamble += "static __NSConstantStringImpl " + S;
2705 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2706 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002707 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002708 std::string prettyBufS;
2709 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002710 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2711 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002712 Preamble += prettyBuf.str();
2713 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002714 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002715
2716 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002717 SourceLocation(), &Context->Idents.get(S),
2718 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002719 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2720 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002721 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002722 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002723 VK_RValue, OK_Ordinary,
2724 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002725 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002726 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002727 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002728 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002729 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002730 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002731}
2732
Steve Naroff874e2322007-11-15 10:28:18 +00002733// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002734QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002735 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002736 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002737 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002738 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002739 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Steve Naroff874e2322007-11-15 10:28:18 +00002741 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002742 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002743 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002744 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002745
Steve Naroff874e2322007-11-15 10:28:18 +00002746 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002747 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002748 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002749 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002750 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002751 FieldTypes[i], 0,
2752 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002753 /*Mutable=*/false,
2754 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002755 }
Mike Stump1eb44332009-09-09 15:08:12 +00002756
Douglas Gregor838db382010-02-11 01:19:42 +00002757 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002758 }
2759 return Context->getTagDeclType(SuperStructDecl);
2760}
2761
Steve Naroffb29b4272008-04-14 22:03:09 +00002762QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002763 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002764 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002765 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002766 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002767 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002768
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002769 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002770 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002771 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002772 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002773 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002774 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002775 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002776 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002777
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002778 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002779 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002780 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2781 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002782 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002783 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002784 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002785 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002786 /*Mutable=*/true,
2787 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002788 }
2789
Douglas Gregor838db382010-02-11 01:19:42 +00002790 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002791 }
2792 return Context->getTagDeclType(ConstantStringDecl);
2793}
2794
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002795Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2796 SourceLocation StartLoc,
2797 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002798 if (!SelGetUidFunctionDecl)
2799 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002800 if (!MsgSendFunctionDecl)
2801 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002802 if (!MsgSendSuperFunctionDecl)
2803 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002804 if (!MsgSendStretFunctionDecl)
2805 SynthMsgSendStretFunctionDecl();
2806 if (!MsgSendSuperStretFunctionDecl)
2807 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002808 if (!MsgSendFpretFunctionDecl)
2809 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002810 if (!GetClassFunctionDecl)
2811 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002812 if (!GetSuperClassFunctionDecl)
2813 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002814 if (!GetMetaClassFunctionDecl)
2815 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002816
Steve Naroff874e2322007-11-15 10:28:18 +00002817 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002818 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2819 // May need to use objc_msgSend_stret() as well.
2820 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002821 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2822 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002823 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002824 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002825 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002826 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002827 }
Mike Stump1eb44332009-09-09 15:08:12 +00002828
Steve Naroff934f2762007-10-24 22:48:43 +00002829 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002830 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002831 switch (Exp->getReceiverKind()) {
2832 case ObjCMessageExpr::SuperClass: {
2833 MsgSendFlavor = MsgSendSuperFunctionDecl;
2834 if (MsgSendStretFlavor)
2835 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2836 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002837
Douglas Gregor04badcf2010-04-21 00:45:42 +00002838 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002839
Chris Lattner5f9e2722011-07-23 10:55:15 +00002840 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002841
Douglas Gregor04badcf2010-04-21 00:45:42 +00002842 // set the receiver to self, the first argument to all methods.
2843 InitExprs.push_back(
2844 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002845 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002846 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002847 Context->getObjCIdType(),
2848 VK_RValue,
2849 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002850 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002851
Douglas Gregor04badcf2010-04-21 00:45:42 +00002852 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002853 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002854 QualType argType = Context->getPointerType(Context->CharTy);
2855 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002856 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002857 StringLiteral::Ascii, false,
2858 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002859 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2860 &ClsExprs[0],
2861 ClsExprs.size(),
2862 StartLoc,
2863 EndLoc);
2864 // (Class)objc_getClass("CurrentClass")
2865 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2866 Context->getObjCClassType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002867 CK_CPointerToObjCPointerCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002868 ClsExprs.clear();
2869 ClsExprs.push_back(ArgExpr);
2870 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2871 &ClsExprs[0], ClsExprs.size(),
2872 StartLoc, EndLoc);
2873
2874 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2875 // To turn off a warning, type-cast to 'id'
2876 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2877 NoTypeInfoCStyleCastExpr(Context,
2878 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002879 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002880 // struct objc_super
2881 QualType superType = getSuperStructType();
2882 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002883
Francois Pichet62ec1f22011-09-17 17:15:52 +00002884 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002885 SynthSuperContructorFunctionDecl();
2886 // Simulate a contructor call...
2887 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002888 superType, VK_LValue,
2889 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002890 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2891 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002892 superType, VK_LValue,
2893 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002894 // The code for super is a little tricky to prevent collision with
2895 // the structure definition in the header. The rewriter has it's own
2896 // internal definition (__rw_objc_super) that is uses. This is why
2897 // we need the cast below. For example:
2898 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2899 //
John McCall2de56d12010-08-25 11:45:40 +00002900 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002901 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002902 VK_RValue, OK_Ordinary,
2903 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002904 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2905 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002906 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002907 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002908 // (struct objc_super) { <exprs from above> }
2909 InitListExpr *ILE =
2910 new (Context) InitListExpr(*Context, SourceLocation(),
2911 &InitExprs[0], InitExprs.size(),
2912 SourceLocation());
2913 TypeSourceInfo *superTInfo
2914 = Context->getTrivialTypeSourceInfo(superType);
2915 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002916 superType, VK_LValue,
2917 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002918 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002919 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002920 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002921 VK_RValue, OK_Ordinary,
2922 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002923 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002924 MsgExprs.push_back(SuperRep);
2925 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002926 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002927
2928 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002929 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002930 QualType argType = Context->getPointerType(Context->CharTy);
2931 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002932 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002933 IdentifierInfo *clsName = Class->getIdentifier();
2934 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002935 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002936 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002937 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002938 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2939 &ClsExprs[0],
2940 ClsExprs.size(),
2941 StartLoc, EndLoc);
2942 MsgExprs.push_back(Cls);
2943 break;
2944 }
2945
2946 case ObjCMessageExpr::SuperInstance:{
2947 MsgSendFlavor = MsgSendSuperFunctionDecl;
2948 if (MsgSendStretFlavor)
2949 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2950 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2951 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002952 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002953
2954 InitExprs.push_back(
2955 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002956 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002957 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002958 Context->getObjCIdType(),
2959 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002960 ); // set the 'receiver'.
2961
2962 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002963 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002964 QualType argType = Context->getPointerType(Context->CharTy);
2965 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002966 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002967 StringLiteral::Ascii, false, argType,
2968 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002969 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2970 &ClsExprs[0],
2971 ClsExprs.size(),
2972 StartLoc, EndLoc);
2973 // (Class)objc_getClass("CurrentClass")
2974 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2975 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002976 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002977 ClsExprs.clear();
2978 ClsExprs.push_back(ArgExpr);
2979 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2980 &ClsExprs[0], ClsExprs.size(),
2981 StartLoc, EndLoc);
2982
2983 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2984 // To turn off a warning, type-cast to 'id'
2985 InitExprs.push_back(
2986 // set 'super class', using class_getSuperclass().
2987 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002988 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002989 // struct objc_super
2990 QualType superType = getSuperStructType();
2991 Expr *SuperRep;
2992
Francois Pichet62ec1f22011-09-17 17:15:52 +00002993 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002994 SynthSuperContructorFunctionDecl();
2995 // Simulate a contructor call...
2996 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002997 superType, VK_LValue,
2998 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002999 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3000 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003001 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00003002 // The code for super is a little tricky to prevent collision with
3003 // the structure definition in the header. The rewriter has it's own
3004 // internal definition (__rw_objc_super) that is uses. This is why
3005 // we need the cast below. For example:
3006 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3007 //
John McCall2de56d12010-08-25 11:45:40 +00003008 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003009 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003010 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003011 SourceLocation());
3012 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3013 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00003014 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003015 } else {
3016 // (struct objc_super) { <exprs from above> }
3017 InitListExpr *ILE =
3018 new (Context) InitListExpr(*Context, SourceLocation(),
3019 &InitExprs[0], InitExprs.size(),
3020 SourceLocation());
3021 TypeSourceInfo *superTInfo
3022 = Context->getTrivialTypeSourceInfo(superType);
3023 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003024 superType, VK_RValue, ILE,
3025 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003026 }
3027 MsgExprs.push_back(SuperRep);
3028 break;
3029 }
3030
3031 case ObjCMessageExpr::Instance: {
3032 // Remove all type-casts because it may contain objc-style types; e.g.
3033 // Foo<Proto> *.
3034 Expr *recExpr = Exp->getInstanceReceiver();
3035 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3036 recExpr = CE->getSubExpr();
3037 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00003038 CK_BitCast, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003039 MsgExprs.push_back(recExpr);
3040 break;
3041 }
3042 }
3043
Steve Naroffbeaf2992007-11-03 11:27:19 +00003044 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003045 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00003046 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00003047 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00003048 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00003049 StringLiteral::Ascii, false,
3050 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00003051 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003052 &SelExprs[0], SelExprs.size(),
3053 StartLoc,
3054 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00003055 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003056
Steve Naroff934f2762007-10-24 22:48:43 +00003057 // Now push any user supplied arguments.
3058 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00003059 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00003060 // Make all implicit casts explicit...ICE comes in handy:-)
3061 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3062 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00003063 QualType type = ICE->getType();
3064 if (needToScanForQualifiers(type))
3065 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003066 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003067 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00003068 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00003069 CastKind CK;
3070 if (SubExpr->getType()->isIntegralType(*Context) &&
3071 type->isBooleanType()) {
3072 CK = CK_IntegralToBoolean;
3073 } else if (type->isObjCObjectPointerType()) {
3074 if (SubExpr->getType()->isBlockPointerType()) {
3075 CK = CK_BlockPointerToObjCPointerCast;
3076 } else if (SubExpr->getType()->isPointerType()) {
3077 CK = CK_CPointerToObjCPointerCast;
3078 } else {
3079 CK = CK_BitCast;
3080 }
3081 } else {
3082 CK = CK_BitCast;
3083 }
3084
3085 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003086 }
3087 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003088 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003089 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003090 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003091 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00003092 CastKind CK;
3093 if (userExpr->getType()->isIntegralType(*Context)) {
3094 CK = CK_IntegralToPointer;
3095 } else if (userExpr->getType()->isBlockPointerType()) {
3096 CK = CK_BlockPointerToObjCPointerCast;
3097 } else if (userExpr->getType()->isPointerType()) {
3098 CK = CK_CPointerToObjCPointerCast;
3099 } else {
3100 CK = CK_BitCast;
3101 }
John McCall9d125032010-01-15 18:39:57 +00003102 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00003103 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003104 }
Mike Stump1eb44332009-09-09 15:08:12 +00003105 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003106 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003107 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3108 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003109 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003110 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003111 }
Steve Naroffab972d32007-11-04 22:37:50 +00003112 // Generate the funky cast.
3113 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003114 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00003115 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003116
Steve Naroffab972d32007-11-04 22:37:50 +00003117 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003118 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3119 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3120 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003121 ArgTypes.push_back(Context->getObjCIdType());
3122 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003123 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003124 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003125 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3126 E = OMD->param_end(); PI != E; ++PI) {
3127 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003128 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003129 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003130 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003131 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003132 ArgTypes.push_back(t);
3133 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00003134 returnType = Exp->getType();
3135 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003136 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003137 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003138 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003139 }
3140 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003141 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003142
Steve Naroffab972d32007-11-04 22:37:50 +00003143 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003144 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003145 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003146
Mike Stump1eb44332009-09-09 15:08:12 +00003147 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003148 // If we don't do this cast, we get the following bizarre warning/note:
3149 // xx.m:13: warning: function called through a non-compatible type
3150 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003151 cast = NoTypeInfoCStyleCastExpr(Context,
3152 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003153 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003154
Steve Naroffab972d32007-11-04 22:37:50 +00003155 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003156 QualType castType =
3157 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3158 // If we don't have a method decl, force a variadic cast.
3159 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003160 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003161 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003162 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003163
3164 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003165 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003166
John McCall183700f2009-09-21 23:43:11 +00003167 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003168 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003169 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003170 FT->getResultType(), VK_RValue,
3171 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003172 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003173 if (MsgSendStretFlavor) {
3174 // We have the method which returns a struct/union. Must also generate
3175 // call to objc_msgSend_stret and hang both varieties on a conditional
3176 // expression which dictate which one to envoke depending on size of
3177 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003178
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003179 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003180 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003181 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003182 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003183 cast = NoTypeInfoCStyleCastExpr(Context,
3184 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003185 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003186 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003187 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3188 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003189 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003190 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003191 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003192
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003193 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003194 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003195
John McCall183700f2009-09-21 23:43:11 +00003196 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003197 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003198 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003199 FT->getResultType(), VK_RValue,
3200 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003201
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003202 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003203 UnaryExprOrTypeTraitExpr *sizeofExpr =
3204 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3205 Context->getTrivialTypeSourceInfo(returnType),
3206 Context->getSizeType(), SourceLocation(),
3207 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003208 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3209 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3210 // For X86 it is more complicated and some kind of target specific routine
3211 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003212 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003213 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003214 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3215 llvm::APInt(IntSize, 8),
3216 Context->IntTy,
3217 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003218 BinaryOperator *lessThanExpr =
3219 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3220 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003221 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003222 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003223 new (Context) ConditionalOperator(lessThanExpr,
3224 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003225 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003226 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003227 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3228 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003229 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003230 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003231 return ReplacingStmt;
3232}
3233
Steve Naroffb29b4272008-04-14 22:03:09 +00003234Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003235 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3236 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003237
Steve Naroff934f2762007-10-24 22:48:43 +00003238 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003239 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003240
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003241 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003242 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003243}
3244
Steve Naroff621edce2009-04-29 16:37:50 +00003245// typedef struct objc_object Protocol;
3246QualType RewriteObjC::getProtocolType() {
3247 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003248 TypeSourceInfo *TInfo
3249 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003250 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003251 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003252 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003253 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003254 }
3255 return Context->getTypeDeclType(ProtocolTypeDecl);
3256}
3257
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003258/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003259/// a synthesized/forward data reference (to the protocol's metadata).
3260/// The forward references (and metadata) are generated in
3261/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003262Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003263 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3264 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003265 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003266 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003267 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003268 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3269 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003270 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003271 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003272 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003273 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003274 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003275 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003276 ReplaceStmt(Exp, castExpr);
3277 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003278 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003279 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003280
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003281}
3282
Mike Stump1eb44332009-09-09 15:08:12 +00003283bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003284 const char *endBuf) {
3285 while (startBuf < endBuf) {
3286 if (*startBuf == '#') {
3287 // Skip whitespace.
3288 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3289 ;
3290 if (!strncmp(startBuf, "if", strlen("if")) ||
3291 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3292 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3293 !strncmp(startBuf, "define", strlen("define")) ||
3294 !strncmp(startBuf, "undef", strlen("undef")) ||
3295 !strncmp(startBuf, "else", strlen("else")) ||
3296 !strncmp(startBuf, "elif", strlen("elif")) ||
3297 !strncmp(startBuf, "endif", strlen("endif")) ||
3298 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3299 !strncmp(startBuf, "include", strlen("include")) ||
3300 !strncmp(startBuf, "import", strlen("import")) ||
3301 !strncmp(startBuf, "include_next", strlen("include_next")))
3302 return true;
3303 }
3304 startBuf++;
3305 }
3306 return false;
3307}
3308
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003309/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003310/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003311void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003312 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003313 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003314 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003315 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003316 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003317 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003318 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003319 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003320 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003321 SourceLocation LocStart = CDecl->getLocStart();
3322 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003323
Steve Narofffea763e82007-11-14 19:25:57 +00003324 const char *startBuf = SM->getCharacterData(LocStart);
3325 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003326
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003327 // If no ivars and no root or if its root, directly or indirectly,
3328 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003329 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3330 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003331 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003332 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003333 return;
3334 }
Mike Stump1eb44332009-09-09 15:08:12 +00003335
3336 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003337 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003338 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003339 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003340 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003341 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003342
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003343 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003344 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003345 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003346 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003347 // If the buffer contains preprocessor directives, we do more fine-grained
3348 // rewrites. This is intended to fix code that looks like (which occurs in
3349 // NSURL.h, for example):
3350 //
3351 // #ifdef XYZ
3352 // @interface Foo : NSObject
3353 // #else
3354 // @interface FooBar : NSObject
3355 // #endif
3356 // {
3357 // int i;
3358 // }
3359 // @end
3360 //
3361 // This clause is segregated to avoid breaking the common case.
3362 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003363 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003364 CDecl->getClassLoc();
3365 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003366 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003367
Chris Lattnercafeb352009-02-20 18:18:36 +00003368 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003369 // advance to the end of the referenced protocols.
3370 while (endHeader < cursor && *endHeader != '>') endHeader++;
3371 endHeader++;
3372 }
3373 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003374 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003375 } else {
3376 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003377 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003378 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003379 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003380 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003381 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003382 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003383 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003384 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003385
Steve Narofffea763e82007-11-14 19:25:57 +00003386 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003387 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003388 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003389 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003390 }
3391 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003392
Steve Narofffea763e82007-11-14 19:25:57 +00003393 // Now comment out any visibility specifiers.
3394 while (cursor < endBuf) {
3395 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003396 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003397 // Skip whitespace.
3398 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3399 /*scan*/;
3400
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003401 // FIXME: presence of @public, etc. inside comment results in
3402 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003403 if (!strncmp(cursor, "public", strlen("public")) ||
3404 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003405 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003406 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003407 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003408 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003409 // FIXME: If there are cases where '<' is used in ivar declaration part
3410 // of user code, then scan the ivar list and use needToScanForQualifiers
3411 // for type checking.
3412 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003413 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003414 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003415 cursor = strchr(cursor, '>');
3416 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003417 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003418 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003419 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003420 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003421 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003422 }
Steve Narofffea763e82007-11-14 19:25:57 +00003423 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003424 }
Steve Narofffea763e82007-11-14 19:25:57 +00003425 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003426 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003427 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003428 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003429 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003430 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003431 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003432 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003433 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003434 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003435 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003436 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003437 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003438 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003439}
3440
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003441// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003442/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003443template<typename MethodIterator>
3444void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3445 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003446 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003447 StringRef prefix,
3448 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003449 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003450 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003451
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003452 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003453 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003454 SEL _cmd;
3455 char *method_types;
3456 void *_imp;
3457 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003458 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003459 Result += "\nstruct _objc_method {\n";
3460 Result += "\tSEL _cmd;\n";
3461 Result += "\tchar *method_types;\n";
3462 Result += "\tvoid *_imp;\n";
3463 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003464
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003465 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003466 }
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003468 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003469
Steve Naroff946a6932008-03-11 00:12:29 +00003470 /* struct {
3471 struct _objc_method_list *next_method;
3472 int method_count;
3473 struct _objc_method method_list[];
3474 }
3475 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003476 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003477 Result += "\nstatic struct {\n";
3478 Result += "\tstruct _objc_method_list *next_method;\n";
3479 Result += "\tint method_count;\n";
3480 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003481 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003482 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003483 Result += prefix;
3484 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3485 Result += "_METHODS_";
3486 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003487 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003488 Result += IsInstanceMethod ? "inst" : "cls";
3489 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003490 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003491
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003492 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003493 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003494 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003495 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003496 Result += "\", \"";
3497 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003498 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003499 Result += MethodInternalNames[*MethodBegin];
3500 Result += "}\n";
3501 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3502 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003503 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003504 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003505 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003506 Result += "\", \"";
3507 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003508 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003509 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003510 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003511 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003512 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003513}
3514
Steve Naroff621edce2009-04-29 16:37:50 +00003515/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003516void RewriteObjC::
Chris Lattner5f9e2722011-07-23 10:55:15 +00003517RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, StringRef prefix,
3518 StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003519 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003520
3521 // Output struct protocol_methods holder of method selector and type.
3522 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3523 /* struct protocol_methods {
3524 SEL _cmd;
3525 char *method_types;
3526 }
3527 */
3528 Result += "\nstruct _protocol_methods {\n";
3529 Result += "\tstruct objc_selector *_cmd;\n";
3530 Result += "\tchar *method_types;\n";
3531 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003532
Steve Naroff621edce2009-04-29 16:37:50 +00003533 objc_protocol_methods = true;
3534 }
3535 // Do not synthesize the protocol more than once.
3536 if (ObjCSynthesizedProtocols.count(PDecl))
3537 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003538
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003539 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3540 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3541 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003542 /* struct _objc_protocol_method_list {
3543 int protocol_method_count;
3544 struct protocol_methods protocols[];
3545 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003546 */
Steve Naroff621edce2009-04-29 16:37:50 +00003547 Result += "\nstatic struct {\n";
3548 Result += "\tint protocol_method_count;\n";
3549 Result += "\tstruct _protocol_methods protocol_methods[";
3550 Result += utostr(NumMethods);
3551 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3552 Result += PDecl->getNameAsString();
3553 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3554 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003555
Steve Naroff621edce2009-04-29 16:37:50 +00003556 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003557 for (ObjCProtocolDecl::instmeth_iterator
3558 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003559 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003560 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003561 Result += "\t ,{{(struct objc_selector *)\"";
3562 else
3563 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003564 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003565 std::string MethodTypeString;
3566 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3567 Result += "\", \"";
3568 Result += MethodTypeString;
3569 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003570 }
Steve Naroff621edce2009-04-29 16:37:50 +00003571 Result += "\t }\n};\n";
3572 }
Mike Stump1eb44332009-09-09 15:08:12 +00003573
Steve Naroff621edce2009-04-29 16:37:50 +00003574 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003575 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3576 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003577 if (NumMethods > 0) {
3578 /* struct _objc_protocol_method_list {
3579 int protocol_method_count;
3580 struct protocol_methods protocols[];
3581 }
3582 */
3583 Result += "\nstatic struct {\n";
3584 Result += "\tint protocol_method_count;\n";
3585 Result += "\tstruct _protocol_methods protocol_methods[";
3586 Result += utostr(NumMethods);
3587 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3588 Result += PDecl->getNameAsString();
3589 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3590 "{\n\t";
3591 Result += utostr(NumMethods);
3592 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003593
Steve Naroff621edce2009-04-29 16:37:50 +00003594 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003595 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003596 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003597 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003598 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003599 Result += "\t ,{{(struct objc_selector *)\"";
3600 else
3601 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003602 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003603 std::string MethodTypeString;
3604 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3605 Result += "\", \"";
3606 Result += MethodTypeString;
3607 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003608 }
Steve Naroff621edce2009-04-29 16:37:50 +00003609 Result += "\t }\n};\n";
3610 }
3611
3612 // Output:
3613 /* struct _objc_protocol {
3614 // Objective-C 1.0 extensions
3615 struct _objc_protocol_extension *isa;
3616 char *protocol_name;
3617 struct _objc_protocol **protocol_list;
3618 struct _objc_protocol_method_list *instance_methods;
3619 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003620 };
Steve Naroff621edce2009-04-29 16:37:50 +00003621 */
3622 static bool objc_protocol = false;
3623 if (!objc_protocol) {
3624 Result += "\nstruct _objc_protocol {\n";
3625 Result += "\tstruct _objc_protocol_extension *isa;\n";
3626 Result += "\tchar *protocol_name;\n";
3627 Result += "\tstruct _objc_protocol **protocol_list;\n";
3628 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3629 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003630 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003631
Steve Naroff621edce2009-04-29 16:37:50 +00003632 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003633 }
Mike Stump1eb44332009-09-09 15:08:12 +00003634
Steve Naroff621edce2009-04-29 16:37:50 +00003635 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3636 Result += PDecl->getNameAsString();
3637 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3638 "{\n\t0, \"";
3639 Result += PDecl->getNameAsString();
3640 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003641 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003642 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3643 Result += PDecl->getNameAsString();
3644 Result += ", ";
3645 }
3646 else
3647 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003648 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003649 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3650 Result += PDecl->getNameAsString();
3651 Result += "\n";
3652 }
3653 else
3654 Result += "0\n";
3655 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003656
Steve Naroff621edce2009-04-29 16:37:50 +00003657 // Mark this protocol as having been generated.
3658 if (!ObjCSynthesizedProtocols.insert(PDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003659 llvm_unreachable("protocol already synthesized");
Steve Naroff621edce2009-04-29 16:37:50 +00003660
3661}
3662
3663void RewriteObjC::
3664RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003665 StringRef prefix, StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003666 std::string &Result) {
3667 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003668
Steve Naroff621edce2009-04-29 16:37:50 +00003669 for (unsigned i = 0; i != Protocols.size(); i++)
3670 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3671
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003672 // Output the top lovel protocol meta-data for the class.
3673 /* struct _objc_protocol_list {
3674 struct _objc_protocol_list *next;
3675 int protocol_count;
3676 struct _objc_protocol *class_protocols[];
3677 }
3678 */
3679 Result += "\nstatic struct {\n";
3680 Result += "\tstruct _objc_protocol_list *next;\n";
3681 Result += "\tint protocol_count;\n";
3682 Result += "\tstruct _objc_protocol *class_protocols[";
3683 Result += utostr(Protocols.size());
3684 Result += "];\n} _OBJC_";
3685 Result += prefix;
3686 Result += "_PROTOCOLS_";
3687 Result += ClassName;
3688 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3689 "{\n\t0, ";
3690 Result += utostr(Protocols.size());
3691 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003692
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003693 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003694 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003695 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003696
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003697 for (unsigned i = 1; i != Protocols.size(); i++) {
3698 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003699 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003700 Result += "\n";
3701 }
3702 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003703}
3704
Steve Naroff621edce2009-04-29 16:37:50 +00003705
Mike Stump1eb44332009-09-09 15:08:12 +00003706/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003707/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003708void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003709 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003710 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003711 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003712 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003713 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003714 CDecl = CDecl->getNextClassCategory())
3715 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3716 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003717
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003718 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003719 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003720 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003721
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003722 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003723 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003724 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003725
3726 // If any of our property implementations have associated getters or
3727 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003728 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3729 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003730 Prop != PropEnd; ++Prop) {
3731 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3732 continue;
3733 if (!(*Prop)->getPropertyIvarDecl())
3734 continue;
3735 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3736 if (!PD)
3737 continue;
3738 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3739 InstanceMethods.push_back(Getter);
3740 if (PD->isReadOnly())
3741 continue;
3742 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3743 InstanceMethods.push_back(Setter);
3744 }
3745 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003746 true, "CATEGORY_", FullCategoryName.c_str(),
3747 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003748
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003749 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003750 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003751 false, "CATEGORY_", FullCategoryName.c_str(),
3752 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003753
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003754 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003755 // Null CDecl is case of a category implementation with no category interface
3756 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003757 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003758 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003759 /* struct _objc_category {
3760 char *category_name;
3761 char *class_name;
3762 struct _objc_method_list *instance_methods;
3763 struct _objc_method_list *class_methods;
3764 struct _objc_protocol_list *protocols;
3765 // Objective-C 1.0 extensions
3766 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003767 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003768 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003769 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003770 */
Mike Stump1eb44332009-09-09 15:08:12 +00003771
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003772 static bool objc_category = false;
3773 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003774 Result += "\nstruct _objc_category {\n";
3775 Result += "\tchar *category_name;\n";
3776 Result += "\tchar *class_name;\n";
3777 Result += "\tstruct _objc_method_list *instance_methods;\n";
3778 Result += "\tstruct _objc_method_list *class_methods;\n";
3779 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003780 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003781 Result += "\tstruct _objc_property_list *instance_properties;\n";
3782 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003783 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003784 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003785 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3786 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003787 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003788 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003789 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003790 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003791 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003792
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003793 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003794 Result += "\t, (struct _objc_method_list *)"
3795 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3796 Result += FullCategoryName;
3797 Result += "\n";
3798 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003799 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003800 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003801 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003802 Result += "\t, (struct _objc_method_list *)"
3803 "&_OBJC_CATEGORY_CLASS_METHODS_";
3804 Result += FullCategoryName;
3805 Result += "\n";
3806 }
3807 else
3808 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003809
Chris Lattnercafeb352009-02-20 18:18:36 +00003810 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003811 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003812 Result += FullCategoryName;
3813 Result += "\n";
3814 }
3815 else
3816 Result += "\t, 0\n";
3817 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003818}
3819
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003820/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3821/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003822void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003823 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003824 if (ivar->isBitField()) {
3825 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3826 // place all bitfields at offset 0.
3827 Result += "0";
3828 } else {
3829 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003830 Result += ivar->getContainingInterface()->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003831 if (LangOpts.MicrosoftExt)
Steve Naroff8f3b2652008-07-16 18:22:22 +00003832 Result += "_IMPL";
3833 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003834 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003835 Result += ")";
3836 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003837}
3838
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003839//===----------------------------------------------------------------------===//
3840// Meta Data Emission
3841//===----------------------------------------------------------------------===//
3842
Steve Naroffb29b4272008-04-14 22:03:09 +00003843void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003844 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003845 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003846
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003847 // Explicitly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003848 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003849 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003850 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003851 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003852 }
Mike Stump1eb44332009-09-09 15:08:12 +00003853
Chris Lattnerbe6df082007-12-12 07:56:42 +00003854 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003855 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003856 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003857 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003858 if (NumIvars > 0) {
3859 static bool objc_ivar = false;
3860 if (!objc_ivar) {
3861 /* struct _objc_ivar {
3862 char *ivar_name;
3863 char *ivar_type;
3864 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003865 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003866 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003867 Result += "\nstruct _objc_ivar {\n";
3868 Result += "\tchar *ivar_name;\n";
3869 Result += "\tchar *ivar_type;\n";
3870 Result += "\tint ivar_offset;\n";
3871 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003872
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003873 objc_ivar = true;
3874 }
3875
Steve Naroff946a6932008-03-11 00:12:29 +00003876 /* struct {
3877 int ivar_count;
3878 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003879 };
Steve Naroff946a6932008-03-11 00:12:29 +00003880 */
Mike Stump1eb44332009-09-09 15:08:12 +00003881 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003882 Result += "\tint ivar_count;\n";
3883 Result += "\tstruct _objc_ivar ivar_list[";
3884 Result += utostr(NumIvars);
3885 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003886 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003887 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003888 "{\n\t";
3889 Result += utostr(NumIvars);
3890 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003891
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003892 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003893 SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003894 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003895 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003896 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003897 IV != IVEnd; ++IV)
3898 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003899 IVI = IDecl->ivar_begin();
3900 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003901 } else {
3902 IVI = CDecl->ivar_begin();
3903 IVE = CDecl->ivar_end();
3904 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003905 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003906 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003907 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003908 std::string TmpString, StrEncoding;
3909 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3910 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003911 Result += StrEncoding;
3912 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003913 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003914 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003915 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003916 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003917 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003918 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003919 std::string TmpString, StrEncoding;
3920 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3921 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003922 Result += StrEncoding;
3923 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003924 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003925 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003926 }
Mike Stump1eb44332009-09-09 15:08:12 +00003927
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003928 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003929 }
Mike Stump1eb44332009-09-09 15:08:12 +00003930
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003931 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003932 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003933 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003934
3935 // If any of our property implementations have associated getters or
3936 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003937 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3938 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003939 Prop != PropEnd; ++Prop) {
3940 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3941 continue;
3942 if (!(*Prop)->getPropertyIvarDecl())
3943 continue;
3944 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3945 if (!PD)
3946 continue;
3947 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003948 if (!Getter->isDefined())
3949 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003950 if (PD->isReadOnly())
3951 continue;
3952 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003953 if (!Setter->isDefined())
3954 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003955 }
3956 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003957 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003958
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003959 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003960 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003961 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003962
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003963 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003964 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003965 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003966
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003967 // Declaration of class/meta-class metadata
3968 /* struct _objc_class {
3969 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003970 const char *super_class_name;
3971 char *name;
3972 long version;
3973 long info;
3974 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003975 struct _objc_ivar_list *ivars;
3976 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003977 struct objc_cache *cache;
3978 struct objc_protocol_list *protocols;
3979 const char *ivar_layout;
3980 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003981 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003982 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003983 static bool objc_class = false;
3984 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003985 Result += "\nstruct _objc_class {\n";
3986 Result += "\tstruct _objc_class *isa;\n";
3987 Result += "\tconst char *super_class_name;\n";
3988 Result += "\tchar *name;\n";
3989 Result += "\tlong version;\n";
3990 Result += "\tlong info;\n";
3991 Result += "\tlong instance_size;\n";
3992 Result += "\tstruct _objc_ivar_list *ivars;\n";
3993 Result += "\tstruct _objc_method_list *methods;\n";
3994 Result += "\tstruct objc_cache *cache;\n";
3995 Result += "\tstruct _objc_protocol_list *protocols;\n";
3996 Result += "\tconst char *ivar_layout;\n";
3997 Result += "\tstruct _objc_class_ext *ext;\n";
3998 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003999 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004000 }
Mike Stump1eb44332009-09-09 15:08:12 +00004001
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004002 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004003 ObjCInterfaceDecl *RootClass = 0;
4004 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004005 while (SuperClass) {
4006 RootClass = SuperClass;
4007 SuperClass = SuperClass->getSuperClass();
4008 }
4009 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00004010
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004011 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004012 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004013 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004014 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004015 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004016 Result += "\"";
4017
4018 if (SuperClass) {
4019 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004020 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004021 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004022 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004023 Result += "\"";
4024 }
4025 else {
4026 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004027 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004028 Result += "\"";
4029 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004030 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004031 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004032 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004033 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00004034 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004035 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004036 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004037 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004038 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004039 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00004040 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004041 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004042 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004043 Result += ",0,0\n";
4044 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00004045 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004046 Result += "\t,0,0,0,0\n";
4047 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004048
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004049 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004050 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004051 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004052 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004053 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004054 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004055 if (SuperClass) {
4056 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004057 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004058 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004059 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004060 Result += "\"";
4061 }
4062 else {
4063 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004064 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004065 Result += "\"";
4066 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004067 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004068 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004069 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004070 Result += ",0";
4071 else {
4072 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00004073 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004074 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00004075 if (LangOpts.MicrosoftExt)
Steve Naroffba9ac4e2008-03-10 23:33:22 +00004076 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004077 Result += ")";
4078 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004079 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00004080 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004081 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004082 Result += "\n\t";
4083 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004084 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004085 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004086 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00004087 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004088 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004089 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004090 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004091 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004092 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00004093 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004094 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004095 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004096 Result += ", 0,0\n";
4097 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004098 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004099 Result += ",0,0,0\n";
4100 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004101}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004102
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004103/// RewriteImplementations - This routine rewrites all method implementations
4104/// and emits meta-data.
4105
Steve Narofface66252008-11-13 20:07:04 +00004106void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004107 int ClsDefCount = ClassImplementation.size();
4108 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004109
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004110 // Rewrite implemented methods
4111 for (int i = 0; i < ClsDefCount; i++)
4112 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004113
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004114 for (int i = 0; i < CatDefCount; i++)
4115 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004116}
Mike Stump1eb44332009-09-09 15:08:12 +00004117
Steve Narofface66252008-11-13 20:07:04 +00004118void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4119 int ClsDefCount = ClassImplementation.size();
4120 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004121
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004122 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004123 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004124 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004125
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004126 // For each implemented category, write out all its meta data.
4127 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004128 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004129
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004130 // Write objc_symtab metadata
4131 /*
4132 struct _objc_symtab
4133 {
4134 long sel_ref_cnt;
4135 SEL *refs;
4136 short cls_def_cnt;
4137 short cat_def_cnt;
4138 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004139 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004140 */
Mike Stump1eb44332009-09-09 15:08:12 +00004141
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004142 Result += "\nstruct _objc_symtab {\n";
4143 Result += "\tlong sel_ref_cnt;\n";
4144 Result += "\tSEL *refs;\n";
4145 Result += "\tshort cls_def_cnt;\n";
4146 Result += "\tshort cat_def_cnt;\n";
4147 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4148 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004149
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004150 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004151 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004152 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004153 + ", " + utostr(CatDefCount) + "\n";
4154 for (int i = 0; i < ClsDefCount; i++) {
4155 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004156 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004157 Result += "\n";
4158 }
Mike Stump1eb44332009-09-09 15:08:12 +00004159
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004160 for (int i = 0; i < CatDefCount; i++) {
4161 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004162 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004163 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004164 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004165 Result += "\n";
4166 }
Mike Stump1eb44332009-09-09 15:08:12 +00004167
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004168 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004169
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004170 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004171
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004172 /*
4173 struct _objc_module {
4174 long version;
4175 long size;
4176 const char *name;
4177 struct _objc_symtab *symtab;
4178 }
4179 */
Mike Stump1eb44332009-09-09 15:08:12 +00004180
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004181 Result += "\nstruct _objc_module {\n";
4182 Result += "\tlong version;\n";
4183 Result += "\tlong size;\n";
4184 Result += "\tconst char *name;\n";
4185 Result += "\tstruct _objc_symtab *symtab;\n";
4186 Result += "};\n\n";
4187 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004188 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004189 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004190 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004191 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004192
Francois Pichet62ec1f22011-09-17 17:15:52 +00004193 if (LangOpts.MicrosoftExt) {
Steve Naroff621edce2009-04-29 16:37:50 +00004194 if (ProtocolExprDecls.size()) {
4195 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4196 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004197 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004198 E = ProtocolExprDecls.end(); I != E; ++I) {
4199 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4200 Result += (*I)->getNameAsString();
4201 Result += " = &_OBJC_PROTOCOL_";
4202 Result += (*I)->getNameAsString();
4203 Result += ";\n";
4204 }
4205 Result += "#pragma data_seg(pop)\n\n";
4206 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004207 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004208 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004209 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4210 Result += "&_OBJC_MODULES;\n";
4211 Result += "#pragma data_seg(pop)\n\n";
4212 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004213}
Chris Lattner311ff022007-10-16 22:36:42 +00004214
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004215void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4216 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004217 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004218 assert(BlockByRefDeclNo.count(VD) &&
4219 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004220 if (def)
4221 ResultStr += "struct ";
4222 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004223 "_" + utostr(BlockByRefDeclNo[VD]) ;
4224}
4225
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004226static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4227 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4228 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4229 return false;
4230}
4231
Steve Naroff54055232008-10-27 17:20:55 +00004232std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004233 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004234 std::string Tag) {
4235 const FunctionType *AFT = CE->getFunctionType();
4236 QualType RT = AFT->getResultType();
4237 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004238 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004239 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004240
Steve Naroff54055232008-10-27 17:20:55 +00004241 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004242
Douglas Gregor72564e72009-02-26 23:50:07 +00004243 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004244 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004245 // block (to reference imported block decl refs).
4246 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004247 } else if (BD->param_empty()) {
4248 S += "(" + StructRef + " *__cself)";
4249 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004250 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004251 assert(FT && "SynthesizeBlockFunc: No function proto");
4252 S += '(';
4253 // first add the implicit argument.
4254 S += StructRef + " *__cself, ";
4255 std::string ParamStr;
4256 for (BlockDecl::param_iterator AI = BD->param_begin(),
4257 E = BD->param_end(); AI != E; ++AI) {
4258 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004259 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004260 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004261 if (convertBlockPointerToFunctionPointer(QT))
4262 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004263 else
4264 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004265 S += ParamStr;
4266 }
4267 if (FT->isVariadic()) {
4268 if (!BD->param_empty()) S += ", ";
4269 S += "...";
4270 }
4271 S += ')';
4272 }
4273 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004274
Steve Naroff54055232008-10-27 17:20:55 +00004275 // Create local declarations to avoid rewriting all closure decl ref exprs.
4276 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004277 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004278 E = BlockByRefDecls.end(); I != E; ++I) {
4279 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004280 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004281 std::string TypeString;
4282 RewriteByRefString(TypeString, Name, (*I));
4283 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004284 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004285 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004286 }
Steve Naroff54055232008-10-27 17:20:55 +00004287 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004288 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004289 E = BlockByCopyDecls.end(); I != E; ++I) {
4290 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004291 // Handle nested closure invocation. For example:
4292 //
4293 // void (^myImportedClosure)(void);
4294 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004295 //
Steve Naroff54055232008-10-27 17:20:55 +00004296 // void (^anotherClosure)(void);
4297 // anotherClosure = ^(void) {
4298 // myImportedClosure(); // import and invoke the closure
4299 // };
4300 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004301 if (isTopLevelBlockPointerType((*I)->getType())) {
4302 RewriteBlockPointerTypeVariable(S, (*I));
4303 S += " = (";
4304 RewriteBlockPointerType(S, (*I)->getType());
4305 S += ")";
4306 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4307 }
4308 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004309 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004310 QualType QT = (*I)->getType();
4311 if (HasLocalVariableExternalStorage(*I))
4312 QT = Context->getPointerType(QT);
4313 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004314 S += Name + " = __cself->" +
4315 (*I)->getNameAsString() + "; // bound by copy\n";
4316 }
Steve Naroff54055232008-10-27 17:20:55 +00004317 }
4318 std::string RewrittenStr = RewrittenBlockExprs[CE];
4319 const char *cstr = RewrittenStr.c_str();
4320 while (*cstr++ != '{') ;
4321 S += cstr;
4322 S += "\n";
4323 return S;
4324}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004325
Steve Naroff54055232008-10-27 17:20:55 +00004326std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004327 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004328 std::string Tag) {
4329 std::string StructRef = "struct " + Tag;
4330 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004331
Steve Naroff54055232008-10-27 17:20:55 +00004332 S += funcName;
4333 S += "_block_copy_" + utostr(i);
4334 S += "(" + StructRef;
4335 S += "*dst, " + StructRef;
4336 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004337 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004338 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004339 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004340 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004341 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004342 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004343 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004344 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004345 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004346 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004347 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004348 else
4349 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004350 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004351 S += "}\n";
4352
Steve Naroff54055232008-10-27 17:20:55 +00004353 S += "\nstatic void __";
4354 S += funcName;
4355 S += "_block_dispose_" + utostr(i);
4356 S += "(" + StructRef;
4357 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004358 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004359 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004360 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004361 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004362 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004363 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004364 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004365 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004366 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004367 else
4368 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004369 }
Mike Stump1eb44332009-09-09 15:08:12 +00004370 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004371 return S;
4372}
4373
Steve Naroff01aec112009-12-06 21:14:13 +00004374std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4375 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004376 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004377 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004378
Steve Naroff54055232008-10-27 17:20:55 +00004379 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004380 S += " struct " + Desc;
4381 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004382
Steve Naroff01aec112009-12-06 21:14:13 +00004383 Constructor += "(void *fp, "; // Invoke function pointer.
4384 Constructor += "struct " + Desc; // Descriptor pointer.
4385 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004386
Steve Naroff54055232008-10-27 17:20:55 +00004387 if (BlockDeclRefs.size()) {
4388 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004389 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004390 E = BlockByCopyDecls.end(); I != E; ++I) {
4391 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004392 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004393 std::string ArgName = "_" + FieldName;
4394 // Handle nested closure invocation. For example:
4395 //
4396 // void (^myImportedBlock)(void);
4397 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004398 //
Steve Naroff54055232008-10-27 17:20:55 +00004399 // void (^anotherBlock)(void);
4400 // anotherBlock = ^(void) {
4401 // myImportedBlock(); // import and invoke the closure
4402 // };
4403 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004404 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004405 S += "struct __block_impl *";
4406 Constructor += ", void *" + ArgName;
4407 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004408 QualType QT = (*I)->getType();
4409 if (HasLocalVariableExternalStorage(*I))
4410 QT = Context->getPointerType(QT);
4411 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4412 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004413 Constructor += ", " + ArgName;
4414 }
4415 S += FieldName + ";\n";
4416 }
4417 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004418 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004419 E = BlockByRefDecls.end(); I != E; ++I) {
4420 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004421 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004422 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004423 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004424 std::string TypeString;
4425 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004426 TypeString += " *";
4427 FieldName = TypeString + FieldName;
4428 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004429 Constructor += ", " + ArgName;
4430 }
4431 S += FieldName + "; // by ref\n";
4432 }
4433 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004434 Constructor += ", int flags=0)";
4435 // Initialize all "by copy" arguments.
4436 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004437 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004438 E = BlockByCopyDecls.end(); I != E; ++I) {
4439 std::string Name = (*I)->getNameAsString();
4440 if (firsTime) {
4441 Constructor += " : ";
4442 firsTime = false;
4443 }
4444 else
4445 Constructor += ", ";
4446 if (isTopLevelBlockPointerType((*I)->getType()))
4447 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4448 else
4449 Constructor += Name + "(_" + Name + ")";
4450 }
4451 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004452 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004453 E = BlockByRefDecls.end(); I != E; ++I) {
4454 std::string Name = (*I)->getNameAsString();
4455 if (firsTime) {
4456 Constructor += " : ";
4457 firsTime = false;
4458 }
4459 else
4460 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004461 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004462 }
4463
4464 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004465 if (GlobalVarDecl)
4466 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4467 else
4468 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004469 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004470
Steve Naroff01aec112009-12-06 21:14:13 +00004471 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004472 } else {
4473 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004474 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004475 if (GlobalVarDecl)
4476 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4477 else
4478 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004479 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4480 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004481 }
4482 Constructor += " ";
4483 Constructor += "}\n";
4484 S += Constructor;
4485 S += "};\n";
4486 return S;
4487}
4488
Steve Naroff01aec112009-12-06 21:14:13 +00004489std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4490 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004491 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004492 unsigned hasCopy) {
4493 std::string S = "\nstatic struct " + DescTag;
4494
4495 S += " {\n unsigned long reserved;\n";
4496 S += " unsigned long Block_size;\n";
4497 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004498 S += " void (*copy)(struct ";
4499 S += ImplTag; S += "*, struct ";
4500 S += ImplTag; S += "*);\n";
4501
4502 S += " void (*dispose)(struct ";
4503 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004504 }
4505 S += "} ";
4506
4507 S += DescTag + "_DATA = { 0, sizeof(struct ";
4508 S += ImplTag + ")";
4509 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004510 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4511 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004512 }
4513 S += "};\n";
4514 return S;
4515}
4516
Steve Naroff54055232008-10-27 17:20:55 +00004517void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004518 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004519 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004520 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004521 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004522 bool RewriteSC = (GlobalVarDecl &&
4523 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004524 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004525 GlobalVarDecl->getType().getCVRQualifiers());
4526 if (RewriteSC) {
4527 std::string SC(" void __");
4528 SC += GlobalVarDecl->getNameAsString();
4529 SC += "() {}";
4530 InsertText(FunLocStart, SC);
4531 }
4532
Steve Naroff54055232008-10-27 17:20:55 +00004533 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004534 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4535 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004536 // Need to copy-in the inner copied-in variables not actually used in this
4537 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004538 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4539 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4540 ValueDecl *VD = Exp->getDecl();
4541 BlockDeclRefs.push_back(Exp);
4542 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4543 BlockByCopyDeclsPtrSet.insert(VD);
4544 BlockByCopyDecls.push_back(VD);
4545 }
4546 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4547 BlockByRefDeclsPtrSet.insert(VD);
4548 BlockByRefDecls.push_back(VD);
4549 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004550 // imported objects in the inner blocks not used in the outer
4551 // blocks must be copied/disposed in the outer block as well.
4552 if (Exp->isByRef() ||
4553 VD->getType()->isObjCObjectPointerType() ||
4554 VD->getType()->isBlockPointerType())
4555 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004556 }
Steve Naroff54055232008-10-27 17:20:55 +00004557
Daniel Dunbar4087f272010-08-17 22:39:59 +00004558 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4559 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004560
Steve Naroff01aec112009-12-06 21:14:13 +00004561 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004562
Benjamin Kramerd999b372010-02-14 14:14:16 +00004563 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004564
Steve Naroff01aec112009-12-06 21:14:13 +00004565 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004566
Benjamin Kramerd999b372010-02-14 14:14:16 +00004567 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004568
4569 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004570 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004571 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004572 }
Steve Naroff01aec112009-12-06 21:14:13 +00004573 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4574 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004575 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004576
Steve Naroff54055232008-10-27 17:20:55 +00004577 BlockDeclRefs.clear();
4578 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004579 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004580 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004581 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004582 ImportedBlockDecls.clear();
4583 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004584 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004585 // Must insert any 'const/volatile/static here. Since it has been
4586 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004587 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004588 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004589 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004590 if (GlobalVarDecl->getType().isConstQualified())
4591 SC += "const ";
4592 if (GlobalVarDecl->getType().isVolatileQualified())
4593 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004594 if (GlobalVarDecl->getType().isRestrictQualified())
4595 SC += "restrict ";
4596 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004597 }
4598
Steve Naroff54055232008-10-27 17:20:55 +00004599 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004600 InnerDeclRefsCount.clear();
4601 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004602 RewrittenBlockExprs.clear();
4603}
4604
4605void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4606 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00004607 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004608
Steve Naroff54055232008-10-27 17:20:55 +00004609 SynthesizeBlockLiterals(FunLocStart, FuncName);
4610}
4611
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004612static void BuildUniqueMethodName(std::string &Name,
4613 ObjCMethodDecl *MD) {
4614 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004615 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004616 Name += "__" + MD->getSelector().getAsString();
4617 // Convert colons to underscores.
4618 std::string::size_type loc = 0;
4619 while ((loc = Name.find(":", loc)) != std::string::npos)
4620 Name.replace(loc, 1, "_");
4621}
4622
Steve Naroff54055232008-10-27 17:20:55 +00004623void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004624 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4625 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004626 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004627 std::string FuncName;
4628 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004629 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004630}
4631
4632void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00004633 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00004634 if (*CI) {
4635 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4636 GetBlockDeclRefExprs(CBE->getBody());
4637 else
4638 GetBlockDeclRefExprs(*CI);
4639 }
4640 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004641 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004642 // FIXME: Handle enums.
4643 if (!isa<FunctionDecl>(CDRE->getDecl()))
4644 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004645 }
4646 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4647 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4648 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00004649 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4650 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004651 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004652 BlockDeclRefs.push_back(BDRE);
4653 }
4654
Steve Naroff54055232008-10-27 17:20:55 +00004655 return;
4656}
4657
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004658void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004659 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004660 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00004661 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004662 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004663 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4664 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004665 GetInnerBlockDeclRefExprs(CBE->getBody(),
4666 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004667 InnerContexts);
4668 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004669 else
4670 GetInnerBlockDeclRefExprs(*CI,
4671 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004672 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004673
4674 }
4675 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004676 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004677 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004678 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004679 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004680 }
4681 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4682 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4683 if (Var->isFunctionOrMethodVarDecl())
4684 ImportedLocalExternalDecls.insert(Var);
4685 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004686
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004687 return;
4688}
4689
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004690/// convertFunctionTypeOfBlocks - This routine converts a function type
4691/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00004692/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004693/// all block pointers to function pointers.
4694QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4695 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4696 // FTP will be null for closures that don't take arguments.
4697 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004698 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004699 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004700 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004701
4702 if (FTP) {
4703 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4704 E = FTP->arg_type_end(); I && (I != E); ++I) {
4705 QualType t = *I;
4706 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004707 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004708 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004709 ArgTypes.push_back(t);
4710 }
4711 }
4712 QualType FuncType;
4713 // FIXME. Does this work if block takes no argument but has a return type
4714 // which is of block type?
4715 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00004716 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004717 else FuncType = QualType(FT, 0);
4718 return FuncType;
4719}
4720
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004721Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004722 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004723 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004724
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004725 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004726 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004727 } else if (const BlockDeclRefExpr *CDRE =
4728 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004729 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004730 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004731 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004732 }
4733 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4734 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4735 }
4736 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4737 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4738 else if (const ConditionalOperator *CEXPR =
4739 dyn_cast<ConditionalOperator>(BlockExp)) {
4740 Expr *LHSExp = CEXPR->getLHS();
4741 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4742 Expr *RHSExp = CEXPR->getRHS();
4743 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4744 Expr *CONDExp = CEXPR->getCond();
4745 ConditionalOperator *CondExpr =
4746 new (Context) ConditionalOperator(CONDExp,
4747 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004748 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00004749 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004750 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004751 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4752 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004753 } else {
4754 assert(1 && "RewriteBlockClass: Bad type");
4755 }
4756 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004757 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004758 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004759 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004760 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004761
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004762 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004763 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004764 &Context->Idents.get("__block_impl"));
4765 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004766
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004767 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004768 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004769
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004770 // Push the block argument type.
4771 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004772 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004773 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004774 E = FTP->arg_type_end(); I && (I != E); ++I) {
4775 QualType t = *I;
4776 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004777 if (!convertBlockPointerToFunctionPointer(t))
4778 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004779 ArgTypes.push_back(t);
4780 }
Steve Naroff54055232008-10-27 17:20:55 +00004781 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004782 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00004783 QualType PtrToFuncCastType
4784 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004785
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004786 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004787
John McCall9d125032010-01-15 18:39:57 +00004788 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004789 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004790 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004791 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004792 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4793 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004794 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004795
Douglas Gregor44b43212008-12-11 16:49:14 +00004796 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004797 SourceLocation(),
4798 &Context->Idents.get("FuncPtr"),
4799 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004800 /*BitWidth=*/0, /*Mutable=*/true,
4801 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004802 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004803 FD->getType(), VK_LValue,
4804 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004805
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004806
John McCall9d125032010-01-15 18:39:57 +00004807 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004808 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004809 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004810
Chris Lattner5f9e2722011-07-23 10:55:15 +00004811 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004812 // Add the implicit argument.
4813 BlkExprs.push_back(BlkCast);
4814 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004815 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004816 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004817 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004818 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004819 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4820 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004821 Exp->getType(), VK_RValue,
4822 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004823 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004824}
4825
Steve Naroff621edce2009-04-29 16:37:50 +00004826// We need to return the rewritten expression to handle cases where the
4827// BlockDeclRefExpr is embedded in another expression being rewritten.
4828// For example:
4829//
4830// int main() {
4831// __block Foo *f;
4832// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004833//
Steve Naroff621edce2009-04-29 16:37:50 +00004834// void (^myblock)() = ^() {
4835// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4836// i = 77;
4837// };
4838//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004839Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004840 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004841 // for each DeclRefExp where BYREFVAR is name of the variable.
4842 ValueDecl *VD;
4843 bool isArrow = true;
4844 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4845 VD = BDRE->getDecl();
4846 else {
4847 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4848 isArrow = false;
4849 }
4850
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004851 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004852 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004853 &Context->Idents.get("__forwarding"),
4854 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004855 /*BitWidth=*/0, /*Mutable=*/true,
4856 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004857 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4858 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004859 FD->getType(), VK_LValue,
4860 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004861
Chris Lattner5f9e2722011-07-23 10:55:15 +00004862 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004863 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004864 &Context->Idents.get(Name),
4865 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004866 /*BitWidth=*/0, /*Mutable=*/true,
4867 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004868 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004869 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004870
4871
4872
Steve Naroffdf8570d2009-02-02 17:19:26 +00004873 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00004874 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4875 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004876 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004877 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004878 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004879}
4880
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004881// Rewrites the imported local variable V with external storage
4882// (static, extern, etc.) as *V
4883//
4884Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4885 ValueDecl *VD = DRE->getDecl();
4886 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4887 if (!ImportedLocalExternalDecls.count(Var))
4888 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004889 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4890 VK_LValue, OK_Ordinary,
4891 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004892 // Need parens to enforce precedence.
4893 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4894 Exp);
4895 ReplaceStmt(DRE, PE);
4896 return PE;
4897}
4898
Steve Naroffb2f9e512008-11-03 23:29:32 +00004899void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4900 SourceLocation LocStart = CE->getLParenLoc();
4901 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004902
4903 // Need to avoid trying to rewrite synthesized casts.
4904 if (LocStart.isInvalid())
4905 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004906 // Need to avoid trying to rewrite casts contained in macros.
4907 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4908 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004909
Steve Naroff54055232008-10-27 17:20:55 +00004910 const char *startBuf = SM->getCharacterData(LocStart);
4911 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004912 QualType QT = CE->getType();
4913 const Type* TypePtr = QT->getAs<Type>();
4914 if (isa<TypeOfExprType>(TypePtr)) {
4915 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4916 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4917 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004918 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004919 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004920 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004921 return;
4922 }
Steve Naroff54055232008-10-27 17:20:55 +00004923 // advance the location to startArgList.
4924 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004925
Steve Naroff54055232008-10-27 17:20:55 +00004926 while (*argPtr++ && (argPtr < endBuf)) {
4927 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004928 case '^':
4929 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004930 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004931 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004932 break;
Steve Naroff54055232008-10-27 17:20:55 +00004933 }
4934 }
4935 return;
4936}
4937
4938void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4939 SourceLocation DeclLoc = FD->getLocation();
4940 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004941
Steve Naroff54055232008-10-27 17:20:55 +00004942 // We have 1 or more arguments that have closure pointers.
4943 const char *startBuf = SM->getCharacterData(DeclLoc);
4944 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004945
Steve Naroff54055232008-10-27 17:20:55 +00004946 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004947
Steve Naroff54055232008-10-27 17:20:55 +00004948 parenCount++;
4949 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004950 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004951 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004952
Steve Naroff54055232008-10-27 17:20:55 +00004953 const char *argPtr = startArgList;
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 '^':
4958 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004959 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004960 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004961 break;
4962 case '(':
4963 parenCount++;
4964 break;
4965 case ')':
4966 parenCount--;
4967 break;
Steve Naroff54055232008-10-27 17:20:55 +00004968 }
4969 }
4970 return;
4971}
4972
4973bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004974 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004975 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004976 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004977 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004978 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004979 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004980 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004981 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004982 }
4983 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004984 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004985 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004986 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004987 return true;
4988 }
4989 return false;
4990}
4991
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004992bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4993 const FunctionProtoType *FTP;
4994 const PointerType *PT = QT->getAs<PointerType>();
4995 if (PT) {
4996 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4997 } else {
4998 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4999 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5000 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5001 }
5002 if (FTP) {
5003 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00005004 E = FTP->arg_type_end(); I != E; ++I) {
5005 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005006 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00005007 if ((*I)->isObjCObjectPointerType() &&
5008 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5009 return true;
5010 }
5011
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005012 }
5013 return false;
5014}
5015
Ted Kremenek8189cde2009-02-07 01:47:29 +00005016void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5017 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00005018 const char *argPtr = strchr(Name, '(');
5019 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00005020
Steve Naroff54055232008-10-27 17:20:55 +00005021 LParen = argPtr; // output the start.
5022 argPtr++; // skip past the left paren.
5023 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00005024
Steve Naroff54055232008-10-27 17:20:55 +00005025 while (*argPtr && parenCount) {
5026 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00005027 case '(': parenCount++; break;
5028 case ')': parenCount--; break;
5029 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00005030 }
5031 if (parenCount) argPtr++;
5032 }
5033 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5034 RParen = argPtr; // output the end
5035}
5036
5037void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5038 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5039 RewriteBlockPointerFunctionArgs(FD);
5040 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005041 }
Steve Naroff54055232008-10-27 17:20:55 +00005042 // Handle Variables and Typedefs.
5043 SourceLocation DeclLoc = ND->getLocation();
5044 QualType DeclT;
5045 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5046 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00005047 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00005048 DeclT = TDD->getUnderlyingType();
5049 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5050 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005051 else
David Blaikieb219cfc2011-09-23 05:06:16 +00005052 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00005053
Steve Naroff54055232008-10-27 17:20:55 +00005054 const char *startBuf = SM->getCharacterData(DeclLoc);
5055 const char *endBuf = startBuf;
5056 // scan backward (from the decl location) for the end of the previous decl.
5057 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5058 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00005059 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005060 std::string buf;
5061 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00005062 // *startBuf != '^' if we are dealing with a pointer to function that
5063 // may take block argument types (which will be handled below).
5064 if (*startBuf == '^') {
5065 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005066 buf = '*';
5067 startBuf++;
5068 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005069 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005070 while (*startBuf != ')') {
5071 buf += *startBuf;
5072 startBuf++;
5073 OrigLength++;
5074 }
5075 buf += ')';
5076 OrigLength++;
5077
5078 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5079 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00005080 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005081 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00005082 DeclLoc = ND->getLocation();
5083 startBuf = SM->getCharacterData(DeclLoc);
5084 const char *argListBegin, *argListEnd;
5085 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5086 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005087 if (*argListBegin == '^')
5088 buf += '*';
5089 else if (*argListBegin == '<') {
5090 buf += "/*";
5091 buf += *argListBegin++;
5092 OrigLength++;;
5093 while (*argListBegin != '>') {
5094 buf += *argListBegin++;
5095 OrigLength++;
5096 }
5097 buf += *argListBegin;
5098 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005099 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005100 else
5101 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005102 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005103 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005104 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005105 buf += ')';
5106 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005107 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005108 ReplaceText(Start, OrigLength, buf);
5109
Steve Naroff54055232008-10-27 17:20:55 +00005110 return;
5111}
5112
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005113
5114/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5115/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5116/// struct Block_byref_id_object *src) {
5117/// _Block_object_assign (&_dest->object, _src->object,
5118/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5119/// [|BLOCK_FIELD_IS_WEAK]) // object
5120/// _Block_object_assign(&_dest->object, _src->object,
5121/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5122/// [|BLOCK_FIELD_IS_WEAK]) // block
5123/// }
5124/// And:
5125/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5126/// _Block_object_dispose(_src->object,
5127/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5128/// [|BLOCK_FIELD_IS_WEAK]) // object
5129/// _Block_object_dispose(_src->object,
5130/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5131/// [|BLOCK_FIELD_IS_WEAK]) // block
5132/// }
5133
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005134std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5135 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005136 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005137 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005138 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005139 CopyDestroyCache.insert(flag);
5140 S = "static void __Block_byref_id_object_copy_";
5141 S += utostr(flag);
5142 S += "(void *dst, void *src) {\n";
5143
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005144 // offset into the object pointer is computed as:
5145 // void * + void* + int + int + void* + void *
5146 unsigned IntSize =
5147 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5148 unsigned VoidPtrSize =
5149 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5150
Ken Dyck0c4e5d62011-04-30 16:08:27 +00005151 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005152 S += " _Block_object_assign((char*)dst + ";
5153 S += utostr(offset);
5154 S += ", *(void * *) ((char*)src + ";
5155 S += utostr(offset);
5156 S += "), ";
5157 S += utostr(flag);
5158 S += ");\n}\n";
5159
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005160 S += "static void __Block_byref_id_object_dispose_";
5161 S += utostr(flag);
5162 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005163 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5164 S += utostr(offset);
5165 S += "), ";
5166 S += utostr(flag);
5167 S += ");\n}\n";
5168 return S;
5169}
5170
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005171/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5172/// the declaration into:
5173/// struct __Block_byref_ND {
5174/// void *__isa; // NULL for everything except __weak pointers
5175/// struct __Block_byref_ND *__forwarding;
5176/// int32_t __flags;
5177/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005178/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5179/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005180/// typex ND;
5181/// };
5182///
5183/// It then replaces declaration of ND variable with:
5184/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5185/// __size=sizeof(struct __Block_byref_ND),
5186/// ND=initializer-if-any};
5187///
5188///
5189void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005190 // Insert declaration for the function in which block literal is
5191 // used.
5192 if (CurFunctionDeclToDeclareForBlock)
5193 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005194 int flag = 0;
5195 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005196 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005197 if (DeclLoc.isInvalid())
5198 // If type location is missing, it is because of missing type (a warning).
5199 // Use variable's location which is good for this case.
5200 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005201 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005202 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00005203 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005204 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005205 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005206 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005207 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005208 ByrefType += " {\n";
5209 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005210 RewriteByRefString(ByrefType, Name, ND);
5211 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005212 ByrefType += " int __flags;\n";
5213 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005214 // Add void *__Block_byref_id_object_copy;
5215 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005216 QualType Ty = ND->getType();
5217 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5218 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005219 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5220 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005221 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005222
5223 QualType T = Ty;
5224 (void)convertBlockPointerToFunctionPointer(T);
5225 T.getAsStringInternal(Name, Context->PrintingPolicy);
5226
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005227 ByrefType += " " + Name + ";\n";
5228 ByrefType += "};\n";
5229 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005230 SourceLocation FunLocStart;
5231 if (CurFunctionDef)
5232 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5233 else {
5234 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5235 FunLocStart = CurMethodDef->getLocStart();
5236 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005237 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005238 if (Ty.isObjCGCWeak()) {
5239 flag |= BLOCK_FIELD_IS_WEAK;
5240 isa = 1;
5241 }
5242
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005243 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005244 flag = BLOCK_BYREF_CALLER;
5245 QualType Ty = ND->getType();
5246 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5247 if (Ty->isBlockPointerType())
5248 flag |= BLOCK_FIELD_IS_BLOCK;
5249 else
5250 flag |= BLOCK_FIELD_IS_OBJECT;
5251 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005252 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005253 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005254 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005255
5256 // struct __Block_byref_ND ND =
5257 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5258 // initializer-if-any};
5259 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005260 unsigned flags = 0;
5261 if (HasCopyAndDispose)
5262 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005263 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005264 ByrefType.clear();
5265 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005266 std::string ForwardingCastType("(");
5267 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005268 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005269 ByrefType += " " + Name + " = {(void*)";
5270 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005271 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005272 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005273 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005274 ByrefType += "sizeof(";
5275 RewriteByRefString(ByrefType, Name, ND);
5276 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005277 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005278 ByrefType += ", __Block_byref_id_object_copy_";
5279 ByrefType += utostr(flag);
5280 ByrefType += ", __Block_byref_id_object_dispose_";
5281 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005282 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005283 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005284 unsigned nameSize = Name.size();
5285 // for block or function pointer declaration. Name is aleady
5286 // part of the declaration.
5287 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5288 nameSize = 1;
5289 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005290 }
5291 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005292 SourceLocation startLoc;
5293 Expr *E = ND->getInit();
5294 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5295 startLoc = ECE->getLParenLoc();
5296 else
5297 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00005298 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005299 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005300 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005301 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005302 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005303 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005304 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005305 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005306 ByrefType += "sizeof(";
5307 RewriteByRefString(ByrefType, Name, ND);
5308 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005309 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005310 ByrefType += "__Block_byref_id_object_copy_";
5311 ByrefType += utostr(flag);
5312 ByrefType += ", __Block_byref_id_object_dispose_";
5313 ByrefType += utostr(flag);
5314 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005315 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005316 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005317
5318 // Complete the newly synthesized compound expression by inserting a right
5319 // curly brace before the end of the declaration.
5320 // FIXME: This approach avoids rewriting the initializer expression. It
5321 // also assumes there is only one declarator. For example, the following
5322 // isn't currently supported by this routine (in general):
5323 //
5324 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5325 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005326 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5327 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005328 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5329 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00005330 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005331
Benjamin Kramerd999b372010-02-14 14:14:16 +00005332 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005333 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005334 return;
5335}
5336
Mike Stump1eb44332009-09-09 15:08:12 +00005337void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005338 // Add initializers for any closure decl refs.
5339 GetBlockDeclRefExprs(Exp->getBody());
5340 if (BlockDeclRefs.size()) {
5341 // Unique all "by copy" declarations.
5342 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005343 if (!BlockDeclRefs[i]->isByRef()) {
5344 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5345 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5346 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5347 }
5348 }
Steve Naroff54055232008-10-27 17:20:55 +00005349 // Unique all "by ref" declarations.
5350 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5351 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005352 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5353 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5354 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5355 }
Steve Naroff54055232008-10-27 17:20:55 +00005356 }
5357 // Find any imported blocks...they will need special attention.
5358 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005359 if (BlockDeclRefs[i]->isByRef() ||
5360 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005361 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005362 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005363 }
5364}
5365
Chris Lattner5f9e2722011-07-23 10:55:15 +00005366FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005367 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005368 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005369 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5370 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00005371 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005372}
5373
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005374Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005375 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005376 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00005377 Blocks.push_back(Exp);
5378
5379 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005380
5381 // Add inner imported variables now used in current block.
5382 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005383 if (!InnerBlockDeclRefs.empty()) {
5384 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5385 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5386 ValueDecl *VD = Exp->getDecl();
5387 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005388 // We need to save the copied-in variables in nested
5389 // blocks because it is needed at the end for some of the API generations.
5390 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005391 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5392 BlockDeclRefs.push_back(Exp);
5393 BlockByCopyDeclsPtrSet.insert(VD);
5394 BlockByCopyDecls.push_back(VD);
5395 }
5396 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5397 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5398 BlockDeclRefs.push_back(Exp);
5399 BlockByRefDeclsPtrSet.insert(VD);
5400 BlockByRefDecls.push_back(VD);
5401 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005402 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005403 // Find any imported blocks...they will need special attention.
5404 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5405 if (InnerBlockDeclRefs[i]->isByRef() ||
5406 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5407 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5408 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005409 }
5410 InnerDeclRefsCount.push_back(countOfInnerDecls);
5411
Steve Narofffa15fd92008-10-28 20:29:00 +00005412 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005413
Steve Narofffa15fd92008-10-28 20:29:00 +00005414 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005415 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005416 else if (CurMethodDef)
5417 BuildUniqueMethodName(FuncName, CurMethodDef);
5418 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005419 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005420
Steve Narofffa15fd92008-10-28 20:29:00 +00005421 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005422
Steve Narofffa15fd92008-10-28 20:29:00 +00005423 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5424 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005425
Steve Narofffa15fd92008-10-28 20:29:00 +00005426 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005427 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5428 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005429
5430 FunctionDecl *FD;
5431 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005432
Steve Narofffa15fd92008-10-28 20:29:00 +00005433 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005434 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005435 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5436 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005437
Chris Lattner5f9e2722011-07-23 10:55:15 +00005438 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005439
Steve Narofffdc03722008-10-29 21:23:59 +00005440 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005441 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005442 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005443 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005444 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005445 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005446 InitExprs.push_back(castExpr);
5447
Steve Naroff01aec112009-12-06 21:14:13 +00005448 // Initialize the block descriptor.
5449 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005450
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005451 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5452 SourceLocation(), SourceLocation(),
5453 &Context->Idents.get(DescData.c_str()),
5454 Context->VoidPtrTy, 0,
5455 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005456 UnaryOperator *DescRefExpr =
5457 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5458 Context->VoidPtrTy,
5459 VK_LValue,
5460 SourceLocation()),
5461 UO_AddrOf,
5462 Context->getPointerType(Context->VoidPtrTy),
5463 VK_RValue, OK_Ordinary,
5464 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005465 InitExprs.push_back(DescRefExpr);
5466
Steve Narofffa15fd92008-10-28 20:29:00 +00005467 // Add initializers for any closure decl refs.
5468 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005469 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005470 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005471 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005472 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005473 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005474 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005475 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005476 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5477 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005478 if (HasLocalVariableExternalStorage(*I)) {
5479 QualType QT = (*I)->getType();
5480 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005481 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5482 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005483 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005484 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005485 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005486 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5487 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005488 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005489 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005490 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005491 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005492 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5493 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005494 if (HasLocalVariableExternalStorage(*I)) {
5495 QualType QT = (*I)->getType();
5496 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005497 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5498 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005499 }
5500
Steve Narofffa15fd92008-10-28 20:29:00 +00005501 }
Mike Stump1eb44332009-09-09 15:08:12 +00005502 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005503 }
5504 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005505 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005506 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005507 ValueDecl *ND = (*I);
5508 std::string Name(ND->getNameAsString());
5509 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005510 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005511 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5512 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005513 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005514 SourceLocation(), SourceLocation(),
5515 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005516 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5517 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5518
Daniel Dunbar4087f272010-08-17 22:39:59 +00005519 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005520 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5521 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005522 bool isNestedCapturedVar = false;
5523 if (block)
5524 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5525 ce = block->capture_end(); ci != ce; ++ci) {
5526 const VarDecl *variable = ci->getVariable();
5527 if (variable == ND && ci->isNested()) {
5528 assert (ci->isByRef() &&
5529 "SynthBlockInitExpr - captured block variable is not byref");
5530 isNestedCapturedVar = true;
5531 break;
5532 }
5533 }
5534 // captured nested byref variable has its address passed. Do not take
5535 // its address again.
5536 if (!isNestedCapturedVar)
5537 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005538 Context->getPointerType(Exp->getType()),
5539 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005540 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005541 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005542 }
5543 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005544 if (ImportedBlockDecls.size()) {
5545 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5546 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005547 unsigned IntSize =
5548 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005549 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5550 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005551 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005552 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005553 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005554 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005555 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005556 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005557 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005558 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005559 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005560 BlockDeclRefs.clear();
5561 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005562 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005563 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005564 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005565 ImportedBlockDecls.clear();
5566 return NewRep;
5567}
5568
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005569bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5570 if (const ObjCForCollectionStmt * CS =
5571 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5572 return CS->getElement() == DS;
5573 return false;
5574}
5575
Steve Narofffa15fd92008-10-28 20:29:00 +00005576//===----------------------------------------------------------------------===//
5577// Function Body / Expression rewriting
5578//===----------------------------------------------------------------------===//
5579
Steve Naroffc77a6362008-12-04 16:24:46 +00005580// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5581// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5582// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5583// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5584// Since the rewriter isn't capable of rewriting rewritten code, it's important
5585// we get this right.
5586void RewriteObjC::CollectPropertySetters(Stmt *S) {
5587 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005588 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffc77a6362008-12-04 16:24:46 +00005589 if (*CI)
5590 CollectPropertySetters(*CI);
5591
5592 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5593 if (BinOp->isAssignmentOp()) {
John McCall12f78a62010-12-02 01:19:52 +00005594 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5595 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005596 }
5597 }
5598}
5599
Steve Narofffa15fd92008-10-28 20:29:00 +00005600Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005601 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005602 isa<DoStmt>(S) || isa<ForStmt>(S))
5603 Stmts.push_back(S);
5604 else if (isa<ObjCForCollectionStmt>(S)) {
5605 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005606 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005607 }
Mike Stump1eb44332009-09-09 15:08:12 +00005608
Steve Narofffa15fd92008-10-28 20:29:00 +00005609 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005610
Steve Narofffa15fd92008-10-28 20:29:00 +00005611 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005612 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00005613 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005614 Stmt *newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005615 Stmt *ChildStmt = (*CI);
5616 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(ChildStmt)) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005617 Expr *OldBase = IvarRefExpr->getBase();
5618 bool replaced = false;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005619 newStmt = RewriteObjCNestedIvarRefExpr(ChildStmt, replaced);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005620 if (replaced) {
5621 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5622 ReplaceStmt(OldBase, IRE->getBase());
5623 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005624 ReplaceStmt(ChildStmt, newStmt);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005625 }
5626 }
5627 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005628 newStmt = RewriteFunctionBodyOrGlobalInitializer(ChildStmt);
5629 if (newStmt) {
5630 if (Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(ChildStmt))
5631 if (PropSetters[PropOrImplicitRefExpr] == S) {
5632 S = newStmt;
5633 newStmt = 0;
5634 }
5635 if (newStmt)
5636 *CI = newStmt;
5637 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005638 // If dealing with an assignment with LHS being a property reference
5639 // expression, the entire assignment tree is rewritten into a property
5640 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5641 // RHS again.
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005642 if (Expr *Exp = dyn_cast<Expr>(ChildStmt))
John McCall12f78a62010-12-02 01:19:52 +00005643 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005644 if (PropSetters[Exp]) {
5645 ++CI;
5646 continue;
5647 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005648 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005649 }
Mike Stump1eb44332009-09-09 15:08:12 +00005650
Steve Narofffa15fd92008-10-28 20:29:00 +00005651 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005652 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005653 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5654 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005655 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005656 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005657 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005658 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005659 Stmt *SaveCurrentBody = CurrentBody;
5660 CurrentBody = BE->getBody();
Fariborz Jahanian36178092011-04-08 23:48:29 +00005661 CollectPropertySetters(CurrentBody);
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005662 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005663 // block literal on rhs of a property-dot-sytax assignment
5664 // must be replaced by its synthesize ast so getRewrittenText
5665 // works as expected. In this case, what actually ends up on RHS
5666 // is the blockTranscribed which is the helper function for the
5667 // block literal; as in: self.c = ^() {[ace ARR];};
5668 bool saveDisableReplaceStmt = DisableReplaceStmt;
5669 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00005670 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005671 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005672 CurrentBody = SaveCurrentBody;
5673 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005674 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005675 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005676 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005677 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005678
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005679 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5680
Steve Narofffa15fd92008-10-28 20:29:00 +00005681 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005682 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005683 return blockTranscribed;
5684 }
5685 // Handle specific things.
5686 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5687 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005688
John McCall12f78a62010-12-02 01:19:52 +00005689 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005690 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5691 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5692
5693 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005694 if (BinOp) {
5695 // Because the rewriter doesn't allow us to rewrite rewritten code,
5696 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005697 DisableReplaceStmt = true;
5698 // Save the source range. Even if we disable the replacement, the
5699 // rewritten node will have been inserted into the tree. If the synthesized
5700 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005701 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005702 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5703 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005704 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005705 // Need to rewrite the ivar access expression if need be.
5706 if (isa<ObjCIvarRefExpr>(newStmt)) {
5707 bool replaced = false;
5708 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5709 }
5710
Steve Naroffb619d952008-12-09 12:56:34 +00005711 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005712 //
5713 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5714 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5715 // to see the original expression). Consider this example:
5716 //
5717 // Foo *obj1, *obj2;
5718 //
5719 // obj1.i = [obj2 rrrr];
5720 //
5721 // 'BinOp' for the previous expression looks like:
5722 //
5723 // (BinaryOperator 0x231ccf0 'int' '='
5724 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5725 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5726 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5727 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5728 //
5729 // 'newStmt' represents the rewritten message expression. For example:
5730 //
5731 // (CallExpr 0x231d300 'id':'struct objc_object *'
5732 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5733 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5734 // (CStyleCastExpr 0x231d220 'void *'
5735 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5736 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005737 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005738 // can be used as the setter argument. ReplaceStmt() will still 'see'
5739 // the original RHS (since we haven't altered BinOp).
5740 //
Mike Stump1eb44332009-09-09 15:08:12 +00005741 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005742 // node. As a result, we now leak the original AST nodes.
5743 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005744 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005745 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005746 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005747 }
5748 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005749
Steve Narofffa15fd92008-10-28 20:29:00 +00005750 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5751 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005752
Steve Narofffa15fd92008-10-28 20:29:00 +00005753 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5754 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005755
Steve Narofffa15fd92008-10-28 20:29:00 +00005756 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005757#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005758 // Before we rewrite it, put the original message expression in a comment.
5759 SourceLocation startLoc = MessExpr->getLocStart();
5760 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005761
Steve Narofffa15fd92008-10-28 20:29:00 +00005762 const char *startBuf = SM->getCharacterData(startLoc);
5763 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005764
Steve Narofffa15fd92008-10-28 20:29:00 +00005765 std::string messString;
5766 messString += "// ";
5767 messString.append(startBuf, endBuf-startBuf+1);
5768 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005769
5770 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005771 // InsertText(clang::SourceLocation, char const*, unsigned int).
5772 // InsertText(startLoc, messString.c_str(), messString.size());
5773 // Tried this, but it didn't work either...
5774 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005775#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005776 return RewriteMessageExpr(MessExpr);
5777 }
Mike Stump1eb44332009-09-09 15:08:12 +00005778
Steve Narofffa15fd92008-10-28 20:29:00 +00005779 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5780 return RewriteObjCTryStmt(StmtTry);
5781
5782 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5783 return RewriteObjCSynchronizedStmt(StmtTry);
5784
5785 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5786 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005787
Steve Narofffa15fd92008-10-28 20:29:00 +00005788 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5789 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005790
5791 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005792 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005793 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005794 OrigStmtRange.getEnd());
5795 if (BreakStmt *StmtBreakStmt =
5796 dyn_cast<BreakStmt>(S))
5797 return RewriteBreakStmt(StmtBreakStmt);
5798 if (ContinueStmt *StmtContinueStmt =
5799 dyn_cast<ContinueStmt>(S))
5800 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005801
5802 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005803 // and cast exprs.
5804 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5805 // FIXME: What we're doing here is modifying the type-specifier that
5806 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005807 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005808 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5809 // the context of an ObjCForCollectionStmt. For example:
5810 // NSArray *someArray;
5811 // for (id <FooProtocol> index in someArray) ;
5812 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5813 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005814 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005815 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005816
Steve Narofffa15fd92008-10-28 20:29:00 +00005817 // Blocks rewrite rules.
5818 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5819 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005820 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005821 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005822 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005823 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005824 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005825 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005826 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005827 if (VD->hasAttr<BlocksAttr>()) {
5828 static unsigned uniqueByrefDeclCount = 0;
5829 assert(!BlockByRefDeclNo.count(ND) &&
5830 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5831 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005832 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005833 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005834 else
5835 RewriteTypeOfDecl(VD);
5836 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005837 }
Richard Smith162e1c12011-04-15 14:24:37 +00005838 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005839 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005840 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005841 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005842 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5843 }
5844 }
5845 }
Mike Stump1eb44332009-09-09 15:08:12 +00005846
Steve Narofffa15fd92008-10-28 20:29:00 +00005847 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5848 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005849
5850 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005851 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5852 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005853 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5854 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005855 && "Statement stack mismatch");
5856 Stmts.pop_back();
5857 }
5858 // Handle blocks rewriting.
5859 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5860 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005861 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005862 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005863 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5864 ValueDecl *VD = DRE->getDecl();
5865 if (VD->hasAttr<BlocksAttr>())
5866 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005867 if (HasLocalVariableExternalStorage(VD))
5868 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005869 }
5870
Steve Narofffa15fd92008-10-28 20:29:00 +00005871 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005872 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005873 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005874 ReplaceStmt(S, BlockCall);
5875 return BlockCall;
5876 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005877 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005878 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005879 RewriteCastExpr(CE);
5880 }
5881#if 0
5882 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005883 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5884 ICE->getSubExpr(),
5885 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005886 // Get the new text.
5887 std::string SStr;
5888 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005889 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005890 const std::string &Str = Buf.str();
5891
5892 printf("CAST = %s\n", &Str[0]);
5893 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5894 delete S;
5895 return Replacement;
5896 }
5897#endif
5898 // Return this stmt unmodified.
5899 return S;
5900}
5901
Steve Naroff3d7e7862009-12-05 15:55:59 +00005902void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5903 for (RecordDecl::field_iterator i = RD->field_begin(),
5904 e = RD->field_end(); i != e; ++i) {
5905 FieldDecl *FD = *i;
5906 if (isTopLevelBlockPointerType(FD->getType()))
5907 RewriteBlockPointerDecl(FD);
5908 if (FD->getType()->isObjCQualifiedIdType() ||
5909 FD->getType()->isObjCQualifiedInterfaceType())
5910 RewriteObjCQualifiedInterfaceTypes(FD);
5911 }
5912}
5913
Steve Narofffa15fd92008-10-28 20:29:00 +00005914/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5915/// main file of the input.
5916void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5917 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005918 if (FD->isOverloadedOperator())
5919 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005920
Steve Narofffa15fd92008-10-28 20:29:00 +00005921 // Since function prototypes don't have ParmDecl's, we check the function
5922 // prototype. This enables us to rewrite function declarations and
5923 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005924 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005925
Sebastian Redld3a413d2009-04-26 20:35:05 +00005926 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005927 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005928 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005929 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005930 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005931 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005932 Body =
5933 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5934 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005935 CurrentBody = 0;
5936 if (PropParentMap) {
5937 delete PropParentMap;
5938 PropParentMap = 0;
5939 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005940 // This synthesizes and inserts the block "impl" struct, invoke function,
5941 // and any copy/dispose helper functions.
5942 InsertBlockLiteralsWithinFunction(FD);
5943 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005944 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005945 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005946 return;
5947 }
5948 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005949 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005950 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005951 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005952 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005953 Body =
5954 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5955 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005956 CurrentBody = 0;
5957 if (PropParentMap) {
5958 delete PropParentMap;
5959 PropParentMap = 0;
5960 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005961 InsertBlockLiteralsWithinMethod(MD);
5962 CurMethodDef = 0;
5963 }
5964 }
5965 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5966 ClassImplementation.push_back(CI);
5967 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5968 CategoryImplementation.push_back(CI);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005969 else if (isa<ObjCClassDecl>(D))
David Blaikieb219cfc2011-09-23 05:06:16 +00005970 llvm_unreachable("RewriteObjC::HandleDeclInMainFile - ObjCClassDecl");
Steve Narofffa15fd92008-10-28 20:29:00 +00005971 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5972 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005973 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005974 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005975 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005976 CheckFunctionPointerDecl(VD->getType(), VD);
5977 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005978 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005979 RewriteCastExpr(CE);
5980 }
5981 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005982 } else if (VD->getType()->isRecordType()) {
5983 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5984 if (RD->isDefinition())
5985 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005986 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005987 if (VD->getInit()) {
5988 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005989 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005990 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005991 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005992 CurrentBody = 0;
5993 if (PropParentMap) {
5994 delete PropParentMap;
5995 PropParentMap = 0;
5996 }
Mike Stump1eb44332009-09-09 15:08:12 +00005997 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005998 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005999 GlobalVarDecl = 0;
6000
6001 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00006002 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00006003 RewriteCastExpr(CE);
6004 }
6005 }
Steve Narofffa15fd92008-10-28 20:29:00 +00006006 return;
6007 }
Richard Smith162e1c12011-04-15 14:24:37 +00006008 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00006009 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00006010 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00006011 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00006012 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
6013 return;
6014 }
6015 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00006016 if (RD->isDefinition())
6017 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00006018 return;
6019 }
6020 // Nothing yet.
6021}
6022
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00006023void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00006024 if (Diags.hasErrorOccurred())
6025 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006026
Steve Narofffa15fd92008-10-28 20:29:00 +00006027 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00006028
Steve Naroff621edce2009-04-29 16:37:50 +00006029 // Here's a great place to add any extra declarations that may be needed.
6030 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00006031 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00006032 E = ProtocolExprDecls.end(); I != E; ++I)
6033 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
6034
Benjamin Kramerd999b372010-02-14 14:14:16 +00006035 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00006036 if (ClassImplementation.size() || CategoryImplementation.size())
6037 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00006038
Steve Narofffa15fd92008-10-28 20:29:00 +00006039 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6040 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00006041 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00006042 Rewrite.getRewriteBufferFor(MainFileID)) {
6043 //printf("Changed:\n");
6044 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6045 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00006046 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00006047 }
Steve Narofface66252008-11-13 20:07:04 +00006048
Steve Naroff621edce2009-04-29 16:37:50 +00006049 if (ClassImplementation.size() || CategoryImplementation.size() ||
6050 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00006051 // Rewrite Objective-c meta data*
6052 std::string ResultStr;
6053 SynthesizeMetaDataIntoBuffer(ResultStr);
6054 // Emit metadata.
6055 *OutFile << ResultStr;
6056 }
Steve Narofffa15fd92008-10-28 20:29:00 +00006057 OutFile->flush();
6058}