blob: 645883606a0fcc94a4ed0a6e074a4e8248fed903 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar9b414d32010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000035 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000036 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000037 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000041 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000042 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000043 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000044 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner2c64b7b2007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattner01c57482007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner5f9e2722011-07-23 10:55:15 +000070 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000072 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +000076 SmallVector<Stmt *, 32> Stmts;
77 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffd82a9ab2008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000084
Steve Naroffebf2b562007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Fariborz Jahanianb586cce2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Steve Naroff874e2322007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Steve Naroff621edce2009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Steve Naroffa7b402d2008-03-28 22:26:09 +0000115 std::string InFileName;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000116 raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000120
Steve Naroffba92b2e2008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000122
123 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000124 SmallVector<BlockExpr *, 32> Blocks;
125 SmallVector<int, 32> InnerDeclRefsCount;
126 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000127
Chris Lattner5f9e2722011-07-23 10:55:15 +0000128 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Steve Naroff54055232008-10-27 17:20:55 +0000130 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000131 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000133 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff54055232008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroffc77a6362008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000142 llvm::DenseMap<Expr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000145 llvm::DenseMap<Expr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Steve Naroff4c3580e2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000151
Steve Naroff54055232008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Steve Naroffb619d952008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Nick Lewycky7e749242010-10-31 21:07:24 +0000158 static const int OBJC_ABI_VERSION = 7;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000159 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattnerf04da132007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
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,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000175 Diagnostic &D, const LangOptions &LOpts,
176 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() &&
423 T->getPointeeType()->isObjCQualifiedInterfaceType())
424 T = Context->getObjCIdType();
425 }
426
Steve Naroff54055232008-10-27 17:20:55 +0000427 // FIXME: This predicate seems like it would be useful to add to ASTContext.
428 bool isObjCType(QualType T) {
429 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
430 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Steve Naroff54055232008-10-27 17:20:55 +0000432 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Steve Naroff54055232008-10-27 17:20:55 +0000434 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
435 OCT == Context->getCanonicalType(Context->getObjCClassType()))
436 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Ted Kremenek6217b802009-07-29 21:53:49 +0000438 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000439 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000440 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000441 return true;
442 }
443 return false;
444 }
445 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000446 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000447 void GetExtentOfArgList(const char *Name, const char *&LParen,
448 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000449 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Chris Lattner5f9e2722011-07-23 10:55:15 +0000451 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000452 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000453 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Steve Naroff621edce2009-04-29 16:37:50 +0000455 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000456 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000457 if (From[i] == '"')
458 To += "\\\"";
459 else
460 To += From[i];
461 }
462 }
John McCalle23cf432010-12-14 08:05:40 +0000463
464 QualType getSimpleFunctionType(QualType result,
465 const QualType *args,
466 unsigned numArgs,
467 bool variadic = false) {
468 FunctionProtoType::ExtProtoInfo fpi;
469 fpi.Variadic = variadic;
470 return Context->getFunctionType(result, args, numArgs, fpi);
471 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000472 };
John McCall9d125032010-01-15 18:39:57 +0000473
474 // Helper function: create a CStyleCastExpr with trivial type source info.
475 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000476 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000477 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +0000478 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallf871d0c2010-08-07 06:22:56 +0000479 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000480 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000481}
482
Mike Stump1eb44332009-09-09 15:08:12 +0000483void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
484 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000485 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000486 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000487 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000488 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000489 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000490 // All the args are checked/rewritten. Don't call twice!
491 RewriteBlockPointerDecl(D);
492 break;
493 }
494 }
495}
496
497void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000498 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000499 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000500 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000501}
502
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000503static bool IsHeaderFile(const std::string &Filename) {
504 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000506 if (DotPos == std::string::npos) {
507 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000508 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000509 }
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000511 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
512 // C header: .h
513 // C++ header: .hh or .H;
514 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000515}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000516
Chris Lattner5f9e2722011-07-23 10:55:15 +0000517RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000518 Diagnostic &D, const LangOptions &LOpts,
519 bool silenceMacroWarn)
520 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
521 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000522 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000523 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000524 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000525 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000526 "rewriter doesn't support user-specified control flow semantics "
527 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000528}
529
Eli Friedmanbce831b2009-05-18 22:29:17 +0000530ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000531 raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000532 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000533 const LangOptions &LOpts,
534 bool SilenceRewriteMacroWarning) {
535 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000536}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000537
Steve Naroffb29b4272008-04-14 22:03:09 +0000538void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000539 Context = &context;
540 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000541 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000542 MsgSendFunctionDecl = 0;
543 MsgSendSuperFunctionDecl = 0;
544 MsgSendStretFunctionDecl = 0;
545 MsgSendSuperStretFunctionDecl = 0;
546 MsgSendFpretFunctionDecl = 0;
547 GetClassFunctionDecl = 0;
548 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000549 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000550 SelGetUidFunctionDecl = 0;
551 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000552 ConstantStringClassReference = 0;
553 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000554 CurMethodDef = 0;
555 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000556 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000557 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000558 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000559 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000560 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000561 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000562 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000563 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000564 PropParentMap = 0;
565 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000566 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000567 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000569 // Get the ID and start/end of the main file.
570 MainFileID = SM->getMainFileID();
571 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
572 MainFileStart = MainBuf->getBufferStart();
573 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Chris Lattner2c78b872009-04-14 23:22:57 +0000575 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000577 // declaring objc_selector outside the parameter list removes a silly
578 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000579 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000580 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000581 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000582 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000583 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000584 if (LangOpts.Microsoft) {
585 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000586 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
587 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000588 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000589 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000590 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000591 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
592 Preamble += "typedef struct objc_object Protocol;\n";
593 Preamble += "#define _REWRITER_typedef_Protocol\n";
594 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000595 if (LangOpts.Microsoft) {
596 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
597 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
598 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000599 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000600 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000601 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000602 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000603 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000604 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000605 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000606 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000607 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000608 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000609 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000610 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000611 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000612 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
613 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000614 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000615 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000616 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
617 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
618 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
619 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
620 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000621 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000622 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000623 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
624 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
625 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000626 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
627 Preamble += "struct __objcFastEnumerationState {\n\t";
628 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000629 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000630 Preamble += "unsigned long *mutationsPtr;\n\t";
631 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000632 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000633 Preamble += "#define __FASTENUMERATIONSTATE\n";
634 Preamble += "#endif\n";
635 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
636 Preamble += "struct __NSConstantStringImpl {\n";
637 Preamble += " int *isa;\n";
638 Preamble += " int flags;\n";
639 Preamble += " char *str;\n";
640 Preamble += " long length;\n";
641 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000642 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
643 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
644 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000645 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000646 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000647 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
648 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000649 // Blocks preamble.
650 Preamble += "#ifndef BLOCK_IMPL\n";
651 Preamble += "#define BLOCK_IMPL\n";
652 Preamble += "struct __block_impl {\n";
653 Preamble += " void *isa;\n";
654 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000655 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000656 Preamble += " void *FuncPtr;\n";
657 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000658 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000659 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000660 Preamble += "extern \"C\" __declspec(dllexport) "
661 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000662 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
663 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
664 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
665 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000666 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
667 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000668 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
669 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
670 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000671 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000672 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000673 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
674 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000675 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000676 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000677 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000678 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000679 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000680 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000681 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000682 Preamble += "#define __weak\n";
683 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000684 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
685 // as this avoids warning in any 64bit/32bit compilation model.
686 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000687}
688
689
Chris Lattnerf04da132007-10-24 17:06:59 +0000690//===----------------------------------------------------------------------===//
691// Top Level Driver Code
692//===----------------------------------------------------------------------===//
693
Chris Lattner682bf922009-03-29 16:50:03 +0000694void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000695 if (Diags.hasErrorOccurred())
696 return;
697
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000698 // Two cases: either the decl could be in the main file, or it could be in a
699 // #included file. If the former, rewrite it now. If the later, check to see
700 // if we rewrote the #include/#import.
701 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000702 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000704 // If this is for a builtin, ignore it.
705 if (Loc.isInvalid()) return;
706
Steve Naroffebf2b562007-10-23 23:50:29 +0000707 // Look for built-in declarations that we need to refer during the rewrite.
708 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000709 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000710 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000711 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000712 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000713 ConstantStringClassReference = FVD;
714 return;
715 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000716 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000717 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000718 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000719 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000720 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000721 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000722 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000723 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000724 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000725 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
726 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000727 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
728 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000729 DI != DIEnd; ) {
730 if (isa<ObjCClassDecl>((*DI))) {
731 SmallVector<Decl *, 8> DG;
732 Decl *D = (*DI);
733 SourceLocation Loc = D->getLocation();
734 while (DI != DIEnd &&
735 isa<ObjCClassDecl>(D) && D->getLocation() == Loc) {
736 DG.push_back(D);
737 ++DI;
738 D = (*DI);
739 }
740 RewriteForwardClassDecl(DG);
741 continue;
742 }
Chris Lattner682bf922009-03-29 16:50:03 +0000743 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000744 ++DI;
745 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000746 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000747 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000748 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000749 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000750}
751
Chris Lattnerf04da132007-10-24 17:06:59 +0000752//===----------------------------------------------------------------------===//
753// Syntactic (non-AST) Rewriting Code
754//===----------------------------------------------------------------------===//
755
Steve Naroffb29b4272008-04-14 22:03:09 +0000756void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000757 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000758 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000759 const char *MainBufStart = MainBuf.begin();
760 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000761 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000763 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000764 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
765 if (*BufPtr == '#') {
766 if (++BufPtr == MainBufEnd)
767 return;
768 while (*BufPtr == ' ' || *BufPtr == '\t')
769 if (++BufPtr == MainBufEnd)
770 return;
771 if (!strncmp(BufPtr, "import", ImportLen)) {
772 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000773 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000774 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000775 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000776 BufPtr += ImportLen;
777 }
778 }
779 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000780}
781
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000782static std::string getIvarAccessString(ObjCIvarDecl *OID) {
783 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000784 std::string S;
785 S = "((struct ";
786 S += ClassDecl->getIdentifier()->getName();
787 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000788 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000789 return S;
790}
791
Steve Naroffa0876e82008-12-02 17:36:43 +0000792void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
793 ObjCImplementationDecl *IMD,
794 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000795 static bool objcGetPropertyDefined = false;
796 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000797 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000798 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000799 const char *startBuf = SM->getCharacterData(startLoc);
800 assert((*startBuf == '@') && "bogus @synthesize location");
801 const char *semiBuf = strchr(startBuf, ';');
802 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000803 SourceLocation onePastSemiLoc =
804 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000805
806 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
807 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Steve Naroffeb0646c2008-12-02 15:48:25 +0000809 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000810 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000811 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000813 if (!OID)
814 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000815 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000816 if (!PD->getGetterMethodDecl()->isDefined()) {
817 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
818 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
819 ObjCPropertyDecl::OBJC_PR_copy));
820 std::string Getr;
821 if (GenGetProperty && !objcGetPropertyDefined) {
822 objcGetPropertyDefined = true;
823 // FIXME. Is this attribute correct in all cases?
824 Getr = "\nextern \"C\" __declspec(dllimport) "
825 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000826 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000827 RewriteObjCMethodDecl(OID->getContainingInterface(),
828 PD->getGetterMethodDecl(), Getr);
829 Getr += "{ ";
830 // Synthesize an explicit cast to gain access to the ivar.
831 // See objc-act.c:objc_synthesize_new_getter() for details.
832 if (GenGetProperty) {
833 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
834 Getr += "typedef ";
835 const FunctionType *FPRetType = 0;
836 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
837 FPRetType);
838 Getr += " _TYPE";
839 if (FPRetType) {
840 Getr += ")"; // close the precedence "scope" for "*".
841
842 // Now, emit the argument types (if any).
843 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
844 Getr += "(";
845 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
846 if (i) Getr += ", ";
847 std::string ParamStr = FT->getArgType(i).getAsString(
848 Context->PrintingPolicy);
849 Getr += ParamStr;
850 }
851 if (FT->isVariadic()) {
852 if (FT->getNumArgs()) Getr += ", ";
853 Getr += "...";
854 }
855 Getr += ")";
856 } else
857 Getr += "()";
858 }
859 Getr += ";\n";
860 Getr += "return (_TYPE)";
861 Getr += "objc_getProperty(self, _cmd, ";
862 SynthesizeIvarOffsetComputation(OID, Getr);
863 Getr += ", 1)";
864 }
865 else
866 Getr += "return " + getIvarAccessString(OID);
867 Getr += "; }";
868 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000869 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000870
871 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000872 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Steve Naroffeb0646c2008-12-02 15:48:25 +0000874 // Generate the 'setter' function.
875 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000876 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
877 ObjCPropertyDecl::OBJC_PR_copy);
878 if (GenSetProperty && !objcSetPropertyDefined) {
879 objcSetPropertyDefined = true;
880 // FIXME. Is this attribute correct in all cases?
881 Setr = "\nextern \"C\" __declspec(dllimport) "
882 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
883 }
884
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000885 RewriteObjCMethodDecl(OID->getContainingInterface(),
886 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000887 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000888 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000889 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000890 if (GenSetProperty) {
891 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000892 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000893 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000894 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000895 Setr += ", ";
896 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
897 Setr += "0, ";
898 else
899 Setr += "1, ";
900 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
901 Setr += "1)";
902 else
903 Setr += "0)";
904 }
905 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000906 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000907 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000908 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000909 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000910 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000911}
Chris Lattner8a12c272007-10-11 18:38:32 +0000912
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000913static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
914 std::string &typedefString) {
915 typedefString += "#ifndef _REWRITER_typedef_";
916 typedefString += ForwardDecl->getNameAsString();
917 typedefString += "\n";
918 typedefString += "#define _REWRITER_typedef_";
919 typedefString += ForwardDecl->getNameAsString();
920 typedefString += "\n";
921 typedefString += "typedef struct objc_object ";
922 typedefString += ForwardDecl->getNameAsString();
923 typedefString += ";\n#endif\n";
924}
925
926void RewriteObjC::RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
927 const std::string &typedefString) {
928 SourceLocation startLoc = ClassDecl->getLocation();
929 const char *startBuf = SM->getCharacterData(startLoc);
930 const char *semiPtr = strchr(startBuf, ';');
931 // Replace the @class with typedefs corresponding to the classes.
932 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
933}
934
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000935void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000936 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000937 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
938 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(*I);
939 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
940 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000941 // Translate to typedef's that forward reference structs with the same name
942 // as the class. As a convenience, we include the original declaration
943 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000944 typedefString += "// @class ";
945 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000946 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000947 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000948 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000949 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000950 DeclGroupRef::iterator I = D.begin();
951 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(*I), typedefString);
952}
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000954void RewriteObjC::RewriteForwardClassDecl(
955 const llvm::SmallVector<Decl*, 8> &D) {
956 std::string typedefString;
957 for (unsigned i = 0; i < D.size(); i++) {
958 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(D[i]);
959 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
960 if (i == 0) {
961 typedefString += "// @class ";
962 typedefString += ForwardDecl->getNameAsString();
963 typedefString += ";\n";
964 }
965 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
966 }
967 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000968}
969
Steve Naroffb29b4272008-04-14 22:03:09 +0000970void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000971 // When method is a synthesized one, such as a getter/setter there is
972 // nothing to rewrite.
973 if (Method->isSynthesized())
974 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000975 SourceLocation LocStart = Method->getLocStart();
976 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000977
Chandler Carruth64211622011-07-25 21:09:52 +0000978 if (SM->getExpansionLineNumber(LocEnd) >
979 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000980 InsertText(LocStart, "#if 0\n");
981 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000982 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000983 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000984 }
985}
986
Mike Stump1eb44332009-09-09 15:08:12 +0000987void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000988 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Benjamin Kramerd999b372010-02-14 14:14:16 +0000990 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000991 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000992}
993
Steve Naroffb29b4272008-04-14 22:03:09 +0000994void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000995 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Steve Naroff423cb562007-10-30 13:30:57 +0000997 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000998 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Fariborz Jahanian13751e32010-02-10 01:15:09 +00001000 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1001 E = CatDecl->prop_end(); I != E; ++I)
1002 RewriteProperty(*I);
1003
Mike Stump1eb44332009-09-09 15:08:12 +00001004 for (ObjCCategoryDecl::instmeth_iterator
1005 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001006 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001007 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001008 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001009 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001010 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001011 RewriteMethodDeclaration(*I);
1012
Steve Naroff423cb562007-10-30 13:30:57 +00001013 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001014 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1015 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +00001016}
1017
Steve Naroffb29b4272008-04-14 22:03:09 +00001018void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +00001019 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Steve Naroff752d6ef2007-10-30 16:42:30 +00001021 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001022 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001023
1024 for (ObjCProtocolDecl::instmeth_iterator
1025 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001026 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001027 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001028 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001029 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001030 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001031 RewriteMethodDeclaration(*I);
1032
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001033 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1034 E = PDecl->prop_end(); I != E; ++I)
1035 RewriteProperty(*I);
1036
Steve Naroff752d6ef2007-10-30 16:42:30 +00001037 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001038 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001039 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001040
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001041 // Must comment out @optional/@required
1042 const char *startBuf = SM->getCharacterData(LocStart);
1043 const char *endBuf = SM->getCharacterData(LocEnd);
1044 for (const char *p = startBuf; p < endBuf; p++) {
1045 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001046 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001047 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001049 }
1050 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001051 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001052 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001054 }
1055 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001056}
1057
Steve Naroffb29b4272008-04-14 22:03:09 +00001058void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001059 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001060 if (LocStart.isInvalid())
1061 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001062 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001063 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001064}
1065
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001066void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1067 const FunctionType *&FPRetType) {
1068 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001069 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001070 else if (T->isFunctionPointerType() ||
1071 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001072 // needs special handling, since pointer-to-functions have special
1073 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001074 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001075 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001076 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001077 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001078 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001079 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001080 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001081 ResultStr += FPRetType->getResultType().getAsString(
1082 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001083 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001084 }
1085 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001086 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001087}
1088
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001089void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1090 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001091 std::string &ResultStr) {
1092 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1093 const FunctionType *FPRetType = 0;
1094 ResultStr += "\nstatic ";
1095 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001096 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001098 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001099 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001101 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001102 NameStr += "_I_";
1103 else
1104 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001106 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001107 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001108
1109 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001110 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001111 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001112 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001113 }
Mike Stump1eb44332009-09-09 15:08:12 +00001114 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001115 {
1116 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001117 int len = selString.size();
1118 for (int i = 0; i < len; i++)
1119 if (selString[i] == ':')
1120 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001121 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001122 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001123 // Remember this name for metadata emission
1124 MethodInternalNames[OMD] = NameStr;
1125 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001127 // Rewrite arguments
1128 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001130 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001131 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001132 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001133 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001134 if (!LangOpts.Microsoft) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001135 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001136 ResultStr += "struct ";
1137 }
1138 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001139 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001140 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001141 }
1142 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001143 ResultStr += Context->getObjCClassType().getAsString(
1144 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001146 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001147 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001148 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001150 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001151 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1152 E = OMD->param_end(); PI != E; ++PI) {
1153 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001154 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001155 if (PDecl->getType()->isObjCQualifiedIdType()) {
1156 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001157 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001158 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001159 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001160 QualType QT = PDecl->getType();
1161 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1162 if (convertBlockPointerToFunctionPointer(QT))
1163 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1164 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001165 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001166 ResultStr += Name;
1167 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001168 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001169 if (OMD->isVariadic())
1170 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001171 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Steve Naroff76e429d2008-07-16 14:40:40 +00001173 if (FPRetType) {
1174 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Steve Naroff76e429d2008-07-16 14:40:40 +00001176 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001177 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001178 ResultStr += "(";
1179 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1180 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001181 std::string ParamStr = FT->getArgType(i).getAsString(
1182 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001183 ResultStr += ParamStr;
1184 }
1185 if (FT->isVariadic()) {
1186 if (FT->getNumArgs()) ResultStr += ", ";
1187 ResultStr += "...";
1188 }
1189 ResultStr += ")";
1190 } else {
1191 ResultStr += "()";
1192 }
1193 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001194}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001195void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001196 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1197 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001199 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001201 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001202 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1203 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001204 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001205 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001206 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001207 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001208 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001209 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001210
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001211 const char *startBuf = SM->getCharacterData(LocStart);
1212 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001213 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001214 }
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001216 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001217 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1218 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001219 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001220 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001221 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001222 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001223 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001224 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001226 const char *startBuf = SM->getCharacterData(LocStart);
1227 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001228 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001229 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001230 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001231 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001232 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001233 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001234 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001235 }
1236
Benjamin Kramerd999b372010-02-14 14:14:16 +00001237 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001238}
1239
Steve Naroffb29b4272008-04-14 22:03:09 +00001240void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001241 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001242 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001243 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001244 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001245 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001246 ResultStr += "\n";
1247 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001248 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001249 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001250 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001251 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001252 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001253 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001254 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001255 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001256 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001257
1258 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001259 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001260 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001261 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001262 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001263 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001264 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001265 for (ObjCInterfaceDecl::classmeth_iterator
1266 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001267 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001268 RewriteMethodDeclaration(*I);
1269
Steve Naroff2feac5e2007-10-30 03:43:13 +00001270 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001271 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1272 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001273}
1274
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001275Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001276 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001277 ObjCMethodDecl *OMD = 0;
1278 QualType Ty;
1279 Selector Sel;
Duncan Sands54bd4572010-10-20 08:21:16 +00001280 Stmt *Receiver = 0;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001281 bool Super = false;
1282 QualType SuperTy;
1283 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001284 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001285 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001286 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCall12f78a62010-12-02 01:19:52 +00001287 if (ObjCPropertyRefExpr *PropRefExpr =
1288 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001289 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001290 if (PropRefExpr->isExplicitProperty()) {
1291 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1292 OMD = PDecl->getSetterMethodDecl();
1293 Ty = PDecl->getType();
1294 Sel = PDecl->getSetterName();
1295 } else {
1296 OMD = PropRefExpr->getImplicitPropertySetter();
1297 Sel = OMD->getSelector();
1298 Ty = PropRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001299 }
John McCall12f78a62010-12-02 01:19:52 +00001300 Super = PropRefExpr->isSuperReceiver();
1301 if (!Super) {
1302 Receiver = PropRefExpr->getBase();
1303 } else {
1304 SuperTy = PropRefExpr->getSuperReceiverType();
1305 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001306 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001307 }
1308
1309 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Chris Lattner5f9e2722011-07-23 10:55:15 +00001310 SmallVector<Expr *, 1> ExprVec;
Steve Naroffc77a6362008-12-04 16:24:46 +00001311 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001313 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001314 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001315 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001316 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001317 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001318 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001319 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001320 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001321 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001322 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001323 &ExprVec[0], 1,
1324 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001325 else {
1326 // FIXME. Refactor this into common code with that in
1327 // RewritePropertyOrImplicitGetter
1328 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1329 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1330 if (PropGetters[Exp])
1331 // This allows us to handle chain/nested property/implicit getters.
1332 Receiver = PropGetters[Exp];
1333
Douglas Gregor04badcf2010-04-21 00:45:42 +00001334 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001335 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001336 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001337 /*FIXME: */SourceLocation(),
1338 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001339 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001340 &ExprVec[0], 1,
1341 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001342 }
Steve Naroffc77a6362008-12-04 16:24:46 +00001343 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Steve Naroffc77a6362008-12-04 16:24:46 +00001345 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001346 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001347 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001348 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1349 // to things that stay around.
1350 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001351 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001352}
1353
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001354Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1355 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001356 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001357 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001358 ObjCMethodDecl *OMD = 0;
1359 QualType Ty;
1360 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001361 bool Super = false;
1362 QualType SuperTy;
1363 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001364 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001365 if (ObjCPropertyRefExpr *PropRefExpr =
1366 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001367 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001368 if (PropRefExpr->isExplicitProperty()) {
1369 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1370 OMD = PDecl->getGetterMethodDecl();
1371 Ty = PDecl->getType();
1372 Sel = PDecl->getGetterName();
1373 } else {
1374 OMD = PropRefExpr->getImplicitPropertyGetter();
1375 Sel = OMD->getSelector();
1376 Ty = PropRefExpr->getType();
1377 }
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001378 Super = PropRefExpr->isSuperReceiver();
1379 if (!Super)
1380 Receiver = PropRefExpr->getBase();
1381 else {
John McCall12f78a62010-12-02 01:19:52 +00001382 SuperTy = PropRefExpr->getSuperReceiverType();
1383 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001384 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001385 }
1386
1387 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1388
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001389 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001390 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001391 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001392 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001393 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001394 PropOrGetterRefExpr->getLocStart(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001395 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001396 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001397 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001398 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001399 0, 0,
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001400 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001401 else {
1402 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1403 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1404 if (PropGetters[Exp])
1405 // This allows us to handle chain/nested property/implicit getters.
1406 Receiver = PropGetters[Exp];
Douglas Gregor04badcf2010-04-21 00:45:42 +00001407 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001408 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001409 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001410 PropOrGetterRefExpr->getLocStart(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001411 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001412 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001413 0, 0,
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001414 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001415 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001416
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001417 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr, MsgExpr->getLocStart(),
1418 MsgExpr->getLocEnd());
Steve Naroff8599e7a2008-12-08 16:43:47 +00001419
1420 if (!PropParentMap)
1421 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001422 bool NestedPropertyRef = false;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001423 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001424 ImplicitCastExpr*ICE=0;
1425 if (Parent)
1426 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1427 assert((ICE->getCastKind() == CK_GetObjCProperty)
1428 && "RewritePropertyOrImplicitGetter");
1429 Parent = PropParentMap->getParent(Parent);
1430 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1431 }
1432 if (NestedPropertyRef) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001433 // We stash away the ReplacingStmt since actually doing the
1434 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001435 PropGetters[ICE] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001436 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1437 // to things that stay around.
1438 Context->Deallocate(MsgExpr);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001439 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001440 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001441 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001442 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001443 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1444 // to things that stay around.
1445 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001446 return ReplacingStmt;
1447 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001448}
1449
Mike Stump1eb44332009-09-09 15:08:12 +00001450Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001451 SourceLocation OrigStart,
1452 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001453 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001454 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001455 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001456 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001457 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001458 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001459 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001460 // lookup which class implements the instance variable.
1461 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001462 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001463 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001464 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Steve Narofff0757612008-05-08 17:52:16 +00001466 // Synthesize an explicit cast to gain access to the ivar.
1467 std::string RecName = clsDeclared->getIdentifier()->getName();
1468 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001469 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001470 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001471 SourceLocation(), SourceLocation(),
1472 II);
Steve Narofff0757612008-05-08 17:52:16 +00001473 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1474 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001475 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001476 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001477 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001478 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001479 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCallf89e55a2010-11-18 06:31:45 +00001480 IV->getBase()->getLocEnd(),
1481 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001482 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001483 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001484 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001485 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001486 IV->getLocation(),
1487 D->getType(),
1488 VK_LValue, OK_Ordinary);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001489 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001490 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001491 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001492 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001493 // Cannot delete IV->getBase(), since PE points to it.
1494 // Replace the old base with the cast. This is important when doing
1495 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001496 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001497 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001498 }
Steve Naroff84472a82008-04-18 21:55:08 +00001499 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001500 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Steve Naroff9f525972008-05-06 23:20:07 +00001502 // Explicit ivar refs need to have a cast inserted.
1503 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001504 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001505 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001506 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001507 // lookup which class implements the instance variable.
1508 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001509 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001510 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001511 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Steve Naroff9f525972008-05-06 23:20:07 +00001513 // Synthesize an explicit cast to gain access to the ivar.
1514 std::string RecName = clsDeclared->getIdentifier()->getName();
1515 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001516 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001517 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001518 SourceLocation(), SourceLocation(),
1519 II);
Steve Naroff9f525972008-05-06 23:20:07 +00001520 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1521 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001522 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001523 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001524 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001525 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001526 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001527 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001528 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001529 // Cannot delete IV->getBase(), since PE points to it.
1530 // Replace the old base with the cast. This is important when doing
1531 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001532 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001533 return IV;
1534 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001535 }
Steve Naroff84472a82008-04-18 21:55:08 +00001536 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001537}
1538
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001539Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
John McCall7502c1d2011-02-13 04:07:26 +00001540 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001541 if (*CI) {
1542 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1543 if (newStmt)
1544 *CI = newStmt;
1545 }
1546 }
1547 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1548 SourceRange OrigStmtRange = S->getSourceRange();
1549 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1550 replaced);
1551 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001552 }
1553 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1554 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1555 return newStmt;
1556 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001557 return S;
1558}
1559
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001560/// SynthCountByEnumWithState - To print:
1561/// ((unsigned int (*)
1562/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001563/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001564/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001565/// "countByEnumeratingWithState:objects:count:"),
1566/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001567/// (id *)items, (unsigned int)16)
1568///
Steve Naroffb29b4272008-04-14 22:03:09 +00001569void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001570 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1571 "id *, unsigned int))(void *)objc_msgSend)";
1572 buf += "\n\t\t";
1573 buf += "((id)l_collection,\n\t\t";
1574 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1575 buf += "\n\t\t";
1576 buf += "&enumState, "
1577 "(id *)items, (unsigned int)16)";
1578}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001579
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001580/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1581/// statement to exit to its outer synthesized loop.
1582///
Steve Naroffb29b4272008-04-14 22:03:09 +00001583Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001584 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1585 return S;
1586 // replace break with goto __break_label
1587 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001589 SourceLocation startLoc = S->getLocStart();
1590 buf = "goto __break_label_";
1591 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001592 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001593
1594 return 0;
1595}
1596
1597/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1598/// statement to continue with its inner synthesized loop.
1599///
Steve Naroffb29b4272008-04-14 22:03:09 +00001600Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001601 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1602 return S;
1603 // replace continue with goto __continue_label
1604 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001606 SourceLocation startLoc = S->getLocStart();
1607 buf = "goto __continue_label_";
1608 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001609 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001610
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001611 return 0;
1612}
1613
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001614/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001615/// It rewrites:
1616/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001618/// Into:
1619/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001620/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001621/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001622/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001623/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001624/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001625/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001626/// if (limit) {
1627/// unsigned long startMutations = *enumState.mutationsPtr;
1628/// do {
1629/// unsigned long counter = 0;
1630/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001631/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001632/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001633/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001634/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001635/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001636/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001637/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001638/// objects:items count:16]);
1639/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001640/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001641/// }
1642/// else
1643/// elem = nil;
1644/// }
1645///
Steve Naroffb29b4272008-04-14 22:03:09 +00001646Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001647 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001648 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001649 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001650 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001651 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001652 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001654 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001655 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001656 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001657 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001658 std::string buf;
1659 buf = "\n{\n\t";
1660 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1661 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001662 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001663 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001664 if (ElementType->isObjCQualifiedIdType() ||
1665 ElementType->isObjCQualifiedInterfaceType())
1666 // Simply use 'id' for all qualified types.
1667 elementTypeAsString = "id";
1668 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001669 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001670 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001671 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001672 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001673 buf += elementName;
1674 buf += ";\n\t";
1675 }
Chris Lattner06767512008-04-08 05:52:18 +00001676 else {
1677 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001678 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001679 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1680 if (VD->getType()->isObjCQualifiedIdType() ||
1681 VD->getType()->isObjCQualifiedInterfaceType())
1682 // Simply use 'id' for all qualified types.
1683 elementTypeAsString = "id";
1684 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001685 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001686 }
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001688 // struct __objcFastEnumerationState enumState = { 0 };
1689 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1690 // id items[16];
1691 buf += "id items[16];\n\t";
1692 // id l_collection = (id)
1693 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001694 // Find start location of 'collection' the hard way!
1695 const char *startCollectionBuf = startBuf;
1696 startCollectionBuf += 3; // skip 'for'
1697 startCollectionBuf = strchr(startCollectionBuf, '(');
1698 startCollectionBuf++; // skip '('
1699 // find 'in' and skip it.
1700 while (*startCollectionBuf != ' ' ||
1701 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1702 (*(startCollectionBuf+3) != ' ' &&
1703 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1704 startCollectionBuf++;
1705 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001706
1707 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001708 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001709 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001710 SourceLocation rightParenLoc = S->getRParenLoc();
1711 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1712 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001713 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001715 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1716 // objects:items count:16];
1717 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001718 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001719 // ((unsigned int (*)
1720 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001721 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001722 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001723 // "countByEnumeratingWithState:objects:count:"),
1724 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001725 // (id *)items, (unsigned int)16);
1726 buf += "unsigned long limit =\n\t\t";
1727 SynthCountByEnumWithState(buf);
1728 buf += ";\n\t";
1729 /// if (limit) {
1730 /// unsigned long startMutations = *enumState.mutationsPtr;
1731 /// do {
1732 /// unsigned long counter = 0;
1733 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001734 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001735 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001736 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001737 buf += "if (limit) {\n\t";
1738 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1739 buf += "do {\n\t\t";
1740 buf += "unsigned long counter = 0;\n\t\t";
1741 buf += "do {\n\t\t\t";
1742 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1743 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1744 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001745 buf += " = (";
1746 buf += elementTypeAsString;
1747 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001748 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001749 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001751 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001752 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001753 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001754 /// objects:items count:16]);
1755 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001756 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001757 /// }
1758 /// else
1759 /// elem = nil;
1760 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001761 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001762 buf = ";\n\t";
1763 buf += "__continue_label_";
1764 buf += utostr(ObjCBcLabelNo.back());
1765 buf += ": ;";
1766 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001767 buf += "} while (counter < limit);\n\t";
1768 buf += "} while (limit = ";
1769 SynthCountByEnumWithState(buf);
1770 buf += ");\n\t";
1771 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001772 buf += " = ((";
1773 buf += elementTypeAsString;
1774 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001775 buf += "__break_label_";
1776 buf += utostr(ObjCBcLabelNo.back());
1777 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001778 buf += "}\n\t";
1779 buf += "else\n\t\t";
1780 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001781 buf += " = ((";
1782 buf += elementTypeAsString;
1783 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001784 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001786 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001787 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001788 if (isa<CompoundStmt>(S->getBody())) {
1789 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001790 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001791 } else {
1792 /* Need to treat single statements specially. For example:
1793 *
1794 * for (A *a in b) if (stuff()) break;
1795 * for (A *a in b) xxxyy;
1796 *
1797 * The following code simply scans ahead to the semi to find the actual end.
1798 */
1799 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1800 const char *semiBuf = strchr(stmtBuf, ';');
1801 assert(semiBuf && "Can't find ';'");
1802 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001803 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001804 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001805 Stmts.pop_back();
1806 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001807 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001808}
1809
Mike Stump1eb44332009-09-09 15:08:12 +00001810/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001811/// This routine rewrites @synchronized(expr) stmt;
1812/// into:
1813/// objc_sync_enter(expr);
1814/// @try stmt @finally { objc_sync_exit(expr); }
1815///
Steve Naroffb29b4272008-04-14 22:03:09 +00001816Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001817 // Get the start location and compute the semi location.
1818 SourceLocation startLoc = S->getLocStart();
1819 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001821 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001822
1823 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001824 buf = "objc_sync_enter((id)";
1825 const char *lparenBuf = startBuf;
1826 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001827 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001828 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1829 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001830 // been rewritten! (which implies the SourceLocation's are invalid).
1831 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001832 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001833 while (*endBuf != ')') endBuf--;
1834 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001835 buf = ");\n";
1836 // declare a new scope with two variables, _stack and _rethrow.
1837 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1838 buf += "int buf[18/*32-bit i386*/];\n";
1839 buf += "char *pointers[4];} _stack;\n";
1840 buf += "id volatile _rethrow = 0;\n";
1841 buf += "objc_exception_try_enter(&_stack);\n";
1842 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001843 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001844 startLoc = S->getSynchBody()->getLocEnd();
1845 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Steve Naroffc7089f12008-08-19 13:04:19 +00001847 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001848 SourceLocation lastCurlyLoc = startLoc;
1849 buf = "}\nelse {\n";
1850 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001851 buf += "}\n";
1852 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001853 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001854
1855 std::string syncBuf;
1856 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001857 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00001858 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001859 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001860 std::string syncExprBufS;
1861 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001862 syncExpr->printPretty(syncExprBuf, *Context, 0,
1863 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001864 syncBuf += syncExprBuf.str();
1865 syncBuf += ");";
1866
1867 buf += syncBuf;
1868 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001869 buf += "}\n";
1870 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Benjamin Kramerd999b372010-02-14 14:14:16 +00001872 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001873
1874 bool hasReturns = false;
1875 HasReturnStmts(S->getSynchBody(), hasReturns);
1876 if (hasReturns)
1877 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1878
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001879 return 0;
1880}
1881
Steve Naroffb85e77a2009-12-05 21:43:12 +00001882void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1883{
Steve Naroff8c565152008-12-05 17:03:39 +00001884 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001885 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001886 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001887 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001888
Steve Naroffb85e77a2009-12-05 21:43:12 +00001889 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001890 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001891 TryFinallyContainsReturnDiag);
1892 }
1893 return;
1894}
1895
Steve Naroffb85e77a2009-12-05 21:43:12 +00001896void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1897{
1898 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001899 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001900 if (*CI)
1901 HasReturnStmts(*CI, hasReturns);
1902
1903 if (isa<ReturnStmt>(S))
1904 hasReturns = true;
1905 return;
1906}
1907
1908void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1909 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001910 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001911 if (*CI) {
1912 RewriteTryReturnStmts(*CI);
1913 }
1914 if (isa<ReturnStmt>(S)) {
1915 SourceLocation startLoc = S->getLocStart();
1916 const char *startBuf = SM->getCharacterData(startLoc);
1917
1918 const char *semiBuf = strchr(startBuf, ';');
1919 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1920 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1921
1922 std::string buf;
1923 buf = "{ objc_exception_try_exit(&_stack); return";
1924
Benjamin Kramerd999b372010-02-14 14:14:16 +00001925 ReplaceText(startLoc, 6, buf);
1926 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001927 }
1928 return;
1929}
1930
1931void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1932 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001933 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001934 if (*CI) {
1935 RewriteSyncReturnStmts(*CI, syncExitBuf);
1936 }
1937 if (isa<ReturnStmt>(S)) {
1938 SourceLocation startLoc = S->getLocStart();
1939 const char *startBuf = SM->getCharacterData(startLoc);
1940
1941 const char *semiBuf = strchr(startBuf, ';');
1942 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1943 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1944
1945 std::string buf;
1946 buf = "{ objc_exception_try_exit(&_stack);";
1947 buf += syncExitBuf;
1948 buf += " return";
1949
Benjamin Kramerd999b372010-02-14 14:14:16 +00001950 ReplaceText(startLoc, 6, buf);
1951 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001952 }
1953 return;
1954}
1955
Steve Naroffb29b4272008-04-14 22:03:09 +00001956Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001957 // Get the start location and compute the semi location.
1958 SourceLocation startLoc = S->getLocStart();
1959 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Steve Naroff75730982007-11-07 04:08:17 +00001961 assert((*startBuf == '@') && "bogus @try location");
1962
1963 std::string buf;
1964 // declare a new scope with two variables, _stack and _rethrow.
1965 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1966 buf += "int buf[18/*32-bit i386*/];\n";
1967 buf += "char *pointers[4];} _stack;\n";
1968 buf += "id volatile _rethrow = 0;\n";
1969 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001970 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001971
Benjamin Kramerd999b372010-02-14 14:14:16 +00001972 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Steve Naroff75730982007-11-07 04:08:17 +00001974 startLoc = S->getTryBody()->getLocEnd();
1975 startBuf = SM->getCharacterData(startLoc);
1976
1977 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Steve Naroff75730982007-11-07 04:08:17 +00001979 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001980 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001981 startLoc = startLoc.getFileLocWithOffset(1);
1982 buf = " /* @catch begin */ else {\n";
1983 buf += " id _caught = objc_exception_extract(&_stack);\n";
1984 buf += " objc_exception_try_enter (&_stack);\n";
1985 buf += " if (_setjmp(_stack.buf))\n";
1986 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1987 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001988
Benjamin Kramerd999b372010-02-14 14:14:16 +00001989 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001990 } else { /* no catch list */
1991 buf = "}\nelse {\n";
1992 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1993 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001994 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001995 }
Steve Naroff75730982007-11-07 04:08:17 +00001996 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001997 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1998 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001999 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00002000
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002001 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00002002 buf = "if ("; // we are generating code for the first catch clause
2003 else
2004 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002005 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00002006 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002007
Steve Naroff75730982007-11-07 04:08:17 +00002008 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Steve Naroff75730982007-11-07 04:08:17 +00002010 const char *lParenLoc = strchr(startBuf, '(');
2011
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002012 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00002013 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002014 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00002015 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2016 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002017 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00002018 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00002019 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Steve Naroffe12e6922008-02-01 20:02:07 +00002021 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00002022 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002023 } else if (catchDecl) {
2024 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002025 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00002026 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002027 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00002028 } else if (const ObjCObjectPointerType *Ptr =
2029 t->getAs<ObjCObjectPointerType>()) {
2030 // Should be a pointer to a class.
2031 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2032 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00002033 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00002034 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00002035 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002036 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00002037 }
2038 }
2039 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002040 lastCatchBody = Catch->getCatchBody();
2041 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00002042 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2043 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2044 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2045 assert((*rParenBuf == ')') && "bogus @catch paren location");
2046 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Mike Stump1eb44332009-09-09 15:08:12 +00002048 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002049 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002050 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002051 } else {
Steve Naroff75730982007-11-07 04:08:17 +00002052 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002053 }
Steve Naroff75730982007-11-07 04:08:17 +00002054 }
2055 // Complete the catch list...
2056 if (lastCatchBody) {
2057 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002058 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2059 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Steve Naroff378f47a2008-09-11 15:29:03 +00002061 // Insert the last (implicit) else clause *before* the right curly brace.
2062 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2063 buf = "} /* last catch end */\n";
2064 buf += "else {\n";
2065 buf += " _rethrow = _caught;\n";
2066 buf += " objc_exception_try_exit(&_stack);\n";
2067 buf += "} } /* @catch end */\n";
2068 if (!S->getFinallyStmt())
2069 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002070 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Steve Naroff75730982007-11-07 04:08:17 +00002072 // Set lastCurlyLoc
2073 lastCurlyLoc = lastCatchBody->getLocEnd();
2074 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002075 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002076 startLoc = finalStmt->getLocStart();
2077 startBuf = SM->getCharacterData(startLoc);
2078 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Benjamin Kramerd999b372010-02-14 14:14:16 +00002080 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Steve Naroff75730982007-11-07 04:08:17 +00002082 Stmt *body = finalStmt->getFinallyBody();
2083 SourceLocation startLoc = body->getLocStart();
2084 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002085 assert(*SM->getCharacterData(startLoc) == '{' &&
2086 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002087 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002088 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Steve Naroff75730982007-11-07 04:08:17 +00002090 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002091 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00002092 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002093 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Steve Naroff75730982007-11-07 04:08:17 +00002095 // Set lastCurlyLoc
2096 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Steve Naroff8c565152008-12-05 17:03:39 +00002098 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002099 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002100 } else { /* no finally clause - make sure we synthesize an implicit one */
2101 buf = "{ /* implicit finally clause */\n";
2102 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2103 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2104 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002105 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002106
2107 // Now check for any return/continue/go statements within the @try.
2108 // The implicit finally clause won't called if the @try contains any
2109 // jump statements.
2110 bool hasReturns = false;
2111 HasReturnStmts(S->getTryBody(), hasReturns);
2112 if (hasReturns)
2113 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002114 }
2115 // Now emit the final closing curly brace...
2116 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002117 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002118 return 0;
2119}
2120
Mike Stump1eb44332009-09-09 15:08:12 +00002121// This can't be done with ReplaceStmt(S, ThrowExpr), since
2122// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002123// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002124Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002125 // Get the start location and compute the semi location.
2126 SourceLocation startLoc = S->getLocStart();
2127 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Steve Naroff2bd03922007-11-07 15:32:26 +00002129 assert((*startBuf == '@') && "bogus @throw location");
2130
2131 std::string buf;
2132 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002133 if (S->getThrowExpr())
2134 buf = "objc_exception_throw(";
2135 else // add an implicit argument
2136 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002138 // handle "@ throw" correctly.
2139 const char *wBuf = strchr(startBuf, 'w');
2140 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002141 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Steve Naroff2bd03922007-11-07 15:32:26 +00002143 const char *semiBuf = strchr(startBuf, ';');
2144 assert((*semiBuf == ';') && "@throw: can't find ';'");
2145 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002146 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002147 return 0;
2148}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002149
Steve Naroffb29b4272008-04-14 22:03:09 +00002150Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002151 // Create a new string expression.
2152 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002153 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002154 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002155 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002156 StringLiteral::Ascii, false,
2157 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002158 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002159
Chris Lattner07506182007-11-30 22:53:43 +00002160 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002161 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002162 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002163}
2164
Steve Naroffb29b4272008-04-14 22:03:09 +00002165Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002166 if (!SelGetUidFunctionDecl)
2167 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002168 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2169 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002170 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002171 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002172 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002173 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002174 StringLiteral::Ascii, false,
2175 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002176 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2177 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002178 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002179 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002180 return SelExp;
2181}
2182
Steve Naroffb29b4272008-04-14 22:03:09 +00002183CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002184 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2185 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002186 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002187 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002188
Steve Naroffebf2b562007-10-23 23:50:29 +00002189 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002190 DeclRefExpr *DRE =
2191 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Steve Naroffebf2b562007-10-23 23:50:29 +00002193 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002194 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002195 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002196 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002197 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002198
John McCall183700f2009-09-21 23:43:11 +00002199 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002200
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002201 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002202 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002203 FT->getCallResultType(*Context),
2204 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002205 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002206}
2207
Steve Naroffd5255f52007-11-01 13:24:47 +00002208static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2209 const char *&startRef, const char *&endRef) {
2210 while (startBuf < endBuf) {
2211 if (*startBuf == '<')
2212 startRef = startBuf; // mark the start.
2213 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002214 if (startRef && *startRef == '<') {
2215 endRef = startBuf; // mark the end.
2216 return true;
2217 }
2218 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002219 }
2220 startBuf++;
2221 }
2222 return false;
2223}
2224
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002225static void scanToNextArgument(const char *&argRef) {
2226 int angle = 0;
2227 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2228 if (*argRef == '<')
2229 angle++;
2230 else if (*argRef == '>')
2231 angle--;
2232 argRef++;
2233 }
2234 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2235}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002236
Steve Naroffb29b4272008-04-14 22:03:09 +00002237bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002238 if (T->isObjCQualifiedIdType())
2239 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002240 if (const PointerType *PT = T->getAs<PointerType>()) {
2241 if (PT->getPointeeType()->isObjCQualifiedIdType())
2242 return true;
2243 }
2244 if (T->isObjCObjectPointerType()) {
2245 T = T->getPointeeType();
2246 return T->isObjCQualifiedInterfaceType();
2247 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002248 if (T->isArrayType()) {
2249 QualType ElemTy = Context->getBaseElementType(T);
2250 return needToScanForQualifiers(ElemTy);
2251 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002252 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002253}
2254
Steve Naroff4f95b752008-07-29 18:15:38 +00002255void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2256 QualType Type = E->getType();
2257 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002258 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002259
Steve Naroffcda658e2008-11-19 21:15:47 +00002260 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2261 Loc = ECE->getLParenLoc();
2262 EndLoc = ECE->getRParenLoc();
2263 } else {
2264 Loc = E->getLocStart();
2265 EndLoc = E->getLocEnd();
2266 }
2267 // This will defend against trying to rewrite synthesized expressions.
2268 if (Loc.isInvalid() || EndLoc.isInvalid())
2269 return;
2270
Steve Naroff4f95b752008-07-29 18:15:38 +00002271 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002272 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002273 const char *startRef = 0, *endRef = 0;
2274 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2275 // Get the locations of the startRef, endRef.
2276 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2277 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2278 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002279 InsertText(LessLoc, "/*");
2280 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002281 }
2282 }
2283}
2284
Steve Naroffb29b4272008-04-14 22:03:09 +00002285void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002286 SourceLocation Loc;
2287 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002288 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002289 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2290 Loc = VD->getLocation();
2291 Type = VD->getType();
2292 }
2293 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2294 Loc = FD->getLocation();
2295 // Check for ObjC 'id' and class types that have been adorned with protocol
2296 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002297 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002298 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002299 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002300 if (!proto)
2301 return;
2302 Type = proto->getResultType();
2303 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002304 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2305 Loc = FD->getLocation();
2306 Type = FD->getType();
2307 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002308 else
2309 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002311 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002312 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Steve Naroffd5255f52007-11-01 13:24:47 +00002314 const char *endBuf = SM->getCharacterData(Loc);
2315 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002316 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002317 startBuf--; // scan backward (from the decl location) for return type.
2318 const char *startRef = 0, *endRef = 0;
2319 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2320 // Get the locations of the startRef, endRef.
2321 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2322 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2323 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002324 InsertText(LessLoc, "/*");
2325 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002326 }
2327 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002328 if (!proto)
2329 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002330 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002331 const char *startBuf = SM->getCharacterData(Loc);
2332 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002333 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2334 if (needToScanForQualifiers(proto->getArgType(i))) {
2335 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002336
Steve Naroffd5255f52007-11-01 13:24:47 +00002337 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002338 // scan forward (from the decl location) for argument types.
2339 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002340 const char *startRef = 0, *endRef = 0;
2341 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2342 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002343 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002344 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002345 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002346 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002347 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002348 InsertText(LessLoc, "/*");
2349 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002350 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002351 startBuf = ++endBuf;
2352 }
2353 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002354 // If the function name is derived from a macro expansion, then the
2355 // argument buffer will not follow the name. Need to speak with Chris.
2356 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002357 startBuf++; // scan forward (from the decl location) for argument types.
2358 startBuf++;
2359 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002360 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002361}
2362
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002363void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2364 QualType QT = ND->getType();
2365 const Type* TypePtr = QT->getAs<Type>();
2366 if (!isa<TypeOfExprType>(TypePtr))
2367 return;
2368 while (isa<TypeOfExprType>(TypePtr)) {
2369 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2370 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2371 TypePtr = QT->getAs<Type>();
2372 }
2373 // FIXME. This will not work for multiple declarators; as in:
2374 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002375 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002376 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2377 const char *startBuf = SM->getCharacterData(DeclLoc);
2378 if (ND->getInit()) {
2379 std::string Name(ND->getNameAsString());
2380 TypeAsString += " " + Name + " = ";
2381 Expr *E = ND->getInit();
2382 SourceLocation startLoc;
2383 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2384 startLoc = ECE->getLParenLoc();
2385 else
2386 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002387 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002388 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002389 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002390 }
2391 else {
2392 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002393 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002394 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002395 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002396 }
2397}
2398
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002399// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002400void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002401 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002402 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002403 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002404 QualType getFuncType =
2405 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002406 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002407 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002408 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002409 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002410 SC_Extern,
2411 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002412}
2413
Steve Naroffb29b4272008-04-14 22:03:09 +00002414void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002415 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002416 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002417 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002418 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002419 return;
2420 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002421 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002422}
2423
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002424void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2425 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002426 const char *argPtr = TypeString.c_str();
2427 if (!strchr(argPtr, '^')) {
2428 Str += TypeString;
2429 return;
2430 }
2431 while (*argPtr) {
2432 Str += (*argPtr == '^' ? '*' : *argPtr);
2433 argPtr++;
2434 }
2435}
2436
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002437// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002438void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2439 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002440 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002441 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002442 const char *argPtr = TypeString.c_str();
2443 int paren = 0;
2444 while (*argPtr) {
2445 switch (*argPtr) {
2446 case '(':
2447 Str += *argPtr;
2448 paren++;
2449 break;
2450 case ')':
2451 Str += *argPtr;
2452 paren--;
2453 break;
2454 case '^':
2455 Str += '*';
2456 if (paren == 1)
2457 Str += VD->getNameAsString();
2458 break;
2459 default:
2460 Str += *argPtr;
2461 break;
2462 }
2463 argPtr++;
2464 }
2465}
2466
2467
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002468void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2469 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2470 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2471 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2472 if (!proto)
2473 return;
2474 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002475 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002476 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002477 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002478 FdStr += "(";
2479 unsigned numArgs = proto->getNumArgs();
2480 for (unsigned i = 0; i < numArgs; i++) {
2481 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002482 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002483 if (i+1 < numArgs)
2484 FdStr += ", ";
2485 }
2486 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002487 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002488 CurFunctionDeclToDeclareForBlock = 0;
2489}
2490
Steve Naroffc0a123c2008-03-11 17:37:02 +00002491// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002492void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002493 if (SuperContructorFunctionDecl)
2494 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002495 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002496 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002497 QualType argT = Context->getObjCIdType();
2498 assert(!argT.isNull() && "Can't find 'id' type");
2499 ArgTys.push_back(argT);
2500 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002501 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2502 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002503 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002504 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002505 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002506 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002507 SC_Extern,
2508 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002509}
2510
Steve Naroff09b266e2007-10-30 23:14:51 +00002511// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002512void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002513 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002514 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002515 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002516 assert(!argT.isNull() && "Can't find 'id' type");
2517 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002518 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002519 assert(!argT.isNull() && "Can't find 'SEL' type");
2520 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002521 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2522 &ArgTys[0], ArgTys.size(),
2523 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002524 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002525 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002526 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002527 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002528 SC_Extern,
2529 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002530}
2531
Steve Naroff874e2322007-11-15 10:28:18 +00002532// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002533void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002534 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002535 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002536 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002537 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002538 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002539 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2540 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2541 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002542 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002543 assert(!argT.isNull() && "Can't find 'SEL' type");
2544 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002545 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2546 &ArgTys[0], ArgTys.size(),
2547 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002548 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002549 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002550 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002551 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002552 SC_Extern,
2553 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002554}
2555
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002556// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002557void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002558 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002559 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002560 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002561 assert(!argT.isNull() && "Can't find 'id' type");
2562 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002563 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002564 assert(!argT.isNull() && "Can't find 'SEL' type");
2565 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002566 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2567 &ArgTys[0], ArgTys.size(),
2568 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002569 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002570 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002571 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002572 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002573 SC_Extern,
2574 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002575}
2576
Mike Stump1eb44332009-09-09 15:08:12 +00002577// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002578// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002579void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002580 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002581 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002582 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002583 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002584 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002585 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002586 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2587 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2588 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002589 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002590 assert(!argT.isNull() && "Can't find 'SEL' type");
2591 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002592 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2593 &ArgTys[0], ArgTys.size(),
2594 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002595 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002596 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002597 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002598 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002599 SC_Extern,
2600 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002601}
2602
Steve Naroff1284db82008-05-08 22:02:18 +00002603// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002604void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002605 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002606 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002607 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002608 assert(!argT.isNull() && "Can't find 'id' type");
2609 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002610 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002611 assert(!argT.isNull() && "Can't find 'SEL' type");
2612 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002613 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2614 &ArgTys[0], ArgTys.size(),
2615 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002616 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002617 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002618 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002619 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002620 SC_Extern,
2621 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002622}
2623
Steve Naroff09b266e2007-10-30 23:14:51 +00002624// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002625void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002626 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002627 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002628 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002629 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2630 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002631 GetClassFunctionDecl = 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 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002635 SC_Extern,
2636 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002637}
2638
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002639// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2640void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2641 IdentifierInfo *getSuperClassIdent =
2642 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002643 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002644 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002645 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2646 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002647 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002648 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002649 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002650 getSuperClassIdent,
2651 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002652 SC_Extern,
2653 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002654 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002655}
2656
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002657// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002658void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002659 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002660 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002661 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002662 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2663 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002664 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002665 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002666 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002667 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002668 SC_Extern,
2669 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002670}
2671
Steve Naroffb29b4272008-04-14 22:03:09 +00002672Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002673 QualType strType = getConstantStringStructType();
2674
2675 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002676
2677 std::string tmpName = InFileName;
2678 unsigned i;
2679 for (i=0; i < tmpName.length(); i++) {
2680 char c = tmpName.at(i);
2681 // replace any non alphanumeric characters with '_'.
2682 if (!isalpha(c) && (c < '0' || c > '9'))
2683 tmpName[i] = '_';
2684 }
2685 S += tmpName;
2686 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002687 S += utostr(NumObjCStringLiterals++);
2688
Steve Naroffba92b2e2008-03-27 22:29:16 +00002689 Preamble += "static __NSConstantStringImpl " + S;
2690 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2691 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002692 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002693 std::string prettyBufS;
2694 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002695 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2696 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002697 Preamble += prettyBuf.str();
2698 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002699 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002700
2701 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002702 SourceLocation(), &Context->Idents.get(S),
2703 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002704 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2705 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002706 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002707 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002708 VK_RValue, OK_Ordinary,
2709 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002710 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002711 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00002712 CK_BitCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002713 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002714 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002715 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002716}
2717
Steve Naroff874e2322007-11-15 10:28:18 +00002718// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002719QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002720 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002721 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002722 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002723 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002724 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002725
Steve Naroff874e2322007-11-15 10:28:18 +00002726 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002727 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002728 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002729 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002730
Steve Naroff874e2322007-11-15 10:28:18 +00002731 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002732 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002733 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002734 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002735 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002736 FieldTypes[i], 0,
2737 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002738 /*Mutable=*/false,
2739 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002740 }
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Douglas Gregor838db382010-02-11 01:19:42 +00002742 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002743 }
2744 return Context->getTagDeclType(SuperStructDecl);
2745}
2746
Steve Naroffb29b4272008-04-14 22:03:09 +00002747QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002748 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002749 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002750 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002751 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002752 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002753
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002754 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002755 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002756 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002757 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002758 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002759 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002760 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002761 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002762
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002763 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002764 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002765 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2766 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002767 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002768 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002769 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002770 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002771 /*Mutable=*/true,
2772 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002773 }
2774
Douglas Gregor838db382010-02-11 01:19:42 +00002775 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002776 }
2777 return Context->getTagDeclType(ConstantStringDecl);
2778}
2779
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002780Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2781 SourceLocation StartLoc,
2782 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002783 if (!SelGetUidFunctionDecl)
2784 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002785 if (!MsgSendFunctionDecl)
2786 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002787 if (!MsgSendSuperFunctionDecl)
2788 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002789 if (!MsgSendStretFunctionDecl)
2790 SynthMsgSendStretFunctionDecl();
2791 if (!MsgSendSuperStretFunctionDecl)
2792 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002793 if (!MsgSendFpretFunctionDecl)
2794 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002795 if (!GetClassFunctionDecl)
2796 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002797 if (!GetSuperClassFunctionDecl)
2798 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002799 if (!GetMetaClassFunctionDecl)
2800 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002801
Steve Naroff874e2322007-11-15 10:28:18 +00002802 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002803 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2804 // May need to use objc_msgSend_stret() as well.
2805 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002806 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2807 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002808 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002809 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002810 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002811 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002812 }
Mike Stump1eb44332009-09-09 15:08:12 +00002813
Steve Naroff934f2762007-10-24 22:48:43 +00002814 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002815 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002816 switch (Exp->getReceiverKind()) {
2817 case ObjCMessageExpr::SuperClass: {
2818 MsgSendFlavor = MsgSendSuperFunctionDecl;
2819 if (MsgSendStretFlavor)
2820 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2821 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002822
Douglas Gregor04badcf2010-04-21 00:45:42 +00002823 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002824
Chris Lattner5f9e2722011-07-23 10:55:15 +00002825 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002826
Douglas Gregor04badcf2010-04-21 00:45:42 +00002827 // set the receiver to self, the first argument to all methods.
2828 InitExprs.push_back(
2829 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002830 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002831 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002832 Context->getObjCIdType(),
2833 VK_RValue,
2834 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002835 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002836
Douglas Gregor04badcf2010-04-21 00:45:42 +00002837 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002838 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002839 QualType argType = Context->getPointerType(Context->CharTy);
2840 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002841 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002842 StringLiteral::Ascii, false,
2843 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002844 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2845 &ClsExprs[0],
2846 ClsExprs.size(),
2847 StartLoc,
2848 EndLoc);
2849 // (Class)objc_getClass("CurrentClass")
2850 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2851 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002852 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002853 ClsExprs.clear();
2854 ClsExprs.push_back(ArgExpr);
2855 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2856 &ClsExprs[0], ClsExprs.size(),
2857 StartLoc, EndLoc);
2858
2859 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2860 // To turn off a warning, type-cast to 'id'
2861 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2862 NoTypeInfoCStyleCastExpr(Context,
2863 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002864 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002865 // struct objc_super
2866 QualType superType = getSuperStructType();
2867 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002868
Douglas Gregor04badcf2010-04-21 00:45:42 +00002869 if (LangOpts.Microsoft) {
2870 SynthSuperContructorFunctionDecl();
2871 // Simulate a contructor call...
2872 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002873 superType, VK_LValue,
2874 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002875 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2876 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002877 superType, VK_LValue,
2878 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002879 // The code for super is a little tricky to prevent collision with
2880 // the structure definition in the header. The rewriter has it's own
2881 // internal definition (__rw_objc_super) that is uses. This is why
2882 // we need the cast below. For example:
2883 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2884 //
John McCall2de56d12010-08-25 11:45:40 +00002885 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002886 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002887 VK_RValue, OK_Ordinary,
2888 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002889 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2890 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002891 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002892 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002893 // (struct objc_super) { <exprs from above> }
2894 InitListExpr *ILE =
2895 new (Context) InitListExpr(*Context, SourceLocation(),
2896 &InitExprs[0], InitExprs.size(),
2897 SourceLocation());
2898 TypeSourceInfo *superTInfo
2899 = Context->getTrivialTypeSourceInfo(superType);
2900 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002901 superType, VK_LValue,
2902 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002903 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002904 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002905 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002906 VK_RValue, OK_Ordinary,
2907 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002908 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002909 MsgExprs.push_back(SuperRep);
2910 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002911 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002912
2913 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002914 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002915 QualType argType = Context->getPointerType(Context->CharTy);
2916 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002917 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002918 IdentifierInfo *clsName = Class->getIdentifier();
2919 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002920 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002921 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002922 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002923 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2924 &ClsExprs[0],
2925 ClsExprs.size(),
2926 StartLoc, EndLoc);
2927 MsgExprs.push_back(Cls);
2928 break;
2929 }
2930
2931 case ObjCMessageExpr::SuperInstance:{
2932 MsgSendFlavor = MsgSendSuperFunctionDecl;
2933 if (MsgSendStretFlavor)
2934 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2935 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2936 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002937 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002938
2939 InitExprs.push_back(
2940 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002941 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002942 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002943 Context->getObjCIdType(),
2944 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002945 ); // set the 'receiver'.
2946
2947 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002948 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002949 QualType argType = Context->getPointerType(Context->CharTy);
2950 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002951 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002952 StringLiteral::Ascii, false, argType,
2953 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002954 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2955 &ClsExprs[0],
2956 ClsExprs.size(),
2957 StartLoc, EndLoc);
2958 // (Class)objc_getClass("CurrentClass")
2959 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2960 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002961 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002962 ClsExprs.clear();
2963 ClsExprs.push_back(ArgExpr);
2964 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2965 &ClsExprs[0], ClsExprs.size(),
2966 StartLoc, EndLoc);
2967
2968 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2969 // To turn off a warning, type-cast to 'id'
2970 InitExprs.push_back(
2971 // set 'super class', using class_getSuperclass().
2972 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002973 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002974 // struct objc_super
2975 QualType superType = getSuperStructType();
2976 Expr *SuperRep;
2977
2978 if (LangOpts.Microsoft) {
2979 SynthSuperContructorFunctionDecl();
2980 // Simulate a contructor call...
2981 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002982 superType, VK_LValue,
2983 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002984 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2985 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002986 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002987 // The code for super is a little tricky to prevent collision with
2988 // the structure definition in the header. The rewriter has it's own
2989 // internal definition (__rw_objc_super) that is uses. This is why
2990 // we need the cast below. For example:
2991 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2992 //
John McCall2de56d12010-08-25 11:45:40 +00002993 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002994 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002995 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002996 SourceLocation());
2997 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2998 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002999 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003000 } else {
3001 // (struct objc_super) { <exprs from above> }
3002 InitListExpr *ILE =
3003 new (Context) InitListExpr(*Context, SourceLocation(),
3004 &InitExprs[0], InitExprs.size(),
3005 SourceLocation());
3006 TypeSourceInfo *superTInfo
3007 = Context->getTrivialTypeSourceInfo(superType);
3008 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003009 superType, VK_RValue, ILE,
3010 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003011 }
3012 MsgExprs.push_back(SuperRep);
3013 break;
3014 }
3015
3016 case ObjCMessageExpr::Instance: {
3017 // Remove all type-casts because it may contain objc-style types; e.g.
3018 // Foo<Proto> *.
3019 Expr *recExpr = Exp->getInstanceReceiver();
3020 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3021 recExpr = CE->getSubExpr();
3022 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00003023 CK_BitCast, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003024 MsgExprs.push_back(recExpr);
3025 break;
3026 }
3027 }
3028
Steve Naroffbeaf2992007-11-03 11:27:19 +00003029 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003030 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00003031 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00003032 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00003033 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00003034 StringLiteral::Ascii, false,
3035 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00003036 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003037 &SelExprs[0], SelExprs.size(),
3038 StartLoc,
3039 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00003040 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003041
Steve Naroff934f2762007-10-24 22:48:43 +00003042 // Now push any user supplied arguments.
3043 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00003044 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00003045 // Make all implicit casts explicit...ICE comes in handy:-)
3046 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3047 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00003048 QualType type = ICE->getType();
3049 if (needToScanForQualifiers(type))
3050 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003051 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003052 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00003053 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3054 bool integral = SubExpr->getType()->isIntegralType(*Context);
3055 userExpr = NoTypeInfoCStyleCastExpr(Context, type,
3056 (integral && type->isBooleanType())
3057 ? CK_IntegralToBoolean : CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003058 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003059 }
3060 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003061 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003062 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003063 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003064 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00003065 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00003066 CK_BitCast, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003067 }
Mike Stump1eb44332009-09-09 15:08:12 +00003068 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003069 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003070 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3071 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003072 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003073 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003074 }
Steve Naroffab972d32007-11-04 22:37:50 +00003075 // Generate the funky cast.
3076 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003077 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00003078 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003079
Steve Naroffab972d32007-11-04 22:37:50 +00003080 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003081 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3082 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3083 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003084 ArgTypes.push_back(Context->getObjCIdType());
3085 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003086 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003087 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003088 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3089 E = OMD->param_end(); PI != E; ++PI) {
3090 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003091 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003092 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003093 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003094 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003095 ArgTypes.push_back(t);
3096 }
Chris Lattner89951a82009-02-20 18:43:26 +00003097 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3098 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003099 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003100 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003101 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003102 }
3103 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003104 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Steve Naroffab972d32007-11-04 22:37:50 +00003106 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003107 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003108 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003109
Mike Stump1eb44332009-09-09 15:08:12 +00003110 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003111 // If we don't do this cast, we get the following bizarre warning/note:
3112 // xx.m:13: warning: function called through a non-compatible type
3113 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003114 cast = NoTypeInfoCStyleCastExpr(Context,
3115 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003116 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003117
Steve Naroffab972d32007-11-04 22:37:50 +00003118 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003119 QualType castType =
3120 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3121 // If we don't have a method decl, force a variadic cast.
3122 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003123 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003124 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003125 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003126
3127 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003128 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003129
John McCall183700f2009-09-21 23:43:11 +00003130 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003131 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003132 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003133 FT->getResultType(), VK_RValue,
3134 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003135 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003136 if (MsgSendStretFlavor) {
3137 // We have the method which returns a struct/union. Must also generate
3138 // call to objc_msgSend_stret and hang both varieties on a conditional
3139 // expression which dictate which one to envoke depending on size of
3140 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003141
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003142 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003143 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003144 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003145 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003146 cast = NoTypeInfoCStyleCastExpr(Context,
3147 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003148 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003149 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003150 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3151 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003152 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003153 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003154 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003155
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003156 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003157 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003158
John McCall183700f2009-09-21 23:43:11 +00003159 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003160 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003161 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003162 FT->getResultType(), VK_RValue,
3163 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003164
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003165 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003166 UnaryExprOrTypeTraitExpr *sizeofExpr =
3167 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3168 Context->getTrivialTypeSourceInfo(returnType),
3169 Context->getSizeType(), SourceLocation(),
3170 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003171 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3172 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3173 // For X86 it is more complicated and some kind of target specific routine
3174 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003175 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003176 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003177 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3178 llvm::APInt(IntSize, 8),
3179 Context->IntTy,
3180 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003181 BinaryOperator *lessThanExpr =
3182 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3183 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003184 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003185 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003186 new (Context) ConditionalOperator(lessThanExpr,
3187 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003188 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003189 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003190 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3191 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003192 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003193 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003194 return ReplacingStmt;
3195}
3196
Steve Naroffb29b4272008-04-14 22:03:09 +00003197Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003198 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3199 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003200
Steve Naroff934f2762007-10-24 22:48:43 +00003201 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003202 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003203
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003204 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003205 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003206}
3207
Steve Naroff621edce2009-04-29 16:37:50 +00003208// typedef struct objc_object Protocol;
3209QualType RewriteObjC::getProtocolType() {
3210 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003211 TypeSourceInfo *TInfo
3212 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003213 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003214 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003215 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003216 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003217 }
3218 return Context->getTypeDeclType(ProtocolTypeDecl);
3219}
3220
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003221/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003222/// a synthesized/forward data reference (to the protocol's metadata).
3223/// The forward references (and metadata) are generated in
3224/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003225Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003226 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3227 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003228 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003229 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003230 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003231 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3232 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003233 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003234 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003235 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003236 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003237 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003238 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003239 ReplaceStmt(Exp, castExpr);
3240 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003241 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003242 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003243
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003244}
3245
Mike Stump1eb44332009-09-09 15:08:12 +00003246bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003247 const char *endBuf) {
3248 while (startBuf < endBuf) {
3249 if (*startBuf == '#') {
3250 // Skip whitespace.
3251 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3252 ;
3253 if (!strncmp(startBuf, "if", strlen("if")) ||
3254 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3255 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3256 !strncmp(startBuf, "define", strlen("define")) ||
3257 !strncmp(startBuf, "undef", strlen("undef")) ||
3258 !strncmp(startBuf, "else", strlen("else")) ||
3259 !strncmp(startBuf, "elif", strlen("elif")) ||
3260 !strncmp(startBuf, "endif", strlen("endif")) ||
3261 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3262 !strncmp(startBuf, "include", strlen("include")) ||
3263 !strncmp(startBuf, "import", strlen("import")) ||
3264 !strncmp(startBuf, "include_next", strlen("include_next")))
3265 return true;
3266 }
3267 startBuf++;
3268 }
3269 return false;
3270}
3271
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003272/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003273/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003274void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003275 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003276 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003277 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003278 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003279 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003280 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003281 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003282 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003283 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003284 SourceLocation LocStart = CDecl->getLocStart();
3285 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003286
Steve Narofffea763e82007-11-14 19:25:57 +00003287 const char *startBuf = SM->getCharacterData(LocStart);
3288 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003289
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003290 // If no ivars and no root or if its root, directly or indirectly,
3291 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003292 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3293 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003294 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003295 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003296 return;
3297 }
Mike Stump1eb44332009-09-09 15:08:12 +00003298
3299 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003300 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003301 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003302 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003303 if (LangOpts.Microsoft)
3304 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003305
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003306 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003307 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003308 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003309 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003310 // If the buffer contains preprocessor directives, we do more fine-grained
3311 // rewrites. This is intended to fix code that looks like (which occurs in
3312 // NSURL.h, for example):
3313 //
3314 // #ifdef XYZ
3315 // @interface Foo : NSObject
3316 // #else
3317 // @interface FooBar : NSObject
3318 // #endif
3319 // {
3320 // int i;
3321 // }
3322 // @end
3323 //
3324 // This clause is segregated to avoid breaking the common case.
3325 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003326 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003327 CDecl->getClassLoc();
3328 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003329 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003330
Chris Lattnercafeb352009-02-20 18:18:36 +00003331 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003332 // advance to the end of the referenced protocols.
3333 while (endHeader < cursor && *endHeader != '>') endHeader++;
3334 endHeader++;
3335 }
3336 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003337 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003338 } else {
3339 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003340 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003341 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003342 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003343 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003344 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003345 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003346 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003347 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003348
Steve Narofffea763e82007-11-14 19:25:57 +00003349 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003350 SourceLocation OnePastCurly =
3351 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003352 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003353 }
3354 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003355
Steve Narofffea763e82007-11-14 19:25:57 +00003356 // Now comment out any visibility specifiers.
3357 while (cursor < endBuf) {
3358 if (*cursor == '@') {
3359 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003360 // Skip whitespace.
3361 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3362 /*scan*/;
3363
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003364 // FIXME: presence of @public, etc. inside comment results in
3365 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003366 if (!strncmp(cursor, "public", strlen("public")) ||
3367 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003368 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003369 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003370 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003371 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003372 // FIXME: If there are cases where '<' is used in ivar declaration part
3373 // of user code, then scan the ivar list and use needToScanForQualifiers
3374 // for type checking.
3375 else if (*cursor == '<') {
3376 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003377 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003378 cursor = strchr(cursor, '>');
3379 cursor++;
3380 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003381 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003382 } else if (*cursor == '^') { // rewrite block specifier.
3383 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003384 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003385 }
Steve Narofffea763e82007-11-14 19:25:57 +00003386 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003387 }
Steve Narofffea763e82007-11-14 19:25:57 +00003388 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003389 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003390 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003391 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003392 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003393 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003394 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003395 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003396 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003397 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003398 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003399 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003400 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003401 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003402}
3403
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003404// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003405/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003406template<typename MethodIterator>
3407void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3408 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003409 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003410 StringRef prefix,
3411 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003412 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003413 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003414
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003415 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003416 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003417 SEL _cmd;
3418 char *method_types;
3419 void *_imp;
3420 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003421 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003422 Result += "\nstruct _objc_method {\n";
3423 Result += "\tSEL _cmd;\n";
3424 Result += "\tchar *method_types;\n";
3425 Result += "\tvoid *_imp;\n";
3426 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003427
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003428 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003429 }
Mike Stump1eb44332009-09-09 15:08:12 +00003430
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003431 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003432
Steve Naroff946a6932008-03-11 00:12:29 +00003433 /* struct {
3434 struct _objc_method_list *next_method;
3435 int method_count;
3436 struct _objc_method method_list[];
3437 }
3438 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003439 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003440 Result += "\nstatic struct {\n";
3441 Result += "\tstruct _objc_method_list *next_method;\n";
3442 Result += "\tint method_count;\n";
3443 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003444 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003445 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003446 Result += prefix;
3447 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3448 Result += "_METHODS_";
3449 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003450 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003451 Result += IsInstanceMethod ? "inst" : "cls";
3452 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003453 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003454
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003455 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003456 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003457 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003458 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003459 Result += "\", \"";
3460 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003461 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003462 Result += MethodInternalNames[*MethodBegin];
3463 Result += "}\n";
3464 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3465 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003466 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003467 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003468 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003469 Result += "\", \"";
3470 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003471 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003472 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003473 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003474 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003475 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003476}
3477
Steve Naroff621edce2009-04-29 16:37:50 +00003478/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003479void RewriteObjC::
Chris Lattner5f9e2722011-07-23 10:55:15 +00003480RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, StringRef prefix,
3481 StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003482 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003483
3484 // Output struct protocol_methods holder of method selector and type.
3485 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3486 /* struct protocol_methods {
3487 SEL _cmd;
3488 char *method_types;
3489 }
3490 */
3491 Result += "\nstruct _protocol_methods {\n";
3492 Result += "\tstruct objc_selector *_cmd;\n";
3493 Result += "\tchar *method_types;\n";
3494 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003495
Steve Naroff621edce2009-04-29 16:37:50 +00003496 objc_protocol_methods = true;
3497 }
3498 // Do not synthesize the protocol more than once.
3499 if (ObjCSynthesizedProtocols.count(PDecl))
3500 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003501
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003502 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3503 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3504 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003505 /* struct _objc_protocol_method_list {
3506 int protocol_method_count;
3507 struct protocol_methods protocols[];
3508 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003509 */
Steve Naroff621edce2009-04-29 16:37:50 +00003510 Result += "\nstatic struct {\n";
3511 Result += "\tint protocol_method_count;\n";
3512 Result += "\tstruct _protocol_methods protocol_methods[";
3513 Result += utostr(NumMethods);
3514 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3515 Result += PDecl->getNameAsString();
3516 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3517 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003518
Steve Naroff621edce2009-04-29 16:37:50 +00003519 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003520 for (ObjCProtocolDecl::instmeth_iterator
3521 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003522 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003523 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003524 Result += "\t ,{{(struct objc_selector *)\"";
3525 else
3526 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003527 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003528 std::string MethodTypeString;
3529 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3530 Result += "\", \"";
3531 Result += MethodTypeString;
3532 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003533 }
Steve Naroff621edce2009-04-29 16:37:50 +00003534 Result += "\t }\n};\n";
3535 }
Mike Stump1eb44332009-09-09 15:08:12 +00003536
Steve Naroff621edce2009-04-29 16:37:50 +00003537 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003538 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3539 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003540 if (NumMethods > 0) {
3541 /* struct _objc_protocol_method_list {
3542 int protocol_method_count;
3543 struct protocol_methods protocols[];
3544 }
3545 */
3546 Result += "\nstatic struct {\n";
3547 Result += "\tint protocol_method_count;\n";
3548 Result += "\tstruct _protocol_methods protocol_methods[";
3549 Result += utostr(NumMethods);
3550 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3551 Result += PDecl->getNameAsString();
3552 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3553 "{\n\t";
3554 Result += utostr(NumMethods);
3555 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003556
Steve Naroff621edce2009-04-29 16:37:50 +00003557 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003558 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003559 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003560 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003561 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003562 Result += "\t ,{{(struct objc_selector *)\"";
3563 else
3564 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003565 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003566 std::string MethodTypeString;
3567 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3568 Result += "\", \"";
3569 Result += MethodTypeString;
3570 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003571 }
Steve Naroff621edce2009-04-29 16:37:50 +00003572 Result += "\t }\n};\n";
3573 }
3574
3575 // Output:
3576 /* struct _objc_protocol {
3577 // Objective-C 1.0 extensions
3578 struct _objc_protocol_extension *isa;
3579 char *protocol_name;
3580 struct _objc_protocol **protocol_list;
3581 struct _objc_protocol_method_list *instance_methods;
3582 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003583 };
Steve Naroff621edce2009-04-29 16:37:50 +00003584 */
3585 static bool objc_protocol = false;
3586 if (!objc_protocol) {
3587 Result += "\nstruct _objc_protocol {\n";
3588 Result += "\tstruct _objc_protocol_extension *isa;\n";
3589 Result += "\tchar *protocol_name;\n";
3590 Result += "\tstruct _objc_protocol **protocol_list;\n";
3591 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3592 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003593 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003594
Steve Naroff621edce2009-04-29 16:37:50 +00003595 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003596 }
Mike Stump1eb44332009-09-09 15:08:12 +00003597
Steve Naroff621edce2009-04-29 16:37:50 +00003598 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3599 Result += PDecl->getNameAsString();
3600 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3601 "{\n\t0, \"";
3602 Result += PDecl->getNameAsString();
3603 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003604 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003605 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3606 Result += PDecl->getNameAsString();
3607 Result += ", ";
3608 }
3609 else
3610 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003611 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003612 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3613 Result += PDecl->getNameAsString();
3614 Result += "\n";
3615 }
3616 else
3617 Result += "0\n";
3618 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003619
Steve Naroff621edce2009-04-29 16:37:50 +00003620 // Mark this protocol as having been generated.
3621 if (!ObjCSynthesizedProtocols.insert(PDecl))
3622 assert(false && "protocol already synthesized");
3623
3624}
3625
3626void RewriteObjC::
3627RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003628 StringRef prefix, StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003629 std::string &Result) {
3630 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003631
Steve Naroff621edce2009-04-29 16:37:50 +00003632 for (unsigned i = 0; i != Protocols.size(); i++)
3633 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3634
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003635 // Output the top lovel protocol meta-data for the class.
3636 /* struct _objc_protocol_list {
3637 struct _objc_protocol_list *next;
3638 int protocol_count;
3639 struct _objc_protocol *class_protocols[];
3640 }
3641 */
3642 Result += "\nstatic struct {\n";
3643 Result += "\tstruct _objc_protocol_list *next;\n";
3644 Result += "\tint protocol_count;\n";
3645 Result += "\tstruct _objc_protocol *class_protocols[";
3646 Result += utostr(Protocols.size());
3647 Result += "];\n} _OBJC_";
3648 Result += prefix;
3649 Result += "_PROTOCOLS_";
3650 Result += ClassName;
3651 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3652 "{\n\t0, ";
3653 Result += utostr(Protocols.size());
3654 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003655
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003656 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003657 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003658 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003659
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003660 for (unsigned i = 1; i != Protocols.size(); i++) {
3661 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003662 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003663 Result += "\n";
3664 }
3665 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003666}
3667
Steve Naroff621edce2009-04-29 16:37:50 +00003668
Mike Stump1eb44332009-09-09 15:08:12 +00003669/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003670/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003671void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003672 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003673 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003674 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003675 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003676 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003677 CDecl = CDecl->getNextClassCategory())
3678 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3679 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003680
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003681 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003682 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003683 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003684
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003685 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003686 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003687 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003688
3689 // If any of our property implementations have associated getters or
3690 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003691 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3692 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003693 Prop != PropEnd; ++Prop) {
3694 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3695 continue;
3696 if (!(*Prop)->getPropertyIvarDecl())
3697 continue;
3698 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3699 if (!PD)
3700 continue;
3701 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3702 InstanceMethods.push_back(Getter);
3703 if (PD->isReadOnly())
3704 continue;
3705 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3706 InstanceMethods.push_back(Setter);
3707 }
3708 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003709 true, "CATEGORY_", FullCategoryName.c_str(),
3710 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003711
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003712 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003713 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003714 false, "CATEGORY_", FullCategoryName.c_str(),
3715 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003716
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003717 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003718 // Null CDecl is case of a category implementation with no category interface
3719 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003720 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003721 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003722 /* struct _objc_category {
3723 char *category_name;
3724 char *class_name;
3725 struct _objc_method_list *instance_methods;
3726 struct _objc_method_list *class_methods;
3727 struct _objc_protocol_list *protocols;
3728 // Objective-C 1.0 extensions
3729 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003730 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003731 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003732 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003733 */
Mike Stump1eb44332009-09-09 15:08:12 +00003734
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003735 static bool objc_category = false;
3736 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003737 Result += "\nstruct _objc_category {\n";
3738 Result += "\tchar *category_name;\n";
3739 Result += "\tchar *class_name;\n";
3740 Result += "\tstruct _objc_method_list *instance_methods;\n";
3741 Result += "\tstruct _objc_method_list *class_methods;\n";
3742 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003743 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003744 Result += "\tstruct _objc_property_list *instance_properties;\n";
3745 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003746 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003747 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003748 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3749 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003750 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003751 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003752 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003753 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003754 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003755
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003756 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003757 Result += "\t, (struct _objc_method_list *)"
3758 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3759 Result += FullCategoryName;
3760 Result += "\n";
3761 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003762 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003763 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003764 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003765 Result += "\t, (struct _objc_method_list *)"
3766 "&_OBJC_CATEGORY_CLASS_METHODS_";
3767 Result += FullCategoryName;
3768 Result += "\n";
3769 }
3770 else
3771 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003772
Chris Lattnercafeb352009-02-20 18:18:36 +00003773 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003774 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003775 Result += FullCategoryName;
3776 Result += "\n";
3777 }
3778 else
3779 Result += "\t, 0\n";
3780 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003781}
3782
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003783/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3784/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003785void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003786 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003787 if (ivar->isBitField()) {
3788 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3789 // place all bitfields at offset 0.
3790 Result += "0";
3791 } else {
3792 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003793 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003794 if (LangOpts.Microsoft)
3795 Result += "_IMPL";
3796 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003797 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003798 Result += ")";
3799 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003800}
3801
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003802//===----------------------------------------------------------------------===//
3803// Meta Data Emission
3804//===----------------------------------------------------------------------===//
3805
Steve Naroffb29b4272008-04-14 22:03:09 +00003806void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003807 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003808 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003809
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003810 // Explicitly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003811 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003812 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003813 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003814 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003815 }
Mike Stump1eb44332009-09-09 15:08:12 +00003816
Chris Lattnerbe6df082007-12-12 07:56:42 +00003817 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003818 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003819 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003820 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003821 if (NumIvars > 0) {
3822 static bool objc_ivar = false;
3823 if (!objc_ivar) {
3824 /* struct _objc_ivar {
3825 char *ivar_name;
3826 char *ivar_type;
3827 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003828 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003829 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003830 Result += "\nstruct _objc_ivar {\n";
3831 Result += "\tchar *ivar_name;\n";
3832 Result += "\tchar *ivar_type;\n";
3833 Result += "\tint ivar_offset;\n";
3834 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003835
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003836 objc_ivar = true;
3837 }
3838
Steve Naroff946a6932008-03-11 00:12:29 +00003839 /* struct {
3840 int ivar_count;
3841 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003842 };
Steve Naroff946a6932008-03-11 00:12:29 +00003843 */
Mike Stump1eb44332009-09-09 15:08:12 +00003844 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003845 Result += "\tint ivar_count;\n";
3846 Result += "\tstruct _objc_ivar ivar_list[";
3847 Result += utostr(NumIvars);
3848 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003849 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003850 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003851 "{\n\t";
3852 Result += utostr(NumIvars);
3853 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003854
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003855 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003856 SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003857 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003858 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003859 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003860 IV != IVEnd; ++IV)
3861 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003862 IVI = IDecl->ivar_begin();
3863 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003864 } else {
3865 IVI = CDecl->ivar_begin();
3866 IVE = CDecl->ivar_end();
3867 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003868 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003869 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003870 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003871 std::string TmpString, StrEncoding;
3872 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3873 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003874 Result += StrEncoding;
3875 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003876 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003877 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003878 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003879 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003880 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003881 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003882 std::string TmpString, StrEncoding;
3883 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3884 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003885 Result += StrEncoding;
3886 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003887 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003888 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003889 }
Mike Stump1eb44332009-09-09 15:08:12 +00003890
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003891 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003892 }
Mike Stump1eb44332009-09-09 15:08:12 +00003893
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003894 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003895 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003896 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003897
3898 // If any of our property implementations have associated getters or
3899 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003900 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3901 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003902 Prop != PropEnd; ++Prop) {
3903 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3904 continue;
3905 if (!(*Prop)->getPropertyIvarDecl())
3906 continue;
3907 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3908 if (!PD)
3909 continue;
3910 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003911 if (!Getter->isDefined())
3912 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003913 if (PD->isReadOnly())
3914 continue;
3915 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003916 if (!Setter->isDefined())
3917 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003918 }
3919 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003920 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003921
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003922 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003923 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003924 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003925
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003926 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003927 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003928 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003929
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003930 // Declaration of class/meta-class metadata
3931 /* struct _objc_class {
3932 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003933 const char *super_class_name;
3934 char *name;
3935 long version;
3936 long info;
3937 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003938 struct _objc_ivar_list *ivars;
3939 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003940 struct objc_cache *cache;
3941 struct objc_protocol_list *protocols;
3942 const char *ivar_layout;
3943 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003944 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003945 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003946 static bool objc_class = false;
3947 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003948 Result += "\nstruct _objc_class {\n";
3949 Result += "\tstruct _objc_class *isa;\n";
3950 Result += "\tconst char *super_class_name;\n";
3951 Result += "\tchar *name;\n";
3952 Result += "\tlong version;\n";
3953 Result += "\tlong info;\n";
3954 Result += "\tlong instance_size;\n";
3955 Result += "\tstruct _objc_ivar_list *ivars;\n";
3956 Result += "\tstruct _objc_method_list *methods;\n";
3957 Result += "\tstruct objc_cache *cache;\n";
3958 Result += "\tstruct _objc_protocol_list *protocols;\n";
3959 Result += "\tconst char *ivar_layout;\n";
3960 Result += "\tstruct _objc_class_ext *ext;\n";
3961 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003962 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003963 }
Mike Stump1eb44332009-09-09 15:08:12 +00003964
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003965 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003966 ObjCInterfaceDecl *RootClass = 0;
3967 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003968 while (SuperClass) {
3969 RootClass = SuperClass;
3970 SuperClass = SuperClass->getSuperClass();
3971 }
3972 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003973
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003974 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003975 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003976 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003977 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003978 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003979 Result += "\"";
3980
3981 if (SuperClass) {
3982 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003983 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003984 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003985 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003986 Result += "\"";
3987 }
3988 else {
3989 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003990 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003991 Result += "\"";
3992 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003993 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003994 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003995 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003996 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003997 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003998 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003999 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004000 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004001 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004002 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00004003 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004004 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004005 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004006 Result += ",0,0\n";
4007 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00004008 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004009 Result += "\t,0,0,0,0\n";
4010 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004011
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004012 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004013 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004014 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004015 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004016 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004017 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004018 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 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004030 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004031 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004032 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004033 Result += ",0";
4034 else {
4035 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00004036 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004037 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00004038 if (LangOpts.Microsoft)
4039 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004040 Result += ")";
4041 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004042 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00004043 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004044 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004045 Result += "\n\t";
4046 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004047 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004048 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004049 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00004050 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004051 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004052 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004053 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004054 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004055 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00004056 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004057 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004058 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004059 Result += ", 0,0\n";
4060 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004061 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004062 Result += ",0,0,0\n";
4063 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004064}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004065
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004066/// RewriteImplementations - This routine rewrites all method implementations
4067/// and emits meta-data.
4068
Steve Narofface66252008-11-13 20:07:04 +00004069void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004070 int ClsDefCount = ClassImplementation.size();
4071 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004072
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004073 // Rewrite implemented methods
4074 for (int i = 0; i < ClsDefCount; i++)
4075 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004076
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004077 for (int i = 0; i < CatDefCount; i++)
4078 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004079}
Mike Stump1eb44332009-09-09 15:08:12 +00004080
Steve Narofface66252008-11-13 20:07:04 +00004081void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4082 int ClsDefCount = ClassImplementation.size();
4083 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004084
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004085 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004086 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004087 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004088
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004089 // For each implemented category, write out all its meta data.
4090 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004091 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004092
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004093 // Write objc_symtab metadata
4094 /*
4095 struct _objc_symtab
4096 {
4097 long sel_ref_cnt;
4098 SEL *refs;
4099 short cls_def_cnt;
4100 short cat_def_cnt;
4101 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004102 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004103 */
Mike Stump1eb44332009-09-09 15:08:12 +00004104
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004105 Result += "\nstruct _objc_symtab {\n";
4106 Result += "\tlong sel_ref_cnt;\n";
4107 Result += "\tSEL *refs;\n";
4108 Result += "\tshort cls_def_cnt;\n";
4109 Result += "\tshort cat_def_cnt;\n";
4110 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4111 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004112
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004113 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004114 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004115 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004116 + ", " + utostr(CatDefCount) + "\n";
4117 for (int i = 0; i < ClsDefCount; i++) {
4118 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004119 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004120 Result += "\n";
4121 }
Mike Stump1eb44332009-09-09 15:08:12 +00004122
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004123 for (int i = 0; i < CatDefCount; i++) {
4124 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004125 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004126 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004127 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004128 Result += "\n";
4129 }
Mike Stump1eb44332009-09-09 15:08:12 +00004130
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004131 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004132
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004133 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004134
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004135 /*
4136 struct _objc_module {
4137 long version;
4138 long size;
4139 const char *name;
4140 struct _objc_symtab *symtab;
4141 }
4142 */
Mike Stump1eb44332009-09-09 15:08:12 +00004143
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004144 Result += "\nstruct _objc_module {\n";
4145 Result += "\tlong version;\n";
4146 Result += "\tlong size;\n";
4147 Result += "\tconst char *name;\n";
4148 Result += "\tstruct _objc_symtab *symtab;\n";
4149 Result += "};\n\n";
4150 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004151 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004152 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004153 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004154 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004155
4156 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004157 if (ProtocolExprDecls.size()) {
4158 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4159 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004160 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004161 E = ProtocolExprDecls.end(); I != E; ++I) {
4162 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4163 Result += (*I)->getNameAsString();
4164 Result += " = &_OBJC_PROTOCOL_";
4165 Result += (*I)->getNameAsString();
4166 Result += ";\n";
4167 }
4168 Result += "#pragma data_seg(pop)\n\n";
4169 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004170 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004171 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004172 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4173 Result += "&_OBJC_MODULES;\n";
4174 Result += "#pragma data_seg(pop)\n\n";
4175 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004176}
Chris Lattner311ff022007-10-16 22:36:42 +00004177
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004178void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4179 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004180 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004181 assert(BlockByRefDeclNo.count(VD) &&
4182 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004183 if (def)
4184 ResultStr += "struct ";
4185 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004186 "_" + utostr(BlockByRefDeclNo[VD]) ;
4187}
4188
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004189static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4190 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4191 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4192 return false;
4193}
4194
Steve Naroff54055232008-10-27 17:20:55 +00004195std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004196 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004197 std::string Tag) {
4198 const FunctionType *AFT = CE->getFunctionType();
4199 QualType RT = AFT->getResultType();
4200 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004201 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004202 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004203
Steve Naroff54055232008-10-27 17:20:55 +00004204 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004205
Douglas Gregor72564e72009-02-26 23:50:07 +00004206 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004207 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004208 // block (to reference imported block decl refs).
4209 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004210 } else if (BD->param_empty()) {
4211 S += "(" + StructRef + " *__cself)";
4212 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004213 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004214 assert(FT && "SynthesizeBlockFunc: No function proto");
4215 S += '(';
4216 // first add the implicit argument.
4217 S += StructRef + " *__cself, ";
4218 std::string ParamStr;
4219 for (BlockDecl::param_iterator AI = BD->param_begin(),
4220 E = BD->param_end(); AI != E; ++AI) {
4221 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004222 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004223 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004224 if (convertBlockPointerToFunctionPointer(QT))
4225 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004226 else
4227 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004228 S += ParamStr;
4229 }
4230 if (FT->isVariadic()) {
4231 if (!BD->param_empty()) S += ", ";
4232 S += "...";
4233 }
4234 S += ')';
4235 }
4236 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004237
Steve Naroff54055232008-10-27 17:20:55 +00004238 // Create local declarations to avoid rewriting all closure decl ref exprs.
4239 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004240 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004241 E = BlockByRefDecls.end(); I != E; ++I) {
4242 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004243 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004244 std::string TypeString;
4245 RewriteByRefString(TypeString, Name, (*I));
4246 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004247 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004248 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004249 }
Steve Naroff54055232008-10-27 17:20:55 +00004250 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004251 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004252 E = BlockByCopyDecls.end(); I != E; ++I) {
4253 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004254 // Handle nested closure invocation. For example:
4255 //
4256 // void (^myImportedClosure)(void);
4257 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004258 //
Steve Naroff54055232008-10-27 17:20:55 +00004259 // void (^anotherClosure)(void);
4260 // anotherClosure = ^(void) {
4261 // myImportedClosure(); // import and invoke the closure
4262 // };
4263 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004264 if (isTopLevelBlockPointerType((*I)->getType())) {
4265 RewriteBlockPointerTypeVariable(S, (*I));
4266 S += " = (";
4267 RewriteBlockPointerType(S, (*I)->getType());
4268 S += ")";
4269 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4270 }
4271 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004272 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004273 QualType QT = (*I)->getType();
4274 if (HasLocalVariableExternalStorage(*I))
4275 QT = Context->getPointerType(QT);
4276 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004277 S += Name + " = __cself->" +
4278 (*I)->getNameAsString() + "; // bound by copy\n";
4279 }
Steve Naroff54055232008-10-27 17:20:55 +00004280 }
4281 std::string RewrittenStr = RewrittenBlockExprs[CE];
4282 const char *cstr = RewrittenStr.c_str();
4283 while (*cstr++ != '{') ;
4284 S += cstr;
4285 S += "\n";
4286 return S;
4287}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004288
Steve Naroff54055232008-10-27 17:20:55 +00004289std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004290 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004291 std::string Tag) {
4292 std::string StructRef = "struct " + Tag;
4293 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004294
Steve Naroff54055232008-10-27 17:20:55 +00004295 S += funcName;
4296 S += "_block_copy_" + utostr(i);
4297 S += "(" + StructRef;
4298 S += "*dst, " + StructRef;
4299 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004300 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004301 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004302 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004303 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004304 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004305 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004306 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004307 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004308 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004309 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004310 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004311 else
4312 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004313 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004314 S += "}\n";
4315
Steve Naroff54055232008-10-27 17:20:55 +00004316 S += "\nstatic void __";
4317 S += funcName;
4318 S += "_block_dispose_" + utostr(i);
4319 S += "(" + StructRef;
4320 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004321 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004322 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004323 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004324 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004325 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004326 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004327 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004328 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004329 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004330 else
4331 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004332 }
Mike Stump1eb44332009-09-09 15:08:12 +00004333 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004334 return S;
4335}
4336
Steve Naroff01aec112009-12-06 21:14:13 +00004337std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4338 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004339 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004340 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004341
Steve Naroff54055232008-10-27 17:20:55 +00004342 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004343 S += " struct " + Desc;
4344 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004345
Steve Naroff01aec112009-12-06 21:14:13 +00004346 Constructor += "(void *fp, "; // Invoke function pointer.
4347 Constructor += "struct " + Desc; // Descriptor pointer.
4348 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004349
Steve Naroff54055232008-10-27 17:20:55 +00004350 if (BlockDeclRefs.size()) {
4351 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004352 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004353 E = BlockByCopyDecls.end(); I != E; ++I) {
4354 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004355 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004356 std::string ArgName = "_" + FieldName;
4357 // Handle nested closure invocation. For example:
4358 //
4359 // void (^myImportedBlock)(void);
4360 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004361 //
Steve Naroff54055232008-10-27 17:20:55 +00004362 // void (^anotherBlock)(void);
4363 // anotherBlock = ^(void) {
4364 // myImportedBlock(); // import and invoke the closure
4365 // };
4366 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004367 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004368 S += "struct __block_impl *";
4369 Constructor += ", void *" + ArgName;
4370 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004371 QualType QT = (*I)->getType();
4372 if (HasLocalVariableExternalStorage(*I))
4373 QT = Context->getPointerType(QT);
4374 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4375 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004376 Constructor += ", " + ArgName;
4377 }
4378 S += FieldName + ";\n";
4379 }
4380 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004381 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004382 E = BlockByRefDecls.end(); I != E; ++I) {
4383 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004384 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004385 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004386 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004387 std::string TypeString;
4388 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004389 TypeString += " *";
4390 FieldName = TypeString + FieldName;
4391 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004392 Constructor += ", " + ArgName;
4393 }
4394 S += FieldName + "; // by ref\n";
4395 }
4396 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004397 Constructor += ", int flags=0)";
4398 // Initialize all "by copy" arguments.
4399 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004400 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004401 E = BlockByCopyDecls.end(); I != E; ++I) {
4402 std::string Name = (*I)->getNameAsString();
4403 if (firsTime) {
4404 Constructor += " : ";
4405 firsTime = false;
4406 }
4407 else
4408 Constructor += ", ";
4409 if (isTopLevelBlockPointerType((*I)->getType()))
4410 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4411 else
4412 Constructor += Name + "(_" + Name + ")";
4413 }
4414 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004415 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004416 E = BlockByRefDecls.end(); I != E; ++I) {
4417 std::string Name = (*I)->getNameAsString();
4418 if (firsTime) {
4419 Constructor += " : ";
4420 firsTime = false;
4421 }
4422 else
4423 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004424 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004425 }
4426
4427 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004428 if (GlobalVarDecl)
4429 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4430 else
4431 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004432 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004433
Steve Naroff01aec112009-12-06 21:14:13 +00004434 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004435 } else {
4436 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004437 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004438 if (GlobalVarDecl)
4439 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4440 else
4441 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004442 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4443 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004444 }
4445 Constructor += " ";
4446 Constructor += "}\n";
4447 S += Constructor;
4448 S += "};\n";
4449 return S;
4450}
4451
Steve Naroff01aec112009-12-06 21:14:13 +00004452std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4453 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004454 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004455 unsigned hasCopy) {
4456 std::string S = "\nstatic struct " + DescTag;
4457
4458 S += " {\n unsigned long reserved;\n";
4459 S += " unsigned long Block_size;\n";
4460 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004461 S += " void (*copy)(struct ";
4462 S += ImplTag; S += "*, struct ";
4463 S += ImplTag; S += "*);\n";
4464
4465 S += " void (*dispose)(struct ";
4466 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004467 }
4468 S += "} ";
4469
4470 S += DescTag + "_DATA = { 0, sizeof(struct ";
4471 S += ImplTag + ")";
4472 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004473 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4474 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004475 }
4476 S += "};\n";
4477 return S;
4478}
4479
Steve Naroff54055232008-10-27 17:20:55 +00004480void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004481 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004482 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004483 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004484 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004485 bool RewriteSC = (GlobalVarDecl &&
4486 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004487 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004488 GlobalVarDecl->getType().getCVRQualifiers());
4489 if (RewriteSC) {
4490 std::string SC(" void __");
4491 SC += GlobalVarDecl->getNameAsString();
4492 SC += "() {}";
4493 InsertText(FunLocStart, SC);
4494 }
4495
Steve Naroff54055232008-10-27 17:20:55 +00004496 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004497 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4498 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004499 // Need to copy-in the inner copied-in variables not actually used in this
4500 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004501 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4502 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4503 ValueDecl *VD = Exp->getDecl();
4504 BlockDeclRefs.push_back(Exp);
4505 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4506 BlockByCopyDeclsPtrSet.insert(VD);
4507 BlockByCopyDecls.push_back(VD);
4508 }
4509 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4510 BlockByRefDeclsPtrSet.insert(VD);
4511 BlockByRefDecls.push_back(VD);
4512 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004513 // imported objects in the inner blocks not used in the outer
4514 // blocks must be copied/disposed in the outer block as well.
4515 if (Exp->isByRef() ||
4516 VD->getType()->isObjCObjectPointerType() ||
4517 VD->getType()->isBlockPointerType())
4518 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004519 }
Steve Naroff54055232008-10-27 17:20:55 +00004520
Daniel Dunbar4087f272010-08-17 22:39:59 +00004521 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4522 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004523
Steve Naroff01aec112009-12-06 21:14:13 +00004524 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004525
Benjamin Kramerd999b372010-02-14 14:14:16 +00004526 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004527
Steve Naroff01aec112009-12-06 21:14:13 +00004528 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004529
Benjamin Kramerd999b372010-02-14 14:14:16 +00004530 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004531
4532 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004533 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004534 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004535 }
Steve Naroff01aec112009-12-06 21:14:13 +00004536 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4537 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004538 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004539
Steve Naroff54055232008-10-27 17:20:55 +00004540 BlockDeclRefs.clear();
4541 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004542 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004543 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004544 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004545 ImportedBlockDecls.clear();
4546 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004547 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004548 // Must insert any 'const/volatile/static here. Since it has been
4549 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004550 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004551 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004552 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004553 if (GlobalVarDecl->getType().isConstQualified())
4554 SC += "const ";
4555 if (GlobalVarDecl->getType().isVolatileQualified())
4556 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004557 if (GlobalVarDecl->getType().isRestrictQualified())
4558 SC += "restrict ";
4559 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004560 }
4561
Steve Naroff54055232008-10-27 17:20:55 +00004562 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004563 InnerDeclRefsCount.clear();
4564 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004565 RewrittenBlockExprs.clear();
4566}
4567
4568void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4569 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00004570 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004571
Steve Naroff54055232008-10-27 17:20:55 +00004572 SynthesizeBlockLiterals(FunLocStart, FuncName);
4573}
4574
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004575static void BuildUniqueMethodName(std::string &Name,
4576 ObjCMethodDecl *MD) {
4577 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004578 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004579 Name += "__" + MD->getSelector().getAsString();
4580 // Convert colons to underscores.
4581 std::string::size_type loc = 0;
4582 while ((loc = Name.find(":", loc)) != std::string::npos)
4583 Name.replace(loc, 1, "_");
4584}
4585
Steve Naroff54055232008-10-27 17:20:55 +00004586void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004587 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4588 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004589 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004590 std::string FuncName;
4591 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004592 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004593}
4594
4595void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00004596 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00004597 if (*CI) {
4598 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4599 GetBlockDeclRefExprs(CBE->getBody());
4600 else
4601 GetBlockDeclRefExprs(*CI);
4602 }
4603 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004604 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004605 // FIXME: Handle enums.
4606 if (!isa<FunctionDecl>(CDRE->getDecl()))
4607 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004608 }
4609 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4610 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4611 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00004612 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4613 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004614 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004615 BlockDeclRefs.push_back(BDRE);
4616 }
4617
Steve Naroff54055232008-10-27 17:20:55 +00004618 return;
4619}
4620
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004621void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004622 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004623 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00004624 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004625 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004626 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4627 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004628 GetInnerBlockDeclRefExprs(CBE->getBody(),
4629 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004630 InnerContexts);
4631 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004632 else
4633 GetInnerBlockDeclRefExprs(*CI,
4634 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004635 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004636
4637 }
4638 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004639 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004640 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004641 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004642 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004643 }
4644 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4645 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4646 if (Var->isFunctionOrMethodVarDecl())
4647 ImportedLocalExternalDecls.insert(Var);
4648 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004649
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004650 return;
4651}
4652
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004653/// convertFunctionTypeOfBlocks - This routine converts a function type
4654/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00004655/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004656/// all block pointers to function pointers.
4657QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4658 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4659 // FTP will be null for closures that don't take arguments.
4660 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004661 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004662 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004663 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004664
4665 if (FTP) {
4666 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4667 E = FTP->arg_type_end(); I && (I != E); ++I) {
4668 QualType t = *I;
4669 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004670 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004671 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004672 ArgTypes.push_back(t);
4673 }
4674 }
4675 QualType FuncType;
4676 // FIXME. Does this work if block takes no argument but has a return type
4677 // which is of block type?
4678 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00004679 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004680 else FuncType = QualType(FT, 0);
4681 return FuncType;
4682}
4683
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004684Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004685 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004686 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004687
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004688 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004689 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004690 } else if (const BlockDeclRefExpr *CDRE =
4691 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004692 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004693 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004694 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004695 }
4696 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4697 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4698 }
4699 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4700 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4701 else if (const ConditionalOperator *CEXPR =
4702 dyn_cast<ConditionalOperator>(BlockExp)) {
4703 Expr *LHSExp = CEXPR->getLHS();
4704 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4705 Expr *RHSExp = CEXPR->getRHS();
4706 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4707 Expr *CONDExp = CEXPR->getCond();
4708 ConditionalOperator *CondExpr =
4709 new (Context) ConditionalOperator(CONDExp,
4710 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004711 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00004712 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004713 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004714 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4715 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004716 } else {
4717 assert(1 && "RewriteBlockClass: Bad type");
4718 }
4719 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004720 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004721 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004722 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004723 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004724
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004725 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004726 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004727 &Context->Idents.get("__block_impl"));
4728 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004729
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004730 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004731 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004732
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004733 // Push the block argument type.
4734 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004735 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004736 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004737 E = FTP->arg_type_end(); I && (I != E); ++I) {
4738 QualType t = *I;
4739 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004740 if (!convertBlockPointerToFunctionPointer(t))
4741 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004742 ArgTypes.push_back(t);
4743 }
Steve Naroff54055232008-10-27 17:20:55 +00004744 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004745 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00004746 QualType PtrToFuncCastType
4747 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004748
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004749 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004750
John McCall9d125032010-01-15 18:39:57 +00004751 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004752 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004753 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004754 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004755 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4756 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004757 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004758
Douglas Gregor44b43212008-12-11 16:49:14 +00004759 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004760 SourceLocation(),
4761 &Context->Idents.get("FuncPtr"),
4762 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004763 /*BitWidth=*/0, /*Mutable=*/true,
4764 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004765 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004766 FD->getType(), VK_LValue,
4767 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004768
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004769
John McCall9d125032010-01-15 18:39:57 +00004770 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004771 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004772 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004773
Chris Lattner5f9e2722011-07-23 10:55:15 +00004774 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004775 // Add the implicit argument.
4776 BlkExprs.push_back(BlkCast);
4777 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004778 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004779 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004780 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004781 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004782 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4783 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004784 Exp->getType(), VK_RValue,
4785 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004786 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004787}
4788
Steve Naroff621edce2009-04-29 16:37:50 +00004789// We need to return the rewritten expression to handle cases where the
4790// BlockDeclRefExpr is embedded in another expression being rewritten.
4791// For example:
4792//
4793// int main() {
4794// __block Foo *f;
4795// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004796//
Steve Naroff621edce2009-04-29 16:37:50 +00004797// void (^myblock)() = ^() {
4798// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4799// i = 77;
4800// };
4801//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004802Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004803 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004804 // for each DeclRefExp where BYREFVAR is name of the variable.
4805 ValueDecl *VD;
4806 bool isArrow = true;
4807 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4808 VD = BDRE->getDecl();
4809 else {
4810 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4811 isArrow = false;
4812 }
4813
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004814 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004815 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004816 &Context->Idents.get("__forwarding"),
4817 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004818 /*BitWidth=*/0, /*Mutable=*/true,
4819 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004820 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4821 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004822 FD->getType(), VK_LValue,
4823 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004824
Chris Lattner5f9e2722011-07-23 10:55:15 +00004825 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004826 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004827 &Context->Idents.get(Name),
4828 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004829 /*BitWidth=*/0, /*Mutable=*/true,
4830 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004831 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004832 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004833
4834
4835
Steve Naroffdf8570d2009-02-02 17:19:26 +00004836 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00004837 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4838 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004839 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004840 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004841 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004842}
4843
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004844// Rewrites the imported local variable V with external storage
4845// (static, extern, etc.) as *V
4846//
4847Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4848 ValueDecl *VD = DRE->getDecl();
4849 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4850 if (!ImportedLocalExternalDecls.count(Var))
4851 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004852 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4853 VK_LValue, OK_Ordinary,
4854 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004855 // Need parens to enforce precedence.
4856 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4857 Exp);
4858 ReplaceStmt(DRE, PE);
4859 return PE;
4860}
4861
Steve Naroffb2f9e512008-11-03 23:29:32 +00004862void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4863 SourceLocation LocStart = CE->getLParenLoc();
4864 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004865
4866 // Need to avoid trying to rewrite synthesized casts.
4867 if (LocStart.isInvalid())
4868 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004869 // Need to avoid trying to rewrite casts contained in macros.
4870 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4871 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004872
Steve Naroff54055232008-10-27 17:20:55 +00004873 const char *startBuf = SM->getCharacterData(LocStart);
4874 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004875 QualType QT = CE->getType();
4876 const Type* TypePtr = QT->getAs<Type>();
4877 if (isa<TypeOfExprType>(TypePtr)) {
4878 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4879 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4880 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004881 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004882 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004883 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004884 return;
4885 }
Steve Naroff54055232008-10-27 17:20:55 +00004886 // advance the location to startArgList.
4887 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004888
Steve Naroff54055232008-10-27 17:20:55 +00004889 while (*argPtr++ && (argPtr < endBuf)) {
4890 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004891 case '^':
4892 // Replace the '^' with '*'.
4893 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004894 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004895 break;
Steve Naroff54055232008-10-27 17:20:55 +00004896 }
4897 }
4898 return;
4899}
4900
4901void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4902 SourceLocation DeclLoc = FD->getLocation();
4903 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004904
Steve Naroff54055232008-10-27 17:20:55 +00004905 // We have 1 or more arguments that have closure pointers.
4906 const char *startBuf = SM->getCharacterData(DeclLoc);
4907 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004908
Steve Naroff54055232008-10-27 17:20:55 +00004909 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004910
Steve Naroff54055232008-10-27 17:20:55 +00004911 parenCount++;
4912 // advance the location to startArgList.
4913 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4914 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004915
Steve Naroff54055232008-10-27 17:20:55 +00004916 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004917
Steve Naroff54055232008-10-27 17:20:55 +00004918 while (*argPtr++ && parenCount) {
4919 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004920 case '^':
4921 // Replace the '^' with '*'.
4922 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004923 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004924 break;
4925 case '(':
4926 parenCount++;
4927 break;
4928 case ')':
4929 parenCount--;
4930 break;
Steve Naroff54055232008-10-27 17:20:55 +00004931 }
4932 }
4933 return;
4934}
4935
4936bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004937 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004938 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004939 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004940 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004941 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004942 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004943 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004944 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004945 }
4946 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004947 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004948 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004949 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004950 return true;
4951 }
4952 return false;
4953}
4954
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004955bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4956 const FunctionProtoType *FTP;
4957 const PointerType *PT = QT->getAs<PointerType>();
4958 if (PT) {
4959 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4960 } else {
4961 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4962 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4963 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4964 }
4965 if (FTP) {
4966 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004967 E = FTP->arg_type_end(); I != E; ++I) {
4968 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004969 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004970 if ((*I)->isObjCObjectPointerType() &&
4971 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4972 return true;
4973 }
4974
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004975 }
4976 return false;
4977}
4978
Ted Kremenek8189cde2009-02-07 01:47:29 +00004979void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4980 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004981 const char *argPtr = strchr(Name, '(');
4982 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004983
Steve Naroff54055232008-10-27 17:20:55 +00004984 LParen = argPtr; // output the start.
4985 argPtr++; // skip past the left paren.
4986 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004987
Steve Naroff54055232008-10-27 17:20:55 +00004988 while (*argPtr && parenCount) {
4989 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004990 case '(': parenCount++; break;
4991 case ')': parenCount--; break;
4992 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004993 }
4994 if (parenCount) argPtr++;
4995 }
4996 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4997 RParen = argPtr; // output the end
4998}
4999
5000void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5001 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5002 RewriteBlockPointerFunctionArgs(FD);
5003 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005004 }
Steve Naroff54055232008-10-27 17:20:55 +00005005 // Handle Variables and Typedefs.
5006 SourceLocation DeclLoc = ND->getLocation();
5007 QualType DeclT;
5008 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5009 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00005010 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00005011 DeclT = TDD->getUnderlyingType();
5012 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5013 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005014 else
Steve Naroff54055232008-10-27 17:20:55 +00005015 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00005016
Steve Naroff54055232008-10-27 17:20:55 +00005017 const char *startBuf = SM->getCharacterData(DeclLoc);
5018 const char *endBuf = startBuf;
5019 // scan backward (from the decl location) for the end of the previous decl.
5020 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5021 startBuf--;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005022 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
5023 std::string buf;
5024 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00005025 // *startBuf != '^' if we are dealing with a pointer to function that
5026 // may take block argument types (which will be handled below).
5027 if (*startBuf == '^') {
5028 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005029 buf = '*';
5030 startBuf++;
5031 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005032 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005033 while (*startBuf != ')') {
5034 buf += *startBuf;
5035 startBuf++;
5036 OrigLength++;
5037 }
5038 buf += ')';
5039 OrigLength++;
5040
5041 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5042 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00005043 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005044 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00005045 DeclLoc = ND->getLocation();
5046 startBuf = SM->getCharacterData(DeclLoc);
5047 const char *argListBegin, *argListEnd;
5048 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5049 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005050 if (*argListBegin == '^')
5051 buf += '*';
5052 else if (*argListBegin == '<') {
5053 buf += "/*";
5054 buf += *argListBegin++;
5055 OrigLength++;;
5056 while (*argListBegin != '>') {
5057 buf += *argListBegin++;
5058 OrigLength++;
5059 }
5060 buf += *argListBegin;
5061 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005062 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005063 else
5064 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005065 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005066 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005067 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005068 buf += ')';
5069 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005070 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005071 ReplaceText(Start, OrigLength, buf);
5072
Steve Naroff54055232008-10-27 17:20:55 +00005073 return;
5074}
5075
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005076
5077/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5078/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5079/// struct Block_byref_id_object *src) {
5080/// _Block_object_assign (&_dest->object, _src->object,
5081/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5082/// [|BLOCK_FIELD_IS_WEAK]) // object
5083/// _Block_object_assign(&_dest->object, _src->object,
5084/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5085/// [|BLOCK_FIELD_IS_WEAK]) // block
5086/// }
5087/// And:
5088/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5089/// _Block_object_dispose(_src->object,
5090/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5091/// [|BLOCK_FIELD_IS_WEAK]) // object
5092/// _Block_object_dispose(_src->object,
5093/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5094/// [|BLOCK_FIELD_IS_WEAK]) // block
5095/// }
5096
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005097std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5098 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005099 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005100 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005101 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005102 CopyDestroyCache.insert(flag);
5103 S = "static void __Block_byref_id_object_copy_";
5104 S += utostr(flag);
5105 S += "(void *dst, void *src) {\n";
5106
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005107 // offset into the object pointer is computed as:
5108 // void * + void* + int + int + void* + void *
5109 unsigned IntSize =
5110 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5111 unsigned VoidPtrSize =
5112 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5113
Ken Dyck0c4e5d62011-04-30 16:08:27 +00005114 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005115 S += " _Block_object_assign((char*)dst + ";
5116 S += utostr(offset);
5117 S += ", *(void * *) ((char*)src + ";
5118 S += utostr(offset);
5119 S += "), ";
5120 S += utostr(flag);
5121 S += ");\n}\n";
5122
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005123 S += "static void __Block_byref_id_object_dispose_";
5124 S += utostr(flag);
5125 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005126 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5127 S += utostr(offset);
5128 S += "), ";
5129 S += utostr(flag);
5130 S += ");\n}\n";
5131 return S;
5132}
5133
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005134/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5135/// the declaration into:
5136/// struct __Block_byref_ND {
5137/// void *__isa; // NULL for everything except __weak pointers
5138/// struct __Block_byref_ND *__forwarding;
5139/// int32_t __flags;
5140/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005141/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5142/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005143/// typex ND;
5144/// };
5145///
5146/// It then replaces declaration of ND variable with:
5147/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5148/// __size=sizeof(struct __Block_byref_ND),
5149/// ND=initializer-if-any};
5150///
5151///
5152void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005153 // Insert declaration for the function in which block literal is
5154 // used.
5155 if (CurFunctionDeclToDeclareForBlock)
5156 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005157 int flag = 0;
5158 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005159 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005160 if (DeclLoc.isInvalid())
5161 // If type location is missing, it is because of missing type (a warning).
5162 // Use variable's location which is good for this case.
5163 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005164 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005165 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00005166 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005167 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005168 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005169 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005170 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005171 ByrefType += " {\n";
5172 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005173 RewriteByRefString(ByrefType, Name, ND);
5174 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005175 ByrefType += " int __flags;\n";
5176 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005177 // Add void *__Block_byref_id_object_copy;
5178 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005179 QualType Ty = ND->getType();
5180 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5181 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005182 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5183 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005184 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005185
5186 QualType T = Ty;
5187 (void)convertBlockPointerToFunctionPointer(T);
5188 T.getAsStringInternal(Name, Context->PrintingPolicy);
5189
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005190 ByrefType += " " + Name + ";\n";
5191 ByrefType += "};\n";
5192 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005193 SourceLocation FunLocStart;
5194 if (CurFunctionDef)
5195 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5196 else {
5197 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5198 FunLocStart = CurMethodDef->getLocStart();
5199 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005200 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005201 if (Ty.isObjCGCWeak()) {
5202 flag |= BLOCK_FIELD_IS_WEAK;
5203 isa = 1;
5204 }
5205
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005206 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005207 flag = BLOCK_BYREF_CALLER;
5208 QualType Ty = ND->getType();
5209 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5210 if (Ty->isBlockPointerType())
5211 flag |= BLOCK_FIELD_IS_BLOCK;
5212 else
5213 flag |= BLOCK_FIELD_IS_OBJECT;
5214 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005215 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005216 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005217 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005218
5219 // struct __Block_byref_ND ND =
5220 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5221 // initializer-if-any};
5222 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005223 unsigned flags = 0;
5224 if (HasCopyAndDispose)
5225 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005226 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005227 ByrefType.clear();
5228 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005229 std::string ForwardingCastType("(");
5230 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005231 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005232 ByrefType += " " + Name + " = {(void*)";
5233 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005234 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005235 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005236 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005237 ByrefType += "sizeof(";
5238 RewriteByRefString(ByrefType, Name, ND);
5239 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005240 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005241 ByrefType += ", __Block_byref_id_object_copy_";
5242 ByrefType += utostr(flag);
5243 ByrefType += ", __Block_byref_id_object_dispose_";
5244 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005245 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005246 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005247 unsigned nameSize = Name.size();
5248 // for block or function pointer declaration. Name is aleady
5249 // part of the declaration.
5250 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5251 nameSize = 1;
5252 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005253 }
5254 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005255 SourceLocation startLoc;
5256 Expr *E = ND->getInit();
5257 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5258 startLoc = ECE->getLParenLoc();
5259 else
5260 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00005261 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005262 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005263 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005264 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005265 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005266 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005267 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005268 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005269 ByrefType += "sizeof(";
5270 RewriteByRefString(ByrefType, Name, ND);
5271 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005272 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005273 ByrefType += "__Block_byref_id_object_copy_";
5274 ByrefType += utostr(flag);
5275 ByrefType += ", __Block_byref_id_object_dispose_";
5276 ByrefType += utostr(flag);
5277 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005278 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005279 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005280
5281 // Complete the newly synthesized compound expression by inserting a right
5282 // curly brace before the end of the declaration.
5283 // FIXME: This approach avoids rewriting the initializer expression. It
5284 // also assumes there is only one declarator. For example, the following
5285 // isn't currently supported by this routine (in general):
5286 //
5287 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5288 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005289 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5290 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005291 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5292 SourceLocation semiLoc =
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005293 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005294
Benjamin Kramerd999b372010-02-14 14:14:16 +00005295 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005296 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005297 return;
5298}
5299
Mike Stump1eb44332009-09-09 15:08:12 +00005300void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005301 // Add initializers for any closure decl refs.
5302 GetBlockDeclRefExprs(Exp->getBody());
5303 if (BlockDeclRefs.size()) {
5304 // Unique all "by copy" declarations.
5305 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005306 if (!BlockDeclRefs[i]->isByRef()) {
5307 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5308 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5309 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5310 }
5311 }
Steve Naroff54055232008-10-27 17:20:55 +00005312 // Unique all "by ref" declarations.
5313 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5314 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005315 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5316 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5317 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5318 }
Steve Naroff54055232008-10-27 17:20:55 +00005319 }
5320 // Find any imported blocks...they will need special attention.
5321 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005322 if (BlockDeclRefs[i]->isByRef() ||
5323 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005324 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005325 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005326 }
5327}
5328
Chris Lattner5f9e2722011-07-23 10:55:15 +00005329FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005330 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005331 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005332 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5333 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00005334 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005335}
5336
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005337Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005338 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005339 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00005340 Blocks.push_back(Exp);
5341
5342 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005343
5344 // Add inner imported variables now used in current block.
5345 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005346 if (!InnerBlockDeclRefs.empty()) {
5347 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5348 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5349 ValueDecl *VD = Exp->getDecl();
5350 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005351 // We need to save the copied-in variables in nested
5352 // blocks because it is needed at the end for some of the API generations.
5353 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005354 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5355 BlockDeclRefs.push_back(Exp);
5356 BlockByCopyDeclsPtrSet.insert(VD);
5357 BlockByCopyDecls.push_back(VD);
5358 }
5359 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5360 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5361 BlockDeclRefs.push_back(Exp);
5362 BlockByRefDeclsPtrSet.insert(VD);
5363 BlockByRefDecls.push_back(VD);
5364 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005365 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005366 // Find any imported blocks...they will need special attention.
5367 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5368 if (InnerBlockDeclRefs[i]->isByRef() ||
5369 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5370 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5371 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005372 }
5373 InnerDeclRefsCount.push_back(countOfInnerDecls);
5374
Steve Narofffa15fd92008-10-28 20:29:00 +00005375 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005376
Steve Narofffa15fd92008-10-28 20:29:00 +00005377 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005378 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005379 else if (CurMethodDef)
5380 BuildUniqueMethodName(FuncName, CurMethodDef);
5381 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005382 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005383
Steve Narofffa15fd92008-10-28 20:29:00 +00005384 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005385
Steve Narofffa15fd92008-10-28 20:29:00 +00005386 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5387 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005388
Steve Narofffa15fd92008-10-28 20:29:00 +00005389 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005390 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5391 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005392
5393 FunctionDecl *FD;
5394 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005395
Steve Narofffa15fd92008-10-28 20:29:00 +00005396 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005397 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005398 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5399 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005400
Chris Lattner5f9e2722011-07-23 10:55:15 +00005401 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005402
Steve Narofffdc03722008-10-29 21:23:59 +00005403 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005404 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005405 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005406 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005407 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005408 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005409 InitExprs.push_back(castExpr);
5410
Steve Naroff01aec112009-12-06 21:14:13 +00005411 // Initialize the block descriptor.
5412 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005413
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005414 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5415 SourceLocation(), SourceLocation(),
5416 &Context->Idents.get(DescData.c_str()),
5417 Context->VoidPtrTy, 0,
5418 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005419 UnaryOperator *DescRefExpr =
5420 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5421 Context->VoidPtrTy,
5422 VK_LValue,
5423 SourceLocation()),
5424 UO_AddrOf,
5425 Context->getPointerType(Context->VoidPtrTy),
5426 VK_RValue, OK_Ordinary,
5427 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005428 InitExprs.push_back(DescRefExpr);
5429
Steve Narofffa15fd92008-10-28 20:29:00 +00005430 // Add initializers for any closure decl refs.
5431 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005432 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005433 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005434 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005435 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005436 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005437 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005438 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005439 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5440 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005441 if (HasLocalVariableExternalStorage(*I)) {
5442 QualType QT = (*I)->getType();
5443 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005444 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5445 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005446 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005447 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005448 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005449 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5450 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005451 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005452 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005453 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005454 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005455 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5456 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005457 if (HasLocalVariableExternalStorage(*I)) {
5458 QualType QT = (*I)->getType();
5459 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005460 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5461 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005462 }
5463
Steve Narofffa15fd92008-10-28 20:29:00 +00005464 }
Mike Stump1eb44332009-09-09 15:08:12 +00005465 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005466 }
5467 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005468 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005469 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005470 ValueDecl *ND = (*I);
5471 std::string Name(ND->getNameAsString());
5472 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005473 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005474 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5475 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005476 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005477 SourceLocation(), SourceLocation(),
5478 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005479 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5480 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5481
Daniel Dunbar4087f272010-08-17 22:39:59 +00005482 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005483 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5484 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005485 bool isNestedCapturedVar = false;
5486 if (block)
5487 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5488 ce = block->capture_end(); ci != ce; ++ci) {
5489 const VarDecl *variable = ci->getVariable();
5490 if (variable == ND && ci->isNested()) {
5491 assert (ci->isByRef() &&
5492 "SynthBlockInitExpr - captured block variable is not byref");
5493 isNestedCapturedVar = true;
5494 break;
5495 }
5496 }
5497 // captured nested byref variable has its address passed. Do not take
5498 // its address again.
5499 if (!isNestedCapturedVar)
5500 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005501 Context->getPointerType(Exp->getType()),
5502 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005503 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005504 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005505 }
5506 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005507 if (ImportedBlockDecls.size()) {
5508 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5509 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005510 unsigned IntSize =
5511 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005512 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5513 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005514 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005515 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005516 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005517 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005518 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005519 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005520 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005521 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005522 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005523 BlockDeclRefs.clear();
5524 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005525 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005526 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005527 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005528 ImportedBlockDecls.clear();
5529 return NewRep;
5530}
5531
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005532bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5533 if (const ObjCForCollectionStmt * CS =
5534 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5535 return CS->getElement() == DS;
5536 return false;
5537}
5538
Steve Narofffa15fd92008-10-28 20:29:00 +00005539//===----------------------------------------------------------------------===//
5540// Function Body / Expression rewriting
5541//===----------------------------------------------------------------------===//
5542
Steve Naroffc77a6362008-12-04 16:24:46 +00005543// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5544// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5545// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5546// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5547// Since the rewriter isn't capable of rewriting rewritten code, it's important
5548// we get this right.
5549void RewriteObjC::CollectPropertySetters(Stmt *S) {
5550 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005551 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffc77a6362008-12-04 16:24:46 +00005552 if (*CI)
5553 CollectPropertySetters(*CI);
5554
5555 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5556 if (BinOp->isAssignmentOp()) {
John McCall12f78a62010-12-02 01:19:52 +00005557 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5558 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005559 }
5560 }
5561}
5562
Steve Narofffa15fd92008-10-28 20:29:00 +00005563Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005564 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005565 isa<DoStmt>(S) || isa<ForStmt>(S))
5566 Stmts.push_back(S);
5567 else if (isa<ObjCForCollectionStmt>(S)) {
5568 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005569 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005570 }
Mike Stump1eb44332009-09-09 15:08:12 +00005571
Steve Narofffa15fd92008-10-28 20:29:00 +00005572 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005573
Steve Narofffa15fd92008-10-28 20:29:00 +00005574 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005575 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00005576 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005577 Stmt *newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005578 Stmt *ChildStmt = (*CI);
5579 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(ChildStmt)) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005580 Expr *OldBase = IvarRefExpr->getBase();
5581 bool replaced = false;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005582 newStmt = RewriteObjCNestedIvarRefExpr(ChildStmt, replaced);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005583 if (replaced) {
5584 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5585 ReplaceStmt(OldBase, IRE->getBase());
5586 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005587 ReplaceStmt(ChildStmt, newStmt);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005588 }
5589 }
5590 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005591 newStmt = RewriteFunctionBodyOrGlobalInitializer(ChildStmt);
5592 if (newStmt) {
5593 if (Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(ChildStmt))
5594 if (PropSetters[PropOrImplicitRefExpr] == S) {
5595 S = newStmt;
5596 newStmt = 0;
5597 }
5598 if (newStmt)
5599 *CI = newStmt;
5600 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005601 // If dealing with an assignment with LHS being a property reference
5602 // expression, the entire assignment tree is rewritten into a property
5603 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5604 // RHS again.
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005605 if (Expr *Exp = dyn_cast<Expr>(ChildStmt))
John McCall12f78a62010-12-02 01:19:52 +00005606 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005607 if (PropSetters[Exp]) {
5608 ++CI;
5609 continue;
5610 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005611 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005612 }
Mike Stump1eb44332009-09-09 15:08:12 +00005613
Steve Narofffa15fd92008-10-28 20:29:00 +00005614 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005615 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005616 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5617 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005618 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005619 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005620 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005621 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005622 Stmt *SaveCurrentBody = CurrentBody;
5623 CurrentBody = BE->getBody();
Fariborz Jahanian36178092011-04-08 23:48:29 +00005624 CollectPropertySetters(CurrentBody);
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005625 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005626 // block literal on rhs of a property-dot-sytax assignment
5627 // must be replaced by its synthesize ast so getRewrittenText
5628 // works as expected. In this case, what actually ends up on RHS
5629 // is the blockTranscribed which is the helper function for the
5630 // block literal; as in: self.c = ^() {[ace ARR];};
5631 bool saveDisableReplaceStmt = DisableReplaceStmt;
5632 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00005633 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005634 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005635 CurrentBody = SaveCurrentBody;
5636 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005637 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005638 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005639 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005640 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005641
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005642 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5643
Steve Narofffa15fd92008-10-28 20:29:00 +00005644 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005645 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005646 return blockTranscribed;
5647 }
5648 // Handle specific things.
5649 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5650 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005651
John McCall12f78a62010-12-02 01:19:52 +00005652 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005653 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5654 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5655
5656 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005657 if (BinOp) {
5658 // Because the rewriter doesn't allow us to rewrite rewritten code,
5659 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005660 DisableReplaceStmt = true;
5661 // Save the source range. Even if we disable the replacement, the
5662 // rewritten node will have been inserted into the tree. If the synthesized
5663 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005664 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005665 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5666 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005667 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005668 // Need to rewrite the ivar access expression if need be.
5669 if (isa<ObjCIvarRefExpr>(newStmt)) {
5670 bool replaced = false;
5671 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5672 }
5673
Steve Naroffb619d952008-12-09 12:56:34 +00005674 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005675 //
5676 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5677 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5678 // to see the original expression). Consider this example:
5679 //
5680 // Foo *obj1, *obj2;
5681 //
5682 // obj1.i = [obj2 rrrr];
5683 //
5684 // 'BinOp' for the previous expression looks like:
5685 //
5686 // (BinaryOperator 0x231ccf0 'int' '='
5687 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5688 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5689 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5690 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5691 //
5692 // 'newStmt' represents the rewritten message expression. For example:
5693 //
5694 // (CallExpr 0x231d300 'id':'struct objc_object *'
5695 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5696 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5697 // (CStyleCastExpr 0x231d220 'void *'
5698 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5699 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005700 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005701 // can be used as the setter argument. ReplaceStmt() will still 'see'
5702 // the original RHS (since we haven't altered BinOp).
5703 //
Mike Stump1eb44332009-09-09 15:08:12 +00005704 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005705 // node. As a result, we now leak the original AST nodes.
5706 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005707 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005708 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005709 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005710 }
5711 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005712
Steve Narofffa15fd92008-10-28 20:29:00 +00005713 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5714 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005715
Steve Narofffa15fd92008-10-28 20:29:00 +00005716 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5717 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005718
Steve Narofffa15fd92008-10-28 20:29:00 +00005719 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005720#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005721 // Before we rewrite it, put the original message expression in a comment.
5722 SourceLocation startLoc = MessExpr->getLocStart();
5723 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005724
Steve Narofffa15fd92008-10-28 20:29:00 +00005725 const char *startBuf = SM->getCharacterData(startLoc);
5726 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005727
Steve Narofffa15fd92008-10-28 20:29:00 +00005728 std::string messString;
5729 messString += "// ";
5730 messString.append(startBuf, endBuf-startBuf+1);
5731 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005732
5733 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005734 // InsertText(clang::SourceLocation, char const*, unsigned int).
5735 // InsertText(startLoc, messString.c_str(), messString.size());
5736 // Tried this, but it didn't work either...
5737 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005738#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005739 return RewriteMessageExpr(MessExpr);
5740 }
Mike Stump1eb44332009-09-09 15:08:12 +00005741
Steve Narofffa15fd92008-10-28 20:29:00 +00005742 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5743 return RewriteObjCTryStmt(StmtTry);
5744
5745 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5746 return RewriteObjCSynchronizedStmt(StmtTry);
5747
5748 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5749 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005750
Steve Narofffa15fd92008-10-28 20:29:00 +00005751 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5752 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005753
5754 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005755 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005756 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005757 OrigStmtRange.getEnd());
5758 if (BreakStmt *StmtBreakStmt =
5759 dyn_cast<BreakStmt>(S))
5760 return RewriteBreakStmt(StmtBreakStmt);
5761 if (ContinueStmt *StmtContinueStmt =
5762 dyn_cast<ContinueStmt>(S))
5763 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005764
5765 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005766 // and cast exprs.
5767 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5768 // FIXME: What we're doing here is modifying the type-specifier that
5769 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005770 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005771 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5772 // the context of an ObjCForCollectionStmt. For example:
5773 // NSArray *someArray;
5774 // for (id <FooProtocol> index in someArray) ;
5775 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5776 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005777 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005778 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005779
Steve Narofffa15fd92008-10-28 20:29:00 +00005780 // Blocks rewrite rules.
5781 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5782 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005783 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005784 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005785 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005786 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005787 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005788 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005789 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005790 if (VD->hasAttr<BlocksAttr>()) {
5791 static unsigned uniqueByrefDeclCount = 0;
5792 assert(!BlockByRefDeclNo.count(ND) &&
5793 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5794 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005795 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005796 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005797 else
5798 RewriteTypeOfDecl(VD);
5799 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005800 }
Richard Smith162e1c12011-04-15 14:24:37 +00005801 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005802 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005803 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005804 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005805 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5806 }
5807 }
5808 }
Mike Stump1eb44332009-09-09 15:08:12 +00005809
Steve Narofffa15fd92008-10-28 20:29:00 +00005810 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5811 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005812
5813 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005814 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5815 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005816 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5817 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005818 && "Statement stack mismatch");
5819 Stmts.pop_back();
5820 }
5821 // Handle blocks rewriting.
5822 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5823 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005824 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005825 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005826 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5827 ValueDecl *VD = DRE->getDecl();
5828 if (VD->hasAttr<BlocksAttr>())
5829 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005830 if (HasLocalVariableExternalStorage(VD))
5831 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005832 }
5833
Steve Narofffa15fd92008-10-28 20:29:00 +00005834 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005835 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005836 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005837 ReplaceStmt(S, BlockCall);
5838 return BlockCall;
5839 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005840 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005841 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005842 RewriteCastExpr(CE);
5843 }
5844#if 0
5845 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005846 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5847 ICE->getSubExpr(),
5848 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005849 // Get the new text.
5850 std::string SStr;
5851 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005852 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005853 const std::string &Str = Buf.str();
5854
5855 printf("CAST = %s\n", &Str[0]);
5856 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5857 delete S;
5858 return Replacement;
5859 }
5860#endif
5861 // Return this stmt unmodified.
5862 return S;
5863}
5864
Steve Naroff3d7e7862009-12-05 15:55:59 +00005865void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5866 for (RecordDecl::field_iterator i = RD->field_begin(),
5867 e = RD->field_end(); i != e; ++i) {
5868 FieldDecl *FD = *i;
5869 if (isTopLevelBlockPointerType(FD->getType()))
5870 RewriteBlockPointerDecl(FD);
5871 if (FD->getType()->isObjCQualifiedIdType() ||
5872 FD->getType()->isObjCQualifiedInterfaceType())
5873 RewriteObjCQualifiedInterfaceTypes(FD);
5874 }
5875}
5876
Steve Narofffa15fd92008-10-28 20:29:00 +00005877/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5878/// main file of the input.
5879void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5880 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005881 if (FD->isOverloadedOperator())
5882 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005883
Steve Narofffa15fd92008-10-28 20:29:00 +00005884 // Since function prototypes don't have ParmDecl's, we check the function
5885 // prototype. This enables us to rewrite function declarations and
5886 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005887 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005888
Sebastian Redld3a413d2009-04-26 20:35:05 +00005889 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005890 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005891 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005892 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005893 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005894 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005895 Body =
5896 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5897 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005898 CurrentBody = 0;
5899 if (PropParentMap) {
5900 delete PropParentMap;
5901 PropParentMap = 0;
5902 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005903 // This synthesizes and inserts the block "impl" struct, invoke function,
5904 // and any copy/dispose helper functions.
5905 InsertBlockLiteralsWithinFunction(FD);
5906 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005907 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005908 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005909 return;
5910 }
5911 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005912 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005913 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005914 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005915 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005916 Body =
5917 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5918 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005919 CurrentBody = 0;
5920 if (PropParentMap) {
5921 delete PropParentMap;
5922 PropParentMap = 0;
5923 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005924 InsertBlockLiteralsWithinMethod(MD);
5925 CurMethodDef = 0;
5926 }
5927 }
5928 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5929 ClassImplementation.push_back(CI);
5930 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5931 CategoryImplementation.push_back(CI);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005932 else if (isa<ObjCClassDecl>(D))
5933 assert(false && "RewriteObjC::HandleDeclInMainFile - ObjCClassDecl");
Steve Narofffa15fd92008-10-28 20:29:00 +00005934 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5935 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005936 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005937 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005938 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005939 CheckFunctionPointerDecl(VD->getType(), VD);
5940 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005941 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005942 RewriteCastExpr(CE);
5943 }
5944 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005945 } else if (VD->getType()->isRecordType()) {
5946 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5947 if (RD->isDefinition())
5948 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005949 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005950 if (VD->getInit()) {
5951 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005952 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005953 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005954 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005955 CurrentBody = 0;
5956 if (PropParentMap) {
5957 delete PropParentMap;
5958 PropParentMap = 0;
5959 }
Mike Stump1eb44332009-09-09 15:08:12 +00005960 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005961 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005962 GlobalVarDecl = 0;
5963
5964 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005965 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005966 RewriteCastExpr(CE);
5967 }
5968 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005969 return;
5970 }
Richard Smith162e1c12011-04-15 14:24:37 +00005971 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005972 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005973 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005974 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005975 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5976 return;
5977 }
5978 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005979 if (RD->isDefinition())
5980 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005981 return;
5982 }
5983 // Nothing yet.
5984}
5985
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005986void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005987 if (Diags.hasErrorOccurred())
5988 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005989
Steve Narofffa15fd92008-10-28 20:29:00 +00005990 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005991
Steve Naroff621edce2009-04-29 16:37:50 +00005992 // Here's a great place to add any extra declarations that may be needed.
5993 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005994 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005995 E = ProtocolExprDecls.end(); I != E; ++I)
5996 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5997
Benjamin Kramerd999b372010-02-14 14:14:16 +00005998 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005999 if (ClassImplementation.size() || CategoryImplementation.size())
6000 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00006001
Steve Narofffa15fd92008-10-28 20:29:00 +00006002 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6003 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00006004 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00006005 Rewrite.getRewriteBufferFor(MainFileID)) {
6006 //printf("Changed:\n");
6007 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6008 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00006009 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00006010 }
Steve Narofface66252008-11-13 20:07:04 +00006011
Steve Naroff621edce2009-04-29 16:37:50 +00006012 if (ClassImplementation.size() || CategoryImplementation.size() ||
6013 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00006014 // Rewrite Objective-c meta data*
6015 std::string ResultStr;
6016 SynthesizeMetaDataIntoBuffer(ResultStr);
6017 // Emit metadata.
6018 *OutFile << ResultStr;
6019 }
Steve Narofffa15fd92008-10-28 20:29:00 +00006020 OutFile->flush();
6021}