blob: 19277e8ea45e33e92fda7d6688b44f7e7e08f903 [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 Jahaniand5c3fa22011-12-08 18:25:15 +000035 protected:
36
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000037 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000038 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000039 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000043 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000044 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000045 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000046 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
Fariborz Jahanian58457172011-12-05 18:43:13 +000058 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000059
Chris Lattner2c64b7b2007-10-16 21:07:07 +000060 Rewriter Rewrite;
David Blaikied6471f72011-09-25 23:23:43 +000061 DiagnosticsEngine &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000062 const LangOptions &LangOpts;
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;
Fariborz Jahanian58457172011-12-05 18:43:13 +000068 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000070 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
76 unsigned RewriteFailedDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000077 // ObjC string constant support.
78 unsigned NumObjCStringLiterals;
79 VarDecl *ConstantStringClassReference;
80 RecordDecl *NSStringRecord;
Fariborz Jahanian58457172011-12-05 18:43:13 +000081
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000082 // ObjC foreach break/continue generation support.
83 int BcLabelCount;
84
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000085 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000086 // Needed for super.
87 ObjCMethodDecl *CurMethodDef;
88 RecordDecl *SuperStructDecl;
89 RecordDecl *ConstantStringDecl;
90
91 FunctionDecl *MsgSendFunctionDecl;
92 FunctionDecl *MsgSendSuperFunctionDecl;
93 FunctionDecl *MsgSendStretFunctionDecl;
94 FunctionDecl *MsgSendSuperStretFunctionDecl;
95 FunctionDecl *MsgSendFpretFunctionDecl;
96 FunctionDecl *GetClassFunctionDecl;
97 FunctionDecl *GetMetaClassFunctionDecl;
98 FunctionDecl *GetSuperClassFunctionDecl;
99 FunctionDecl *SelGetUidFunctionDecl;
100 FunctionDecl *CFStringFunctionDecl;
101 FunctionDecl *SuperContructorFunctionDecl;
102 FunctionDecl *CurFunctionDef;
103 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000105 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner5f9e2722011-07-23 10:55:15 +0000106 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
107 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +0000109 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
111 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000112 SmallVector<Stmt *, 32> Stmts;
113 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +0000114 // Remember all the @protocol(<expr>) expressions.
115 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000116
117 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff54055232008-10-27 17:20:55 +0000118
119 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000120 SmallVector<BlockExpr *, 32> Blocks;
121 SmallVector<int, 32> InnerDeclRefsCount;
122 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000123
Chris Lattner5f9e2722011-07-23 10:55:15 +0000124 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Steve Naroff54055232008-10-27 17:20:55 +0000126 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000129 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000131 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000133 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
134
Steve Naroff54055232008-10-27 17:20:55 +0000135 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
136
Steve Naroff4c3580e2008-12-04 23:50:32 +0000137 // This maps an original source AST to it's rewritten form. This allows
138 // us to avoid rewriting the same node twice (which is very uncommon).
139 // This is needed to support some of the exotic property rewriting.
140 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000141
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000142 // Needed for header files being rewritten
143 bool IsHeader;
144 bool SilenceRewriteMacroWarning;
145 bool objc_impl_method;
146
Steve Naroffb619d952008-12-09 12:56:34 +0000147 bool DisableReplaceStmt;
John McCall4b9c2d22011-11-06 09:01:30 +0000148 class DisableReplaceStmtScope {
149 RewriteObjC &R;
150 bool SavedValue;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000151
John McCall4b9c2d22011-11-06 09:01:30 +0000152 public:
153 DisableReplaceStmtScope(RewriteObjC &R)
154 : R(R), SavedValue(R.DisableReplaceStmt) {
155 R.DisableReplaceStmt = true;
156 }
157 ~DisableReplaceStmtScope() {
158 R.DisableReplaceStmt = SavedValue;
159 }
160 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000161 void InitializeCommon(ASTContext &context);
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Chris Lattner77cd2a02007-10-11 00:43:27 +0000163 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000164
Chris Lattnerf04da132007-10-24 17:06:59 +0000165 // Top Level Driver code.
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000166 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000167 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000168 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
169 if (!Class->isThisDeclarationADefinition()) {
170 RewriteForwardClassDecl(D);
171 break;
172 }
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000173 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000174
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000175 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
176 if (!Proto->isThisDeclarationADefinition()) {
177 RewriteForwardProtocolDecl(D);
178 break;
179 }
180 }
181
Chris Lattner682bf922009-03-29 16:50:03 +0000182 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000183 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000184 return true;
Chris Lattner682bf922009-03-29 16:50:03 +0000185 }
186 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000187 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000188 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000189 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000190 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000191
192 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000194 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000196 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000197 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Steve Naroff4c3580e2008-12-04 23:50:32 +0000199 if (ReplacingStmt)
200 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000201
Steve Naroffb619d952008-12-09 12:56:34 +0000202 if (DisableReplaceStmt)
John McCall4b9c2d22011-11-06 09:01:30 +0000203 return;
Steve Naroffb619d952008-12-09 12:56:34 +0000204
Steve Naroff4c3580e2008-12-04 23:50:32 +0000205 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000206 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000207 ReplacedNodes[Old] = New;
208 return;
209 }
210 if (SilenceRewriteMacroWarning)
211 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000212 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
213 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000214 }
Steve Naroffb619d952008-12-09 12:56:34 +0000215
216 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
John McCall4b9c2d22011-11-06 09:01:30 +0000217 if (DisableReplaceStmt)
218 return;
219
Nick Lewycky7e749242010-10-31 21:07:24 +0000220 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000221 int Size = Rewrite.getRangeSize(SrcRange);
222 if (Size == -1) {
223 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
224 << Old->getSourceRange();
225 return;
226 }
227 // Get the new text.
228 std::string SStr;
229 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000230 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000231 const std::string &Str = S.str();
232
233 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000234 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000235 ReplacedNodes[Old] = New;
236 return;
237 }
238 if (SilenceRewriteMacroWarning)
239 return;
240 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
241 << Old->getSourceRange();
242 }
243
Chris Lattner5f9e2722011-07-23 10:55:15 +0000244 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000245 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000246 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000247 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000248 SilenceRewriteMacroWarning)
249 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000251 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
252 }
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Chris Lattneraadaf782008-01-31 19:51:04 +0000254 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000255 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000256 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000257 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000258 SilenceRewriteMacroWarning)
259 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Chris Lattneraadaf782008-01-31 19:51:04 +0000261 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
262 }
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Chris Lattnerf04da132007-10-24 17:06:59 +0000264 // Syntactic Rewriting.
Fariborz Jahanian58457172011-12-05 18:43:13 +0000265 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000266 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000267 void RewriteForwardClassDecl(DeclGroupRef D);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000268 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
Douglas Gregor375bb142011-12-27 22:43:10 +0000269 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000270 const std::string &typedefString);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000271 void RewriteImplementations();
Steve Naroffa0876e82008-12-02 17:36:43 +0000272 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
273 ObjCImplementationDecl *IMD,
274 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000275 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000276 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000277 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
278 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000279 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
280 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000281 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000282 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000283 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
284 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000285 void RewriteForwardProtocolDecl(DeclGroupRef D);
286 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000287 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000288 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000289 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000290 void RewriteBlockPointerType(std::string& Str, QualType Type);
291 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000292 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000293 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000294 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000295 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000296
Chris Lattnerf04da132007-10-24 17:06:59 +0000297 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000298 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000299 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCall4b9c2d22011-11-06 09:01:30 +0000300 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
301 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffb42f8412007-11-05 14:50:49 +0000302 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000303 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000304 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000305 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000306 void RewriteTryReturnStmts(Stmt *S);
307 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000308 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000309 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000310 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000311 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
312 SourceLocation OrigEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000313 Stmt *RewriteBreakStmt(BreakStmt *S);
314 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000315 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000316
Steve Naroff54055232008-10-27 17:20:55 +0000317 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000318 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000319
Mike Stump1eb44332009-09-09 15:08:12 +0000320 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000321 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000322 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000323 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000324 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000325 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000326
327 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
328 std::string &Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000329
330 virtual void Initialize(ASTContext &context) = 0;
331
332 // Metadata Rewriting.
333 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
334 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
335 StringRef prefix,
336 StringRef ClassName,
337 std::string &Result) = 0;
338 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
339 std::string &Result) = 0;
340 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
341 StringRef prefix,
342 StringRef ClassName,
343 std::string &Result) = 0;
344 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
345 std::string &Result) = 0;
346
347 // Rewriting ivar access
348 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
349 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
350 std::string &Result) = 0;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000351
352 // Misc. AST transformation routines. Somtimes they end up calling
353 // rewriting routines on the new ASTs.
354 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
355 Expr **args, unsigned nargs,
356 SourceLocation StartLoc=SourceLocation(),
357 SourceLocation EndLoc=SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Fariborz Jahanian58457172011-12-05 18:43:13 +0000359 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
360 SourceLocation StartLoc=SourceLocation(),
361 SourceLocation EndLoc=SourceLocation());
362
363 void SynthCountByEnumWithState(std::string &buf);
364 void SynthMsgSendFunctionDecl();
365 void SynthMsgSendSuperFunctionDecl();
366 void SynthMsgSendStretFunctionDecl();
367 void SynthMsgSendFpretFunctionDecl();
368 void SynthMsgSendSuperStretFunctionDecl();
369 void SynthGetClassFunctionDecl();
370 void SynthGetMetaClassFunctionDecl();
371 void SynthGetSuperClassFunctionDecl();
372 void SynthSelGetUidFunctionDecl();
373 void SynthSuperContructorFunctionDecl();
374
375 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump1eb44332009-09-09 15:08:12 +0000376 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000377 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000378 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000379 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000380 std::string SynthesizeBlockImpl(BlockExpr *CE,
381 std::string Tag, std::string Desc);
382 std::string SynthesizeBlockDescriptor(std::string DescTag,
383 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000384 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000385 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000386 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000387 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000388 StringRef FunName);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000389 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
390 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
391 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Fariborz Jahanian58457172011-12-05 18:43:13 +0000393 // Misc. helper routines.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000394 QualType getProtocolType();
Fariborz Jahanian58457172011-12-05 18:43:13 +0000395 void WarnAboutReturnGotoStmts(Stmt *S);
396 void HasReturnStmts(Stmt *S, bool &hasReturns);
397 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
398 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
399 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
400
401 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff54055232008-10-27 17:20:55 +0000402 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000403 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000404 void GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000405 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000406 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Steve Naroff54055232008-10-27 17:20:55 +0000408 // We avoid calling Type::isBlockPointerType(), since it operates on the
409 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000410 bool isTopLevelBlockPointerType(QualType T) {
411 return isa<BlockPointerType>(T);
412 }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000414 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
415 /// to a function pointer type and upon success, returns true; false
416 /// otherwise.
417 bool convertBlockPointerToFunctionPointer(QualType &T) {
418 if (isTopLevelBlockPointerType(T)) {
419 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
420 T = Context->getPointerType(BPT->getPointeeType());
421 return true;
422 }
423 return false;
424 }
425
Fariborz Jahanian58457172011-12-05 18:43:13 +0000426 bool needToScanForQualifiers(QualType T);
427 QualType getSuperStructType();
428 QualType getConstantStringStructType();
429 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
430 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
431
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000432 void convertToUnqualifiedObjCType(QualType &T) {
433 if (T->isObjCQualifiedIdType())
434 T = Context->getObjCIdType();
435 else if (T->isObjCQualifiedClassType())
436 T = Context->getObjCClassType();
437 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000438 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
439 if (const ObjCObjectPointerType * OBJPT =
440 T->getAsObjCInterfacePointerType()) {
441 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
442 T = QualType(IFaceT, 0);
443 T = Context->getPointerType(T);
444 }
445 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000446 }
447
Steve Naroff54055232008-10-27 17:20:55 +0000448 // FIXME: This predicate seems like it would be useful to add to ASTContext.
449 bool isObjCType(QualType T) {
450 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
451 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Steve Naroff54055232008-10-27 17:20:55 +0000453 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Steve Naroff54055232008-10-27 17:20:55 +0000455 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
456 OCT == Context->getCanonicalType(Context->getObjCClassType()))
457 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Ted Kremenek6217b802009-07-29 21:53:49 +0000459 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000460 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000461 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000462 return true;
463 }
464 return false;
465 }
466 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000467 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000468 void GetExtentOfArgList(const char *Name, const char *&LParen,
469 const char *&RParen);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000470
Steve Naroff621edce2009-04-29 16:37:50 +0000471 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000472 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000473 if (From[i] == '"')
474 To += "\\\"";
475 else
476 To += From[i];
477 }
478 }
John McCalle23cf432010-12-14 08:05:40 +0000479
480 QualType getSimpleFunctionType(QualType result,
481 const QualType *args,
482 unsigned numArgs,
483 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000484 if (result == Context->getObjCInstanceType())
485 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000486 FunctionProtoType::ExtProtoInfo fpi;
487 fpi.Variadic = variadic;
488 return Context->getFunctionType(result, args, numArgs, fpi);
489 }
John McCall9d125032010-01-15 18:39:57 +0000490
Fariborz Jahanian58457172011-12-05 18:43:13 +0000491 // Helper function: create a CStyleCastExpr with trivial type source info.
492 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
493 CastKind Kind, Expr *E) {
494 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
495 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
496 SourceLocation(), SourceLocation());
497 }
498 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000499
500 class RewriteObjCFragileABI : public RewriteObjC {
501 public:
502
503 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
504 DiagnosticsEngine &D, const LangOptions &LOpts,
505 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
506 D, LOpts,
507 silenceMacroWarn) {}
508
509 ~RewriteObjCFragileABI() {}
510 virtual void Initialize(ASTContext &context);
511
512 // Rewriting metadata
513 template<typename MethodIterator>
514 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
515 MethodIterator MethodEnd,
516 bool IsInstanceMethod,
517 StringRef prefix,
518 StringRef ClassName,
519 std::string &Result);
520 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
521 StringRef prefix,
522 StringRef ClassName,
523 std::string &Result);
524 virtual void RewriteObjCProtocolListMetaData(
525 const ObjCList<ObjCProtocolDecl> &Prots,
526 StringRef prefix, StringRef ClassName, std::string &Result);
527 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
528 std::string &Result);
529 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
530 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
531 std::string &Result);
532
533 // Rewriting ivar
534 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
535 std::string &Result);
536 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
537 };
Chris Lattner77cd2a02007-10-11 00:43:27 +0000538}
539
Mike Stump1eb44332009-09-09 15:08:12 +0000540void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
541 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000542 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000543 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000544 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000545 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000546 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000547 // All the args are checked/rewritten. Don't call twice!
548 RewriteBlockPointerDecl(D);
549 break;
550 }
551 }
552}
553
554void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000555 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000556 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000557 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000558}
559
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000560static bool IsHeaderFile(const std::string &Filename) {
561 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000563 if (DotPos == std::string::npos) {
564 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000565 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000566 }
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000568 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
569 // C header: .h
570 // C++ header: .hh or .H;
571 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000572}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000573
Chris Lattner5f9e2722011-07-23 10:55:15 +0000574RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000575 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000576 bool silenceMacroWarn)
577 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
578 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000579 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000580 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000581 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000582 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
583 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000584 "rewriter doesn't support user-specified control flow semantics "
585 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000586}
587
Eli Friedmanbce831b2009-05-18 22:29:17 +0000588ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000589 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000590 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000591 const LangOptions &LOpts,
592 bool SilenceRewriteMacroWarning) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000593 if (true /*!LOpts.ObjCNonFragileABI*/)
594 return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
595 else {
596 assert(false && "objective-C rewriter for nonfragile ABI = NYI");
597 return 0;
598 }
Chris Lattnere365c502007-11-30 22:25:36 +0000599}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000600
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000601void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000602 Context = &context;
603 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000604 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000605 MsgSendFunctionDecl = 0;
606 MsgSendSuperFunctionDecl = 0;
607 MsgSendStretFunctionDecl = 0;
608 MsgSendSuperStretFunctionDecl = 0;
609 MsgSendFpretFunctionDecl = 0;
610 GetClassFunctionDecl = 0;
611 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000612 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000613 SelGetUidFunctionDecl = 0;
614 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000615 ConstantStringClassReference = 0;
616 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000617 CurMethodDef = 0;
618 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000619 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000620 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000621 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000622 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000623 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000624 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000625 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000626 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000627 PropParentMap = 0;
628 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000629 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000630 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000632 // Get the ID and start/end of the main file.
633 MainFileID = SM->getMainFileID();
634 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
635 MainFileStart = MainBuf->getBufferStart();
636 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Chris Lattner2c78b872009-04-14 23:22:57 +0000638 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000639}
640
Chris Lattnerf04da132007-10-24 17:06:59 +0000641//===----------------------------------------------------------------------===//
642// Top Level Driver Code
643//===----------------------------------------------------------------------===//
644
Chris Lattner682bf922009-03-29 16:50:03 +0000645void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000646 if (Diags.hasErrorOccurred())
647 return;
648
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000649 // Two cases: either the decl could be in the main file, or it could be in a
650 // #included file. If the former, rewrite it now. If the later, check to see
651 // if we rewrote the #include/#import.
652 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000653 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000654
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000655 // If this is for a builtin, ignore it.
656 if (Loc.isInvalid()) return;
657
Steve Naroffebf2b562007-10-23 23:50:29 +0000658 // Look for built-in declarations that we need to refer during the rewrite.
659 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000660 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000661 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000662 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000663 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000664 ConstantStringClassReference = FVD;
665 return;
666 }
Douglas Gregor7723fec2011-12-15 20:29:51 +0000667 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
668 if (ID->isThisDeclarationADefinition())
669 RewriteInterfaceDecl(ID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000670 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000671 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000672 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000673 if (PD->isThisDeclarationADefinition())
674 RewriteProtocolDecl(PD);
Douglas Gregord0434102009-01-09 00:49:46 +0000675 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
676 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000677 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
678 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000679 DI != DIEnd; ) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000680 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
681 if (!IFace->isThisDeclarationADefinition()) {
682 SmallVector<Decl *, 8> DG;
683 SourceLocation StartLoc = IFace->getLocStart();
684 do {
685 if (isa<ObjCInterfaceDecl>(*DI) &&
686 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
687 StartLoc == (*DI)->getLocStart())
688 DG.push_back(*DI);
689 else
690 break;
691
Douglas Gregor7723fec2011-12-15 20:29:51 +0000692 ++DI;
Douglas Gregor375bb142011-12-27 22:43:10 +0000693 } while (DI != DIEnd);
694 RewriteForwardClassDecl(DG);
695 continue;
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000696 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000697 }
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000698
699 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
700 if (!Proto->isThisDeclarationADefinition()) {
701 SmallVector<Decl *, 8> DG;
702 SourceLocation StartLoc = Proto->getLocStart();
703 do {
704 if (isa<ObjCProtocolDecl>(*DI) &&
705 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
706 StartLoc == (*DI)->getLocStart())
707 DG.push_back(*DI);
708 else
709 break;
710
711 ++DI;
712 } while (DI != DIEnd);
713 RewriteForwardProtocolDecl(DG);
714 continue;
715 }
716 }
717
Chris Lattner682bf922009-03-29 16:50:03 +0000718 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000719 ++DI;
720 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000721 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000722 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000723 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000724 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000725}
726
Chris Lattnerf04da132007-10-24 17:06:59 +0000727//===----------------------------------------------------------------------===//
728// Syntactic (non-AST) Rewriting Code
729//===----------------------------------------------------------------------===//
730
Steve Naroffb29b4272008-04-14 22:03:09 +0000731void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000732 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000733 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000734 const char *MainBufStart = MainBuf.begin();
735 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000736 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000738 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000739 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
740 if (*BufPtr == '#') {
741 if (++BufPtr == MainBufEnd)
742 return;
743 while (*BufPtr == ' ' || *BufPtr == '\t')
744 if (++BufPtr == MainBufEnd)
745 return;
746 if (!strncmp(BufPtr, "import", ImportLen)) {
747 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000748 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000749 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000750 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000751 BufPtr += ImportLen;
752 }
753 }
754 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000755}
756
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000757static std::string getIvarAccessString(ObjCIvarDecl *OID) {
758 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000759 std::string S;
760 S = "((struct ";
761 S += ClassDecl->getIdentifier()->getName();
762 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000763 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000764 return S;
765}
766
Steve Naroffa0876e82008-12-02 17:36:43 +0000767void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
768 ObjCImplementationDecl *IMD,
769 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000770 static bool objcGetPropertyDefined = false;
771 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000772 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000773 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000774 const char *startBuf = SM->getCharacterData(startLoc);
775 assert((*startBuf == '@') && "bogus @synthesize location");
776 const char *semiBuf = strchr(startBuf, ';');
777 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000778 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000779 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000780
781 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
782 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Steve Naroffeb0646c2008-12-02 15:48:25 +0000784 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000785 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000786 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000788 if (!OID)
789 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000790 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000791 if (!PD->getGetterMethodDecl()->isDefined()) {
792 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
793 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
794 ObjCPropertyDecl::OBJC_PR_copy));
795 std::string Getr;
796 if (GenGetProperty && !objcGetPropertyDefined) {
797 objcGetPropertyDefined = true;
798 // FIXME. Is this attribute correct in all cases?
799 Getr = "\nextern \"C\" __declspec(dllimport) "
800 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000801 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000802 RewriteObjCMethodDecl(OID->getContainingInterface(),
803 PD->getGetterMethodDecl(), Getr);
804 Getr += "{ ";
805 // Synthesize an explicit cast to gain access to the ivar.
806 // See objc-act.c:objc_synthesize_new_getter() for details.
807 if (GenGetProperty) {
808 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
809 Getr += "typedef ";
810 const FunctionType *FPRetType = 0;
811 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
812 FPRetType);
813 Getr += " _TYPE";
814 if (FPRetType) {
815 Getr += ")"; // close the precedence "scope" for "*".
816
817 // Now, emit the argument types (if any).
818 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
819 Getr += "(";
820 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
821 if (i) Getr += ", ";
822 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +0000823 Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000824 Getr += ParamStr;
825 }
826 if (FT->isVariadic()) {
827 if (FT->getNumArgs()) Getr += ", ";
828 Getr += "...";
829 }
830 Getr += ")";
831 } else
832 Getr += "()";
833 }
834 Getr += ";\n";
835 Getr += "return (_TYPE)";
836 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000837 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000838 Getr += ", 1)";
839 }
840 else
841 Getr += "return " + getIvarAccessString(OID);
842 Getr += "; }";
843 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000844 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000845
846 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000847 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Steve Naroffeb0646c2008-12-02 15:48:25 +0000849 // Generate the 'setter' function.
850 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000851 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
852 ObjCPropertyDecl::OBJC_PR_copy);
853 if (GenSetProperty && !objcSetPropertyDefined) {
854 objcSetPropertyDefined = true;
855 // FIXME. Is this attribute correct in all cases?
856 Setr = "\nextern \"C\" __declspec(dllimport) "
857 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
858 }
859
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000860 RewriteObjCMethodDecl(OID->getContainingInterface(),
861 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000862 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000863 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000864 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000865 if (GenSetProperty) {
866 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000867 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000868 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000869 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000870 Setr += ", ";
871 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
872 Setr += "0, ";
873 else
874 Setr += "1, ";
875 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
876 Setr += "1)";
877 else
878 Setr += "0)";
879 }
880 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000881 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000882 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000883 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000884 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000885 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000886}
Chris Lattner8a12c272007-10-11 18:38:32 +0000887
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000888static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
889 std::string &typedefString) {
890 typedefString += "#ifndef _REWRITER_typedef_";
891 typedefString += ForwardDecl->getNameAsString();
892 typedefString += "\n";
893 typedefString += "#define _REWRITER_typedef_";
894 typedefString += ForwardDecl->getNameAsString();
895 typedefString += "\n";
896 typedefString += "typedef struct objc_object ";
897 typedefString += ForwardDecl->getNameAsString();
898 typedefString += ";\n#endif\n";
899}
900
Douglas Gregor375bb142011-12-27 22:43:10 +0000901void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000902 const std::string &typedefString) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000903 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000904 const char *startBuf = SM->getCharacterData(startLoc);
905 const char *semiPtr = strchr(startBuf, ';');
906 // Replace the @class with typedefs corresponding to the classes.
907 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
908}
909
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000910void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000911 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000912 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000913 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000914 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000915 // Translate to typedef's that forward reference structs with the same name
916 // as the class. As a convenience, we include the original declaration
917 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000918 typedefString += "// @class ";
919 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000920 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000921 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000922 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000923 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000924 DeclGroupRef::iterator I = D.begin();
Douglas Gregor375bb142011-12-27 22:43:10 +0000925 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000926}
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000928void RewriteObjC::RewriteForwardClassDecl(
929 const llvm::SmallVector<Decl*, 8> &D) {
930 std::string typedefString;
931 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000932 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000933 if (i == 0) {
934 typedefString += "// @class ";
935 typedefString += ForwardDecl->getNameAsString();
936 typedefString += ";\n";
937 }
938 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
939 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000940 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000941}
942
Steve Naroffb29b4272008-04-14 22:03:09 +0000943void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000944 // When method is a synthesized one, such as a getter/setter there is
945 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000946 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000947 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000948 SourceLocation LocStart = Method->getLocStart();
949 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Chandler Carruth64211622011-07-25 21:09:52 +0000951 if (SM->getExpansionLineNumber(LocEnd) >
952 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000953 InsertText(LocStart, "#if 0\n");
954 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000955 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000956 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000957 }
958}
959
Mike Stump1eb44332009-09-09 15:08:12 +0000960void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000961 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000962
Benjamin Kramerd999b372010-02-14 14:14:16 +0000963 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000964 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000965}
966
Steve Naroffb29b4272008-04-14 22:03:09 +0000967void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000968 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Steve Naroff423cb562007-10-30 13:30:57 +0000970 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000971 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000973 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
974 E = CatDecl->prop_end(); I != E; ++I)
975 RewriteProperty(*I);
976
Mike Stump1eb44332009-09-09 15:08:12 +0000977 for (ObjCCategoryDecl::instmeth_iterator
978 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000979 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000980 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000981 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000982 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000983 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000984 RewriteMethodDeclaration(*I);
985
Steve Naroff423cb562007-10-30 13:30:57 +0000986 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000987 ReplaceText(CatDecl->getAtEndRange().getBegin(),
988 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000989}
990
Steve Naroffb29b4272008-04-14 22:03:09 +0000991void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000992 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Steve Naroff752d6ef2007-10-30 16:42:30 +0000994 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000995 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000996
997 for (ObjCProtocolDecl::instmeth_iterator
998 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000999 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001000 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001001 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001002 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001003 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001004 RewriteMethodDeclaration(*I);
1005
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001006 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1007 E = PDecl->prop_end(); I != E; ++I)
1008 RewriteProperty(*I);
1009
Steve Naroff752d6ef2007-10-30 16:42:30 +00001010 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001011 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001012 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001013
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001014 // Must comment out @optional/@required
1015 const char *startBuf = SM->getCharacterData(LocStart);
1016 const char *endBuf = SM->getCharacterData(LocEnd);
1017 for (const char *p = startBuf; p < endBuf; p++) {
1018 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001019 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001020 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001021
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001022 }
1023 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001024 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001025 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001027 }
1028 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001029}
1030
Douglas Gregorbd9482d2012-01-01 21:23:57 +00001031void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1032 SourceLocation LocStart = (*D.begin())->getLocStart();
1033 if (LocStart.isInvalid())
1034 llvm_unreachable("Invalid SourceLocation");
1035 // FIXME: handle forward protocol that are declared across multiple lines.
1036 ReplaceText(LocStart, 0, "// ");
1037}
1038
1039void
1040RewriteObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1041 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001042 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001043 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001044 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001045 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001046}
1047
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001048void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1049 const FunctionType *&FPRetType) {
1050 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001051 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001052 else if (T->isFunctionPointerType() ||
1053 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001054 // needs special handling, since pointer-to-functions have special
1055 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001056 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001057 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001058 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001059 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001060 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001061 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001062 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001063 ResultStr += FPRetType->getResultType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001064 Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001065 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001066 }
1067 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001068 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001069}
1070
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001071void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1072 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001073 std::string &ResultStr) {
1074 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1075 const FunctionType *FPRetType = 0;
1076 ResultStr += "\nstatic ";
1077 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001078 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001080 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001081 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001083 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001084 NameStr += "_I_";
1085 else
1086 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001088 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001089 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001090
1091 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001092 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001093 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001094 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001095 }
Mike Stump1eb44332009-09-09 15:08:12 +00001096 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001097 {
1098 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001099 int len = selString.size();
1100 for (int i = 0; i < len; i++)
1101 if (selString[i] == ':')
1102 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001103 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001104 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001105 // Remember this name for metadata emission
1106 MethodInternalNames[OMD] = NameStr;
1107 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001109 // Rewrite arguments
1110 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001112 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001113 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001114 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001115 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001116 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001117 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001118 ResultStr += "struct ";
1119 }
1120 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001121 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001122 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001123 }
1124 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001125 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001126 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001128 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001129 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001130 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001132 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001133 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1134 E = OMD->param_end(); PI != E; ++PI) {
1135 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001136 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001137 if (PDecl->getType()->isObjCQualifiedIdType()) {
1138 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001139 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001140 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001141 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001142 QualType QT = PDecl->getType();
1143 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1144 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00001145 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001146 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001147 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001148 ResultStr += Name;
1149 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001150 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001151 if (OMD->isVariadic())
1152 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001153 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Steve Naroff76e429d2008-07-16 14:40:40 +00001155 if (FPRetType) {
1156 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Steve Naroff76e429d2008-07-16 14:40:40 +00001158 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001159 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001160 ResultStr += "(";
1161 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1162 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001163 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001164 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001165 ResultStr += ParamStr;
1166 }
1167 if (FT->isVariadic()) {
1168 if (FT->getNumArgs()) ResultStr += ", ";
1169 ResultStr += "...";
1170 }
1171 ResultStr += ")";
1172 } else {
1173 ResultStr += "()";
1174 }
1175 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001176}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001177void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001178 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1179 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001181 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001183 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001184 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1185 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001186 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001187 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001188 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001189 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001190 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001191 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001192
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001193 const char *startBuf = SM->getCharacterData(LocStart);
1194 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001195 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001196 }
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001198 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001199 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1200 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001201 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001202 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001203 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001204 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001205 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001206 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001208 const char *startBuf = SM->getCharacterData(LocStart);
1209 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001210 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001211 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001212 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001213 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001214 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001215 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001216 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001217 }
1218
Benjamin Kramerd999b372010-02-14 14:14:16 +00001219 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001220}
1221
Steve Naroffb29b4272008-04-14 22:03:09 +00001222void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001223 std::string ResultStr;
Douglas Gregor7723fec2011-12-15 20:29:51 +00001224 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001225 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001226 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001227 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001228 ResultStr += "\n";
1229 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001230 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001231 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001232 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001233 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001234 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001235 // Mark this typedef as having been generated.
Douglas Gregor7723fec2011-12-15 20:29:51 +00001236 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001237 }
Fariborz Jahanian58457172011-12-05 18:43:13 +00001238 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001239
1240 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001241 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001242 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001243 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001244 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001245 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001246 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001247 for (ObjCInterfaceDecl::classmeth_iterator
1248 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001249 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001250 RewriteMethodDeclaration(*I);
1251
Steve Naroff2feac5e2007-10-30 03:43:13 +00001252 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001253 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1254 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001255}
1256
John McCall4b9c2d22011-11-06 09:01:30 +00001257Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1258 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001259
John McCall4b9c2d22011-11-06 09:01:30 +00001260 // We just magically know some things about the structure of this
1261 // expression.
1262 ObjCMessageExpr *OldMsg =
1263 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1264 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001265
John McCall4b9c2d22011-11-06 09:01:30 +00001266 // Because the rewriter doesn't allow us to rewrite rewritten code,
1267 // we need to suppress rewriting the sub-statements.
1268 Expr *Base, *RHS;
1269 {
1270 DisableReplaceStmtScope S(*this);
1271
1272 // Rebuild the base expression if we have one.
1273 Base = 0;
1274 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1275 Base = OldMsg->getInstanceReceiver();
1276 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1277 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1278 }
1279
1280 // Rebuild the RHS.
1281 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1282 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1283 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1284 }
1285
1286 // TODO: avoid this copy.
1287 SmallVector<SourceLocation, 1> SelLocs;
1288 OldMsg->getSelectorLocs(SelLocs);
1289
1290 ObjCMessageExpr *NewMsg;
1291 switch (OldMsg->getReceiverKind()) {
1292 case ObjCMessageExpr::Class:
1293 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1294 OldMsg->getValueKind(),
1295 OldMsg->getLeftLoc(),
1296 OldMsg->getClassReceiverTypeInfo(),
1297 OldMsg->getSelector(),
1298 SelLocs,
1299 OldMsg->getMethodDecl(),
1300 RHS,
1301 OldMsg->getRightLoc());
1302 break;
1303
1304 case ObjCMessageExpr::Instance:
1305 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1306 OldMsg->getValueKind(),
1307 OldMsg->getLeftLoc(),
1308 Base,
1309 OldMsg->getSelector(),
1310 SelLocs,
1311 OldMsg->getMethodDecl(),
1312 RHS,
1313 OldMsg->getRightLoc());
1314 break;
1315
1316 case ObjCMessageExpr::SuperClass:
1317 case ObjCMessageExpr::SuperInstance:
1318 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1319 OldMsg->getValueKind(),
1320 OldMsg->getLeftLoc(),
1321 OldMsg->getSuperLoc(),
1322 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1323 OldMsg->getSuperType(),
1324 OldMsg->getSelector(),
1325 SelLocs,
1326 OldMsg->getMethodDecl(),
1327 RHS,
1328 OldMsg->getRightLoc());
1329 break;
1330 }
1331
1332 Stmt *Replacement = SynthMessageExpr(NewMsg);
1333 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1334 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001335}
1336
John McCall4b9c2d22011-11-06 09:01:30 +00001337Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1338 SourceRange OldRange = PseudoOp->getSourceRange();
1339
1340 // We just magically know some things about the structure of this
1341 // expression.
1342 ObjCMessageExpr *OldMsg =
1343 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1344
1345 // Because the rewriter doesn't allow us to rewrite rewritten code,
1346 // we need to suppress rewriting the sub-statements.
1347 Expr *Base = 0;
1348 {
1349 DisableReplaceStmtScope S(*this);
1350
1351 // Rebuild the base expression if we have one.
1352 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1353 Base = OldMsg->getInstanceReceiver();
1354 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1355 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001356 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001357 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001358
John McCall4b9c2d22011-11-06 09:01:30 +00001359 // Intentionally empty.
1360 SmallVector<SourceLocation, 1> SelLocs;
1361 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001362
John McCall4b9c2d22011-11-06 09:01:30 +00001363 ObjCMessageExpr *NewMsg;
1364 switch (OldMsg->getReceiverKind()) {
1365 case ObjCMessageExpr::Class:
1366 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1367 OldMsg->getValueKind(),
1368 OldMsg->getLeftLoc(),
1369 OldMsg->getClassReceiverTypeInfo(),
1370 OldMsg->getSelector(),
1371 SelLocs,
1372 OldMsg->getMethodDecl(),
1373 Args,
1374 OldMsg->getRightLoc());
1375 break;
1376
1377 case ObjCMessageExpr::Instance:
1378 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1379 OldMsg->getValueKind(),
1380 OldMsg->getLeftLoc(),
1381 Base,
1382 OldMsg->getSelector(),
1383 SelLocs,
1384 OldMsg->getMethodDecl(),
1385 Args,
1386 OldMsg->getRightLoc());
1387 break;
1388
1389 case ObjCMessageExpr::SuperClass:
1390 case ObjCMessageExpr::SuperInstance:
1391 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1392 OldMsg->getValueKind(),
1393 OldMsg->getLeftLoc(),
1394 OldMsg->getSuperLoc(),
1395 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1396 OldMsg->getSuperType(),
1397 OldMsg->getSelector(),
1398 SelLocs,
1399 OldMsg->getMethodDecl(),
1400 Args,
1401 OldMsg->getRightLoc());
1402 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001403 }
John McCall4b9c2d22011-11-06 09:01:30 +00001404
1405 Stmt *Replacement = SynthMessageExpr(NewMsg);
1406 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1407 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001408}
1409
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001410/// SynthCountByEnumWithState - To print:
1411/// ((unsigned int (*)
1412/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001413/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001414/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001415/// "countByEnumeratingWithState:objects:count:"),
1416/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001417/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001418///
Steve Naroffb29b4272008-04-14 22:03:09 +00001419void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001420 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1421 "id *, unsigned int))(void *)objc_msgSend)";
1422 buf += "\n\t\t";
1423 buf += "((id)l_collection,\n\t\t";
1424 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1425 buf += "\n\t\t";
1426 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001427 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001428}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001429
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001430/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1431/// statement to exit to its outer synthesized loop.
1432///
Steve Naroffb29b4272008-04-14 22:03:09 +00001433Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001434 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1435 return S;
1436 // replace break with goto __break_label
1437 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001439 SourceLocation startLoc = S->getLocStart();
1440 buf = "goto __break_label_";
1441 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001442 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001443
1444 return 0;
1445}
1446
1447/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1448/// statement to continue with its inner synthesized loop.
1449///
Steve Naroffb29b4272008-04-14 22:03:09 +00001450Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001451 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1452 return S;
1453 // replace continue with goto __continue_label
1454 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001456 SourceLocation startLoc = S->getLocStart();
1457 buf = "goto __continue_label_";
1458 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001459 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001461 return 0;
1462}
1463
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001464/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001465/// It rewrites:
1466/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001468/// Into:
1469/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001470/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001471/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001472/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001473/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001474/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001475/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001476/// if (limit) {
1477/// unsigned long startMutations = *enumState.mutationsPtr;
1478/// do {
1479/// unsigned long counter = 0;
1480/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001481/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001482/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001483/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001484/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001485/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001486/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001487/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001488/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001489/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001490/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001491/// }
1492/// else
1493/// elem = nil;
1494/// }
1495///
Steve Naroffb29b4272008-04-14 22:03:09 +00001496Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001497 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001498 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001499 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001500 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001501 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001502 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001504 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001505 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001506 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001507 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001508 std::string buf;
1509 buf = "\n{\n\t";
1510 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1511 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001512 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001513 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001514 if (ElementType->isObjCQualifiedIdType() ||
1515 ElementType->isObjCQualifiedInterfaceType())
1516 // Simply use 'id' for all qualified types.
1517 elementTypeAsString = "id";
1518 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001519 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001520 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001521 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001522 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001523 buf += elementName;
1524 buf += ";\n\t";
1525 }
Chris Lattner06767512008-04-08 05:52:18 +00001526 else {
1527 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001528 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001529 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1530 if (VD->getType()->isObjCQualifiedIdType() ||
1531 VD->getType()->isObjCQualifiedInterfaceType())
1532 // Simply use 'id' for all qualified types.
1533 elementTypeAsString = "id";
1534 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001535 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001536 }
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001538 // struct __objcFastEnumerationState enumState = { 0 };
1539 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001540 // id __rw_items[16];
1541 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001542 // id l_collection = (id)
1543 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001544 // Find start location of 'collection' the hard way!
1545 const char *startCollectionBuf = startBuf;
1546 startCollectionBuf += 3; // skip 'for'
1547 startCollectionBuf = strchr(startCollectionBuf, '(');
1548 startCollectionBuf++; // skip '('
1549 // find 'in' and skip it.
1550 while (*startCollectionBuf != ' ' ||
1551 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1552 (*(startCollectionBuf+3) != ' ' &&
1553 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1554 startCollectionBuf++;
1555 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001556
1557 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001558 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001559 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001560 SourceLocation rightParenLoc = S->getRParenLoc();
1561 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001562 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001563 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001565 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001566 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001567 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001568 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001569 // ((unsigned int (*)
1570 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001571 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001572 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001573 // "countByEnumeratingWithState:objects:count:"),
1574 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001575 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001576 buf += "unsigned long limit =\n\t\t";
1577 SynthCountByEnumWithState(buf);
1578 buf += ";\n\t";
1579 /// if (limit) {
1580 /// unsigned long startMutations = *enumState.mutationsPtr;
1581 /// do {
1582 /// unsigned long counter = 0;
1583 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001584 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001585 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001586 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001587 buf += "if (limit) {\n\t";
1588 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1589 buf += "do {\n\t\t";
1590 buf += "unsigned long counter = 0;\n\t\t";
1591 buf += "do {\n\t\t\t";
1592 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1593 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1594 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001595 buf += " = (";
1596 buf += elementTypeAsString;
1597 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001598 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001599 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001601 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001602 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001603 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001604 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001605 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001606 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001607 /// }
1608 /// else
1609 /// elem = nil;
1610 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001611 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001612 buf = ";\n\t";
1613 buf += "__continue_label_";
1614 buf += utostr(ObjCBcLabelNo.back());
1615 buf += ": ;";
1616 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001617 buf += "} while (counter < limit);\n\t";
1618 buf += "} while (limit = ";
1619 SynthCountByEnumWithState(buf);
1620 buf += ");\n\t";
1621 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001622 buf += " = ((";
1623 buf += elementTypeAsString;
1624 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001625 buf += "__break_label_";
1626 buf += utostr(ObjCBcLabelNo.back());
1627 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001628 buf += "}\n\t";
1629 buf += "else\n\t\t";
1630 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001631 buf += " = ((";
1632 buf += elementTypeAsString;
1633 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001634 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001636 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001637 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001638 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001639 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001640 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001641 } else {
1642 /* Need to treat single statements specially. For example:
1643 *
1644 * for (A *a in b) if (stuff()) break;
1645 * for (A *a in b) xxxyy;
1646 *
1647 * The following code simply scans ahead to the semi to find the actual end.
1648 */
1649 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1650 const char *semiBuf = strchr(stmtBuf, ';');
1651 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001652 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001653 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001654 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001655 Stmts.pop_back();
1656 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001657 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001658}
1659
Mike Stump1eb44332009-09-09 15:08:12 +00001660/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001661/// This routine rewrites @synchronized(expr) stmt;
1662/// into:
1663/// objc_sync_enter(expr);
1664/// @try stmt @finally { objc_sync_exit(expr); }
1665///
Steve Naroffb29b4272008-04-14 22:03:09 +00001666Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001667 // Get the start location and compute the semi location.
1668 SourceLocation startLoc = S->getLocStart();
1669 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001671 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001672
1673 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001674 buf = "objc_sync_enter((id)";
1675 const char *lparenBuf = startBuf;
1676 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001677 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001678 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1679 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001680 // been rewritten! (which implies the SourceLocation's are invalid).
1681 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001682 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001683 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001684 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001685 buf = ");\n";
1686 // declare a new scope with two variables, _stack and _rethrow.
1687 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1688 buf += "int buf[18/*32-bit i386*/];\n";
1689 buf += "char *pointers[4];} _stack;\n";
1690 buf += "id volatile _rethrow = 0;\n";
1691 buf += "objc_exception_try_enter(&_stack);\n";
1692 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001693 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001694 startLoc = S->getSynchBody()->getLocEnd();
1695 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Steve Naroffc7089f12008-08-19 13:04:19 +00001697 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001698 SourceLocation lastCurlyLoc = startLoc;
1699 buf = "}\nelse {\n";
1700 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001701 buf += "}\n";
1702 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001703 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001704
1705 std::string syncBuf;
1706 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001707
1708 Expr *syncExpr = S->getSynchExpr();
1709 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1710 ? CK_BitCast :
1711 syncExpr->getType()->isBlockPointerType()
1712 ? CK_BlockPointerToObjCPointerCast
1713 : CK_CPointerToObjCPointerCast;
1714 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1715 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001716 std::string syncExprBufS;
1717 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001718 syncExpr->printPretty(syncExprBuf, *Context, 0,
1719 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001720 syncBuf += syncExprBuf.str();
1721 syncBuf += ");";
1722
1723 buf += syncBuf;
1724 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001725 buf += "}\n";
1726 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Benjamin Kramerd999b372010-02-14 14:14:16 +00001728 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001729
1730 bool hasReturns = false;
1731 HasReturnStmts(S->getSynchBody(), hasReturns);
1732 if (hasReturns)
1733 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1734
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001735 return 0;
1736}
1737
Steve Naroffb85e77a2009-12-05 21:43:12 +00001738void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1739{
Steve Naroff8c565152008-12-05 17:03:39 +00001740 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001741 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001742 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001743 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001744
Steve Naroffb85e77a2009-12-05 21:43:12 +00001745 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001746 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001747 TryFinallyContainsReturnDiag);
1748 }
1749 return;
1750}
1751
Steve Naroffb85e77a2009-12-05 21:43:12 +00001752void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1753{
1754 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001755 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001756 if (*CI)
1757 HasReturnStmts(*CI, hasReturns);
1758
1759 if (isa<ReturnStmt>(S))
1760 hasReturns = true;
1761 return;
1762}
1763
1764void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1765 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001766 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001767 if (*CI) {
1768 RewriteTryReturnStmts(*CI);
1769 }
1770 if (isa<ReturnStmt>(S)) {
1771 SourceLocation startLoc = S->getLocStart();
1772 const char *startBuf = SM->getCharacterData(startLoc);
1773
1774 const char *semiBuf = strchr(startBuf, ';');
1775 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001776 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001777
1778 std::string buf;
1779 buf = "{ objc_exception_try_exit(&_stack); return";
1780
Benjamin Kramerd999b372010-02-14 14:14:16 +00001781 ReplaceText(startLoc, 6, buf);
1782 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001783 }
1784 return;
1785}
1786
1787void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1788 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001789 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001790 if (*CI) {
1791 RewriteSyncReturnStmts(*CI, syncExitBuf);
1792 }
1793 if (isa<ReturnStmt>(S)) {
1794 SourceLocation startLoc = S->getLocStart();
1795 const char *startBuf = SM->getCharacterData(startLoc);
1796
1797 const char *semiBuf = strchr(startBuf, ';');
1798 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001799 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001800
1801 std::string buf;
1802 buf = "{ objc_exception_try_exit(&_stack);";
1803 buf += syncExitBuf;
1804 buf += " return";
1805
Benjamin Kramerd999b372010-02-14 14:14:16 +00001806 ReplaceText(startLoc, 6, buf);
1807 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001808 }
1809 return;
1810}
1811
Steve Naroffb29b4272008-04-14 22:03:09 +00001812Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001813 // Get the start location and compute the semi location.
1814 SourceLocation startLoc = S->getLocStart();
1815 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001816
Steve Naroff75730982007-11-07 04:08:17 +00001817 assert((*startBuf == '@') && "bogus @try location");
1818
1819 std::string buf;
1820 // declare a new scope with two variables, _stack and _rethrow.
1821 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1822 buf += "int buf[18/*32-bit i386*/];\n";
1823 buf += "char *pointers[4];} _stack;\n";
1824 buf += "id volatile _rethrow = 0;\n";
1825 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001826 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001827
Benjamin Kramerd999b372010-02-14 14:14:16 +00001828 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Steve Naroff75730982007-11-07 04:08:17 +00001830 startLoc = S->getTryBody()->getLocEnd();
1831 startBuf = SM->getCharacterData(startLoc);
1832
1833 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Steve Naroff75730982007-11-07 04:08:17 +00001835 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001836 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001837 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001838 buf = " /* @catch begin */ else {\n";
1839 buf += " id _caught = objc_exception_extract(&_stack);\n";
1840 buf += " objc_exception_try_enter (&_stack);\n";
1841 buf += " if (_setjmp(_stack.buf))\n";
1842 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1843 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Benjamin Kramerd999b372010-02-14 14:14:16 +00001845 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001846 } else { /* no catch list */
1847 buf = "}\nelse {\n";
1848 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1849 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001850 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001851 }
Steve Naroff75730982007-11-07 04:08:17 +00001852 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001853 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1854 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001855 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001856
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001857 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001858 buf = "if ("; // we are generating code for the first catch clause
1859 else
1860 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001861 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001862 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001863
Steve Naroff75730982007-11-07 04:08:17 +00001864 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Steve Naroff75730982007-11-07 04:08:17 +00001866 const char *lParenLoc = strchr(startBuf, '(');
1867
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001868 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001869 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001870 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001871 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1872 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001873 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001874 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001875 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Steve Naroffe12e6922008-02-01 20:02:07 +00001877 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001878 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001879 } else if (catchDecl) {
1880 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001881 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001882 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001883 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001884 } else if (const ObjCObjectPointerType *Ptr =
1885 t->getAs<ObjCObjectPointerType>()) {
1886 // Should be a pointer to a class.
1887 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1888 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001889 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001890 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001891 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001892 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001893 }
1894 }
1895 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001896 lastCatchBody = Catch->getCatchBody();
1897 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001898 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1899 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1900 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1901 assert((*rParenBuf == ')') && "bogus @catch paren location");
1902 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Mike Stump1eb44332009-09-09 15:08:12 +00001904 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001905 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001906 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001907 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001908 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001909 }
Steve Naroff75730982007-11-07 04:08:17 +00001910 }
1911 // Complete the catch list...
1912 if (lastCatchBody) {
1913 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001914 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1915 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Steve Naroff378f47a2008-09-11 15:29:03 +00001917 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001918 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00001919 buf = "} /* last catch end */\n";
1920 buf += "else {\n";
1921 buf += " _rethrow = _caught;\n";
1922 buf += " objc_exception_try_exit(&_stack);\n";
1923 buf += "} } /* @catch end */\n";
1924 if (!S->getFinallyStmt())
1925 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001926 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Steve Naroff75730982007-11-07 04:08:17 +00001928 // Set lastCurlyLoc
1929 lastCurlyLoc = lastCatchBody->getLocEnd();
1930 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001931 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001932 startLoc = finalStmt->getLocStart();
1933 startBuf = SM->getCharacterData(startLoc);
1934 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Benjamin Kramerd999b372010-02-14 14:14:16 +00001936 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Steve Naroff75730982007-11-07 04:08:17 +00001938 Stmt *body = finalStmt->getFinallyBody();
1939 SourceLocation startLoc = body->getLocStart();
1940 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001941 assert(*SM->getCharacterData(startLoc) == '{' &&
1942 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001943 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001944 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001946 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001947 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001948 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001949 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Steve Naroff75730982007-11-07 04:08:17 +00001951 // Set lastCurlyLoc
1952 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Steve Naroff8c565152008-12-05 17:03:39 +00001954 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001955 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001956 } else { /* no finally clause - make sure we synthesize an implicit one */
1957 buf = "{ /* implicit finally clause */\n";
1958 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1959 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1960 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001961 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001962
1963 // Now check for any return/continue/go statements within the @try.
1964 // The implicit finally clause won't called if the @try contains any
1965 // jump statements.
1966 bool hasReturns = false;
1967 HasReturnStmts(S->getTryBody(), hasReturns);
1968 if (hasReturns)
1969 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001970 }
1971 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001972 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001973 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001974 return 0;
1975}
1976
Mike Stump1eb44332009-09-09 15:08:12 +00001977// This can't be done with ReplaceStmt(S, ThrowExpr), since
1978// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001979// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001980Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001981 // Get the start location and compute the semi location.
1982 SourceLocation startLoc = S->getLocStart();
1983 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001984
Steve Naroff2bd03922007-11-07 15:32:26 +00001985 assert((*startBuf == '@') && "bogus @throw location");
1986
1987 std::string buf;
1988 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001989 if (S->getThrowExpr())
1990 buf = "objc_exception_throw(";
1991 else // add an implicit argument
1992 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001994 // handle "@ throw" correctly.
1995 const char *wBuf = strchr(startBuf, 'w');
1996 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00001997 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001998
Steve Naroff2bd03922007-11-07 15:32:26 +00001999 const char *semiBuf = strchr(startBuf, ';');
2000 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002001 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002002 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002003 return 0;
2004}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002005
Steve Naroffb29b4272008-04-14 22:03:09 +00002006Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002007 // Create a new string expression.
2008 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002009 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002010 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002011 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002012 StringLiteral::Ascii, false,
2013 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002014 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Chris Lattner07506182007-11-30 22:53:43 +00002016 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002017 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002018 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002019}
2020
Steve Naroffb29b4272008-04-14 22:03:09 +00002021Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002022 if (!SelGetUidFunctionDecl)
2023 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002024 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2025 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002026 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002027 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002028 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002029 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002030 StringLiteral::Ascii, false,
2031 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002032 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2033 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002034 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002035 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002036 return SelExp;
2037}
2038
Steve Naroffb29b4272008-04-14 22:03:09 +00002039CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002040 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2041 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002042 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002043 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Steve Naroffebf2b562007-10-23 23:50:29 +00002045 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002046 DeclRefExpr *DRE =
2047 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Steve Naroffebf2b562007-10-23 23:50:29 +00002049 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002050 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002051 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002052 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002053 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002054
John McCall183700f2009-09-21 23:43:11 +00002055 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002057 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002058 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002059 FT->getCallResultType(*Context),
2060 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002061 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002062}
2063
Steve Naroffd5255f52007-11-01 13:24:47 +00002064static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2065 const char *&startRef, const char *&endRef) {
2066 while (startBuf < endBuf) {
2067 if (*startBuf == '<')
2068 startRef = startBuf; // mark the start.
2069 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002070 if (startRef && *startRef == '<') {
2071 endRef = startBuf; // mark the end.
2072 return true;
2073 }
2074 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002075 }
2076 startBuf++;
2077 }
2078 return false;
2079}
2080
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002081static void scanToNextArgument(const char *&argRef) {
2082 int angle = 0;
2083 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2084 if (*argRef == '<')
2085 angle++;
2086 else if (*argRef == '>')
2087 angle--;
2088 argRef++;
2089 }
2090 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2091}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002092
Steve Naroffb29b4272008-04-14 22:03:09 +00002093bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002094 if (T->isObjCQualifiedIdType())
2095 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002096 if (const PointerType *PT = T->getAs<PointerType>()) {
2097 if (PT->getPointeeType()->isObjCQualifiedIdType())
2098 return true;
2099 }
2100 if (T->isObjCObjectPointerType()) {
2101 T = T->getPointeeType();
2102 return T->isObjCQualifiedInterfaceType();
2103 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002104 if (T->isArrayType()) {
2105 QualType ElemTy = Context->getBaseElementType(T);
2106 return needToScanForQualifiers(ElemTy);
2107 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002108 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002109}
2110
Steve Naroff4f95b752008-07-29 18:15:38 +00002111void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2112 QualType Type = E->getType();
2113 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002114 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002115
Steve Naroffcda658e2008-11-19 21:15:47 +00002116 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2117 Loc = ECE->getLParenLoc();
2118 EndLoc = ECE->getRParenLoc();
2119 } else {
2120 Loc = E->getLocStart();
2121 EndLoc = E->getLocEnd();
2122 }
2123 // This will defend against trying to rewrite synthesized expressions.
2124 if (Loc.isInvalid() || EndLoc.isInvalid())
2125 return;
2126
Steve Naroff4f95b752008-07-29 18:15:38 +00002127 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002128 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002129 const char *startRef = 0, *endRef = 0;
2130 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2131 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002132 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2133 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002134 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002135 InsertText(LessLoc, "/*");
2136 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002137 }
2138 }
2139}
2140
Steve Naroffb29b4272008-04-14 22:03:09 +00002141void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002142 SourceLocation Loc;
2143 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002144 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002145 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2146 Loc = VD->getLocation();
2147 Type = VD->getType();
2148 }
2149 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2150 Loc = FD->getLocation();
2151 // Check for ObjC 'id' and class types that have been adorned with protocol
2152 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002153 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002154 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002155 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002156 if (!proto)
2157 return;
2158 Type = proto->getResultType();
2159 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002160 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2161 Loc = FD->getLocation();
2162 Type = FD->getType();
2163 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002164 else
2165 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002167 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002168 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Steve Naroffd5255f52007-11-01 13:24:47 +00002170 const char *endBuf = SM->getCharacterData(Loc);
2171 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002172 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002173 startBuf--; // scan backward (from the decl location) for return type.
2174 const char *startRef = 0, *endRef = 0;
2175 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2176 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002177 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2178 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002179 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002180 InsertText(LessLoc, "/*");
2181 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002182 }
2183 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002184 if (!proto)
2185 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002186 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002187 const char *startBuf = SM->getCharacterData(Loc);
2188 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002189 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2190 if (needToScanForQualifiers(proto->getArgType(i))) {
2191 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Steve Naroffd5255f52007-11-01 13:24:47 +00002193 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002194 // scan forward (from the decl location) for argument types.
2195 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002196 const char *startRef = 0, *endRef = 0;
2197 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2198 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002199 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002200 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002201 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002202 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002203 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002204 InsertText(LessLoc, "/*");
2205 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002206 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002207 startBuf = ++endBuf;
2208 }
2209 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002210 // If the function name is derived from a macro expansion, then the
2211 // argument buffer will not follow the name. Need to speak with Chris.
2212 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002213 startBuf++; // scan forward (from the decl location) for argument types.
2214 startBuf++;
2215 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002216 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002217}
2218
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002219void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2220 QualType QT = ND->getType();
2221 const Type* TypePtr = QT->getAs<Type>();
2222 if (!isa<TypeOfExprType>(TypePtr))
2223 return;
2224 while (isa<TypeOfExprType>(TypePtr)) {
2225 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2226 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2227 TypePtr = QT->getAs<Type>();
2228 }
2229 // FIXME. This will not work for multiple declarators; as in:
2230 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002231 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002232 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2233 const char *startBuf = SM->getCharacterData(DeclLoc);
2234 if (ND->getInit()) {
2235 std::string Name(ND->getNameAsString());
2236 TypeAsString += " " + Name + " = ";
2237 Expr *E = ND->getInit();
2238 SourceLocation startLoc;
2239 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2240 startLoc = ECE->getLParenLoc();
2241 else
2242 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002243 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002244 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002245 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002246 }
2247 else {
2248 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002249 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002250 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002251 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002252 }
2253}
2254
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002255// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002256void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002257 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002258 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002259 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002260 QualType getFuncType =
2261 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002262 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002263 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002264 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002265 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002266 SC_Extern,
2267 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002268}
2269
Steve Naroffb29b4272008-04-14 22:03:09 +00002270void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002271 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002272 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002273 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002274 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002275 return;
2276 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002277 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002278}
2279
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002280void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002281 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002282 const char *argPtr = TypeString.c_str();
2283 if (!strchr(argPtr, '^')) {
2284 Str += TypeString;
2285 return;
2286 }
2287 while (*argPtr) {
2288 Str += (*argPtr == '^' ? '*' : *argPtr);
2289 argPtr++;
2290 }
2291}
2292
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002293// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002294void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2295 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002296 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002297 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002298 const char *argPtr = TypeString.c_str();
2299 int paren = 0;
2300 while (*argPtr) {
2301 switch (*argPtr) {
2302 case '(':
2303 Str += *argPtr;
2304 paren++;
2305 break;
2306 case ')':
2307 Str += *argPtr;
2308 paren--;
2309 break;
2310 case '^':
2311 Str += '*';
2312 if (paren == 1)
2313 Str += VD->getNameAsString();
2314 break;
2315 default:
2316 Str += *argPtr;
2317 break;
2318 }
2319 argPtr++;
2320 }
2321}
2322
2323
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002324void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2325 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2326 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2327 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2328 if (!proto)
2329 return;
2330 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002331 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002332 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002333 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002334 FdStr += "(";
2335 unsigned numArgs = proto->getNumArgs();
2336 for (unsigned i = 0; i < numArgs; i++) {
2337 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002338 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002339 if (i+1 < numArgs)
2340 FdStr += ", ";
2341 }
2342 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002343 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002344 CurFunctionDeclToDeclareForBlock = 0;
2345}
2346
Steve Naroffc0a123c2008-03-11 17:37:02 +00002347// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002348void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002349 if (SuperContructorFunctionDecl)
2350 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002351 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002352 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002353 QualType argT = Context->getObjCIdType();
2354 assert(!argT.isNull() && "Can't find 'id' type");
2355 ArgTys.push_back(argT);
2356 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002357 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2358 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002359 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002360 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002361 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002362 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002363 SC_Extern,
2364 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002365}
2366
Steve Naroff09b266e2007-10-30 23:14:51 +00002367// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002368void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002369 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002370 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002371 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002372 assert(!argT.isNull() && "Can't find 'id' type");
2373 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002374 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002375 assert(!argT.isNull() && "Can't find 'SEL' type");
2376 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002377 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2378 &ArgTys[0], ArgTys.size(),
2379 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002380 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002381 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002382 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002383 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002384 SC_Extern,
2385 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002386}
2387
Steve Naroff874e2322007-11-15 10:28:18 +00002388// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002389void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002390 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002391 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002392 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002393 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002394 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002395 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2396 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2397 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002398 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002399 assert(!argT.isNull() && "Can't find 'SEL' type");
2400 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002401 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2402 &ArgTys[0], ArgTys.size(),
2403 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002404 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002405 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002406 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002407 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002408 SC_Extern,
2409 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002410}
2411
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002412// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002413void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002414 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002415 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002416 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002417 assert(!argT.isNull() && "Can't find 'id' type");
2418 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002419 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002420 assert(!argT.isNull() && "Can't find 'SEL' type");
2421 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002422 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002423 &ArgTys[0], ArgTys.size(),
2424 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002425 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002426 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002427 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002428 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002429 SC_Extern,
2430 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002431}
2432
Mike Stump1eb44332009-09-09 15:08:12 +00002433// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002434// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002435void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002436 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002437 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002438 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002439 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002440 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002441 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002442 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2443 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2444 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002445 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002446 assert(!argT.isNull() && "Can't find 'SEL' type");
2447 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002448 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002449 &ArgTys[0], ArgTys.size(),
2450 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002451 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002452 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002453 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002454 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002455 SC_Extern,
2456 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002457}
2458
Steve Naroff1284db82008-05-08 22:02:18 +00002459// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002460void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002461 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002462 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002463 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002464 assert(!argT.isNull() && "Can't find 'id' type");
2465 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002466 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002467 assert(!argT.isNull() && "Can't find 'SEL' type");
2468 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002469 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2470 &ArgTys[0], ArgTys.size(),
2471 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002472 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002473 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002474 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002475 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002476 SC_Extern,
2477 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002478}
2479
Steve Naroff09b266e2007-10-30 23:14:51 +00002480// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002481void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002482 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002483 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002484 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002485 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2486 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002487 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002488 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002489 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002490 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002491 SC_Extern,
2492 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002493}
2494
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002495// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2496void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2497 IdentifierInfo *getSuperClassIdent =
2498 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002499 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002500 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002501 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2502 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002503 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002504 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002505 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002506 getSuperClassIdent,
2507 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002508 SC_Extern,
2509 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002510 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002511}
2512
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002513// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002514void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002515 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002516 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002517 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002518 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2519 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002520 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002521 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002522 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002523 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002524 SC_Extern,
2525 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002526}
2527
Steve Naroffb29b4272008-04-14 22:03:09 +00002528Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002529 QualType strType = getConstantStringStructType();
2530
2531 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002532
2533 std::string tmpName = InFileName;
2534 unsigned i;
2535 for (i=0; i < tmpName.length(); i++) {
2536 char c = tmpName.at(i);
2537 // replace any non alphanumeric characters with '_'.
2538 if (!isalpha(c) && (c < '0' || c > '9'))
2539 tmpName[i] = '_';
2540 }
2541 S += tmpName;
2542 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002543 S += utostr(NumObjCStringLiterals++);
2544
Steve Naroffba92b2e2008-03-27 22:29:16 +00002545 Preamble += "static __NSConstantStringImpl " + S;
2546 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2547 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002548 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002549 std::string prettyBufS;
2550 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002551 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2552 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002553 Preamble += prettyBuf.str();
2554 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002555 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002556
2557 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002558 SourceLocation(), &Context->Idents.get(S),
2559 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002560 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2561 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002562 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002563 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002564 VK_RValue, OK_Ordinary,
2565 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002566 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002567 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002568 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002569 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002570 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002571 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002572}
2573
Steve Naroff874e2322007-11-15 10:28:18 +00002574// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002575QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002576 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002577 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002578 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002579 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002580 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002581
Steve Naroff874e2322007-11-15 10:28:18 +00002582 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002583 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002584 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002585 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002586
Steve Naroff874e2322007-11-15 10:28:18 +00002587 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002588 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002589 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002590 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002591 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002592 FieldTypes[i], 0,
2593 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002594 /*Mutable=*/false,
2595 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002596 }
Mike Stump1eb44332009-09-09 15:08:12 +00002597
Douglas Gregor838db382010-02-11 01:19:42 +00002598 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002599 }
2600 return Context->getTagDeclType(SuperStructDecl);
2601}
2602
Steve Naroffb29b4272008-04-14 22:03:09 +00002603QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002604 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002605 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002606 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002607 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002608 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002609
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002610 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002611 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002612 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002613 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002614 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002615 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002616 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002617 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002618
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002619 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002620 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002621 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2622 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002623 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002624 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002625 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002626 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002627 /*Mutable=*/true,
2628 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002629 }
2630
Douglas Gregor838db382010-02-11 01:19:42 +00002631 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002632 }
2633 return Context->getTagDeclType(ConstantStringDecl);
2634}
2635
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002636Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2637 SourceLocation StartLoc,
2638 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002639 if (!SelGetUidFunctionDecl)
2640 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002641 if (!MsgSendFunctionDecl)
2642 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002643 if (!MsgSendSuperFunctionDecl)
2644 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002645 if (!MsgSendStretFunctionDecl)
2646 SynthMsgSendStretFunctionDecl();
2647 if (!MsgSendSuperStretFunctionDecl)
2648 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002649 if (!MsgSendFpretFunctionDecl)
2650 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002651 if (!GetClassFunctionDecl)
2652 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002653 if (!GetSuperClassFunctionDecl)
2654 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002655 if (!GetMetaClassFunctionDecl)
2656 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002657
Steve Naroff874e2322007-11-15 10:28:18 +00002658 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002659 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2660 // May need to use objc_msgSend_stret() as well.
2661 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002662 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2663 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002664 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002665 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002666 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002667 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002668 }
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Steve Naroff934f2762007-10-24 22:48:43 +00002670 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002671 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002672 switch (Exp->getReceiverKind()) {
2673 case ObjCMessageExpr::SuperClass: {
2674 MsgSendFlavor = MsgSendSuperFunctionDecl;
2675 if (MsgSendStretFlavor)
2676 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2677 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002678
Douglas Gregor04badcf2010-04-21 00:45:42 +00002679 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Chris Lattner5f9e2722011-07-23 10:55:15 +00002681 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002682
Douglas Gregor04badcf2010-04-21 00:45:42 +00002683 // set the receiver to self, the first argument to all methods.
2684 InitExprs.push_back(
2685 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002686 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002687 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002688 Context->getObjCIdType(),
2689 VK_RValue,
2690 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002691 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002692
Douglas Gregor04badcf2010-04-21 00:45:42 +00002693 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002694 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002695 QualType argType = Context->getPointerType(Context->CharTy);
2696 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002697 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002698 StringLiteral::Ascii, false,
2699 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002700 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2701 &ClsExprs[0],
2702 ClsExprs.size(),
2703 StartLoc,
2704 EndLoc);
2705 // (Class)objc_getClass("CurrentClass")
2706 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2707 Context->getObjCClassType(),
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002708 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002709 ClsExprs.clear();
2710 ClsExprs.push_back(ArgExpr);
2711 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2712 &ClsExprs[0], ClsExprs.size(),
2713 StartLoc, EndLoc);
2714
2715 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2716 // To turn off a warning, type-cast to 'id'
2717 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2718 NoTypeInfoCStyleCastExpr(Context,
2719 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002720 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002721 // struct objc_super
2722 QualType superType = getSuperStructType();
2723 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002724
Francois Pichet62ec1f22011-09-17 17:15:52 +00002725 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002726 SynthSuperContructorFunctionDecl();
2727 // Simulate a contructor call...
2728 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002729 superType, VK_LValue,
2730 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002731 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2732 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002733 superType, VK_LValue,
2734 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002735 // The code for super is a little tricky to prevent collision with
2736 // the structure definition in the header. The rewriter has it's own
2737 // internal definition (__rw_objc_super) that is uses. This is why
2738 // we need the cast below. For example:
2739 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2740 //
John McCall2de56d12010-08-25 11:45:40 +00002741 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002742 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002743 VK_RValue, OK_Ordinary,
2744 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002745 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2746 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002747 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002748 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002749 // (struct objc_super) { <exprs from above> }
2750 InitListExpr *ILE =
2751 new (Context) InitListExpr(*Context, SourceLocation(),
2752 &InitExprs[0], InitExprs.size(),
2753 SourceLocation());
2754 TypeSourceInfo *superTInfo
2755 = Context->getTrivialTypeSourceInfo(superType);
2756 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002757 superType, VK_LValue,
2758 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002759 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002760 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002761 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002762 VK_RValue, OK_Ordinary,
2763 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002764 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002765 MsgExprs.push_back(SuperRep);
2766 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002767 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002768
2769 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002770 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002771 QualType argType = Context->getPointerType(Context->CharTy);
2772 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002773 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002774 IdentifierInfo *clsName = Class->getIdentifier();
2775 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002776 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002777 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002778 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002779 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2780 &ClsExprs[0],
2781 ClsExprs.size(),
2782 StartLoc, EndLoc);
2783 MsgExprs.push_back(Cls);
2784 break;
2785 }
2786
2787 case ObjCMessageExpr::SuperInstance:{
2788 MsgSendFlavor = MsgSendSuperFunctionDecl;
2789 if (MsgSendStretFlavor)
2790 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2791 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2792 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002793 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002794
2795 InitExprs.push_back(
2796 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002797 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002798 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002799 Context->getObjCIdType(),
2800 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002801 ); // set the 'receiver'.
2802
2803 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002804 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002805 QualType argType = Context->getPointerType(Context->CharTy);
2806 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002807 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002808 StringLiteral::Ascii, false, argType,
2809 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002810 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2811 &ClsExprs[0],
2812 ClsExprs.size(),
2813 StartLoc, EndLoc);
2814 // (Class)objc_getClass("CurrentClass")
2815 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2816 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002817 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002818 ClsExprs.clear();
2819 ClsExprs.push_back(ArgExpr);
2820 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2821 &ClsExprs[0], ClsExprs.size(),
2822 StartLoc, EndLoc);
2823
2824 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2825 // To turn off a warning, type-cast to 'id'
2826 InitExprs.push_back(
2827 // set 'super class', using class_getSuperclass().
2828 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002829 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002830 // struct objc_super
2831 QualType superType = getSuperStructType();
2832 Expr *SuperRep;
2833
Francois Pichet62ec1f22011-09-17 17:15:52 +00002834 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002835 SynthSuperContructorFunctionDecl();
2836 // Simulate a contructor call...
2837 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002838 superType, VK_LValue,
2839 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002840 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2841 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002842 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002843 // The code for super is a little tricky to prevent collision with
2844 // the structure definition in the header. The rewriter has it's own
2845 // internal definition (__rw_objc_super) that is uses. This is why
2846 // we need the cast below. For example:
2847 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2848 //
John McCall2de56d12010-08-25 11:45:40 +00002849 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002850 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002851 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002852 SourceLocation());
2853 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2854 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002855 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002856 } else {
2857 // (struct objc_super) { <exprs from above> }
2858 InitListExpr *ILE =
2859 new (Context) InitListExpr(*Context, SourceLocation(),
2860 &InitExprs[0], InitExprs.size(),
2861 SourceLocation());
2862 TypeSourceInfo *superTInfo
2863 = Context->getTrivialTypeSourceInfo(superType);
2864 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002865 superType, VK_RValue, ILE,
2866 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002867 }
2868 MsgExprs.push_back(SuperRep);
2869 break;
2870 }
2871
2872 case ObjCMessageExpr::Instance: {
2873 // Remove all type-casts because it may contain objc-style types; e.g.
2874 // Foo<Proto> *.
2875 Expr *recExpr = Exp->getInstanceReceiver();
2876 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2877 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002878 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2879 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2880 ? CK_BlockPointerToObjCPointerCast
2881 : CK_CPointerToObjCPointerCast;
2882
Douglas Gregor04badcf2010-04-21 00:45:42 +00002883 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002884 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002885 MsgExprs.push_back(recExpr);
2886 break;
2887 }
2888 }
2889
Steve Naroffbeaf2992007-11-03 11:27:19 +00002890 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002891 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00002892 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002893 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002894 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002895 StringLiteral::Ascii, false,
2896 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002897 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002898 &SelExprs[0], SelExprs.size(),
2899 StartLoc,
2900 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002901 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002902
Steve Naroff934f2762007-10-24 22:48:43 +00002903 // Now push any user supplied arguments.
2904 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002905 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002906 // Make all implicit casts explicit...ICE comes in handy:-)
2907 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2908 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00002909 QualType type = ICE->getType();
2910 if (needToScanForQualifiers(type))
2911 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002912 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002913 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00002914 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00002915 CastKind CK;
2916 if (SubExpr->getType()->isIntegralType(*Context) &&
2917 type->isBooleanType()) {
2918 CK = CK_IntegralToBoolean;
2919 } else if (type->isObjCObjectPointerType()) {
2920 if (SubExpr->getType()->isBlockPointerType()) {
2921 CK = CK_BlockPointerToObjCPointerCast;
2922 } else if (SubExpr->getType()->isPointerType()) {
2923 CK = CK_CPointerToObjCPointerCast;
2924 } else {
2925 CK = CK_BitCast;
2926 }
2927 } else {
2928 CK = CK_BitCast;
2929 }
2930
2931 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002932 }
2933 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002934 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002935 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002936 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002937 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00002938 CastKind CK;
2939 if (userExpr->getType()->isIntegralType(*Context)) {
2940 CK = CK_IntegralToPointer;
2941 } else if (userExpr->getType()->isBlockPointerType()) {
2942 CK = CK_BlockPointerToObjCPointerCast;
2943 } else if (userExpr->getType()->isPointerType()) {
2944 CK = CK_CPointerToObjCPointerCast;
2945 } else {
2946 CK = CK_BitCast;
2947 }
John McCall9d125032010-01-15 18:39:57 +00002948 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002949 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002950 }
Mike Stump1eb44332009-09-09 15:08:12 +00002951 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002952 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002953 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2954 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002955 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002956 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002957 }
Steve Naroffab972d32007-11-04 22:37:50 +00002958 // Generate the funky cast.
2959 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002960 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00002961 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002962
Steve Naroffab972d32007-11-04 22:37:50 +00002963 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002964 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2965 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2966 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002967 ArgTypes.push_back(Context->getObjCIdType());
2968 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002969 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002970 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002971 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2972 E = OMD->param_end(); PI != E; ++PI) {
2973 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002974 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002975 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002976 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002977 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00002978 ArgTypes.push_back(t);
2979 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00002980 returnType = Exp->getType();
2981 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002982 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00002983 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002984 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002985 }
2986 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002987 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002988
Steve Naroffab972d32007-11-04 22:37:50 +00002989 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002990 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00002991 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002992
Mike Stump1eb44332009-09-09 15:08:12 +00002993 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002994 // If we don't do this cast, we get the following bizarre warning/note:
2995 // xx.m:13: warning: function called through a non-compatible type
2996 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002997 cast = NoTypeInfoCStyleCastExpr(Context,
2998 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00002999 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003000
Steve Naroffab972d32007-11-04 22:37:50 +00003001 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003002 QualType castType =
3003 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3004 // If we don't have a method decl, force a variadic cast.
3005 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003006 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003007 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003008 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003009
3010 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003011 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003012
John McCall183700f2009-09-21 23:43:11 +00003013 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003014 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003015 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003016 FT->getResultType(), VK_RValue,
3017 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003018 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003019 if (MsgSendStretFlavor) {
3020 // We have the method which returns a struct/union. Must also generate
3021 // call to objc_msgSend_stret and hang both varieties on a conditional
3022 // expression which dictate which one to envoke depending on size of
3023 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003024
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003025 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003026 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003027 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003028 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003029 cast = NoTypeInfoCStyleCastExpr(Context,
3030 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003031 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003032 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003033 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3034 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003035 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003036 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003037 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003038
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003039 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003040 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003041
John McCall183700f2009-09-21 23:43:11 +00003042 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003043 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003044 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003045 FT->getResultType(), VK_RValue,
3046 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003047
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003048 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003049 UnaryExprOrTypeTraitExpr *sizeofExpr =
3050 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3051 Context->getTrivialTypeSourceInfo(returnType),
3052 Context->getSizeType(), SourceLocation(),
3053 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003054 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3055 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3056 // For X86 it is more complicated and some kind of target specific routine
3057 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003058 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003059 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003060 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3061 llvm::APInt(IntSize, 8),
3062 Context->IntTy,
3063 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003064 BinaryOperator *lessThanExpr =
3065 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3066 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003067 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003068 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003069 new (Context) ConditionalOperator(lessThanExpr,
3070 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003071 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003072 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003073 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3074 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003075 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003076 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003077 return ReplacingStmt;
3078}
3079
Steve Naroffb29b4272008-04-14 22:03:09 +00003080Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003081 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3082 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003083
Steve Naroff934f2762007-10-24 22:48:43 +00003084 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003085 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003086
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003087 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003088 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003089}
3090
Steve Naroff621edce2009-04-29 16:37:50 +00003091// typedef struct objc_object Protocol;
3092QualType RewriteObjC::getProtocolType() {
3093 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003094 TypeSourceInfo *TInfo
3095 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003096 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003097 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003098 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003099 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003100 }
3101 return Context->getTypeDeclType(ProtocolTypeDecl);
3102}
3103
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003104/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003105/// a synthesized/forward data reference (to the protocol's metadata).
3106/// The forward references (and metadata) are generated in
3107/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003108Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003109 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3110 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003111 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003112 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003113 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003114 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3115 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003116 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003117 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003118 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003119 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003120 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003121 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003122 ReplaceStmt(Exp, castExpr);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00003123 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003124 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003125 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003126
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003127}
3128
Mike Stump1eb44332009-09-09 15:08:12 +00003129bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003130 const char *endBuf) {
3131 while (startBuf < endBuf) {
3132 if (*startBuf == '#') {
3133 // Skip whitespace.
3134 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3135 ;
3136 if (!strncmp(startBuf, "if", strlen("if")) ||
3137 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3138 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3139 !strncmp(startBuf, "define", strlen("define")) ||
3140 !strncmp(startBuf, "undef", strlen("undef")) ||
3141 !strncmp(startBuf, "else", strlen("else")) ||
3142 !strncmp(startBuf, "elif", strlen("elif")) ||
3143 !strncmp(startBuf, "endif", strlen("endif")) ||
3144 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3145 !strncmp(startBuf, "include", strlen("include")) ||
3146 !strncmp(startBuf, "import", strlen("import")) ||
3147 !strncmp(startBuf, "include_next", strlen("include_next")))
3148 return true;
3149 }
3150 startBuf++;
3151 }
3152 return false;
3153}
3154
Fariborz Jahanian58457172011-12-05 18:43:13 +00003155/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003156/// an objective-c class with ivars.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003157void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003158 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003159 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003160 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003161 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003162 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003163 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003164 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003165 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003166 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003167 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor05c272f2011-12-15 22:34:59 +00003168 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00003169
Steve Narofffea763e82007-11-14 19:25:57 +00003170 const char *startBuf = SM->getCharacterData(LocStart);
3171 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003172
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003173 // If no ivars and no root or if its root, directly or indirectly,
3174 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregor7723fec2011-12-15 20:29:51 +00003175 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003176 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003177 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003178 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003179 return;
3180 }
Mike Stump1eb44332009-09-09 15:08:12 +00003181
3182 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003183 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003184 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003185 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003186 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003187 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003188
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003189 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003190 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003191 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003192 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003193 // If the buffer contains preprocessor directives, we do more fine-grained
3194 // rewrites. This is intended to fix code that looks like (which occurs in
3195 // NSURL.h, for example):
3196 //
3197 // #ifdef XYZ
3198 // @interface Foo : NSObject
3199 // #else
3200 // @interface FooBar : NSObject
3201 // #endif
3202 // {
3203 // int i;
3204 // }
3205 // @end
3206 //
3207 // This clause is segregated to avoid breaking the common case.
3208 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003209 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003210 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003211 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003212 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003213
Chris Lattnercafeb352009-02-20 18:18:36 +00003214 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003215 // advance to the end of the referenced protocols.
3216 while (endHeader < cursor && *endHeader != '>') endHeader++;
3217 endHeader++;
3218 }
3219 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003220 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003221 } else {
3222 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003223 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003224 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003225 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003226 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003227 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003228 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003229 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003230 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003231
Steve Narofffea763e82007-11-14 19:25:57 +00003232 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003233 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003234 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003235 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003236 }
3237 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003238
Steve Narofffea763e82007-11-14 19:25:57 +00003239 // Now comment out any visibility specifiers.
3240 while (cursor < endBuf) {
3241 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003242 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003243 // Skip whitespace.
3244 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3245 /*scan*/;
3246
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003247 // FIXME: presence of @public, etc. inside comment results in
3248 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003249 if (!strncmp(cursor, "public", strlen("public")) ||
3250 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003251 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003252 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003253 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003254 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003255 // FIXME: If there are cases where '<' is used in ivar declaration part
3256 // of user code, then scan the ivar list and use needToScanForQualifiers
3257 // for type checking.
3258 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003259 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003260 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003261 cursor = strchr(cursor, '>');
3262 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003263 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003264 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003265 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003266 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003267 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003268 }
Steve Narofffea763e82007-11-14 19:25:57 +00003269 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003270 }
Steve Narofffea763e82007-11-14 19:25:57 +00003271 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003272 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003273 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003274 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003275 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003276 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003277 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003278 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003279 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003280 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003281 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003282 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003283 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003284 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003285}
3286
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003287//===----------------------------------------------------------------------===//
3288// Meta Data Emission
3289//===----------------------------------------------------------------------===//
3290
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003291
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003292/// RewriteImplementations - This routine rewrites all method implementations
3293/// and emits meta-data.
3294
Steve Narofface66252008-11-13 20:07:04 +00003295void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003296 int ClsDefCount = ClassImplementation.size();
3297 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003298
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003299 // Rewrite implemented methods
3300 for (int i = 0; i < ClsDefCount; i++)
3301 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003302
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003303 for (int i = 0; i < CatDefCount; i++)
3304 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003305}
Mike Stump1eb44332009-09-09 15:08:12 +00003306
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003307void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3308 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003309 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003310 assert(BlockByRefDeclNo.count(VD) &&
3311 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003312 if (def)
3313 ResultStr += "struct ";
3314 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003315 "_" + utostr(BlockByRefDeclNo[VD]) ;
3316}
3317
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003318static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3319 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3320 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3321 return false;
3322}
3323
Steve Naroff54055232008-10-27 17:20:55 +00003324std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003325 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003326 std::string Tag) {
3327 const FunctionType *AFT = CE->getFunctionType();
3328 QualType RT = AFT->getResultType();
3329 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00003330 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00003331 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003332
Steve Naroff54055232008-10-27 17:20:55 +00003333 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003334
Douglas Gregor72564e72009-02-26 23:50:07 +00003335 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003336 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003337 // block (to reference imported block decl refs).
3338 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003339 } else if (BD->param_empty()) {
3340 S += "(" + StructRef + " *__cself)";
3341 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003342 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003343 assert(FT && "SynthesizeBlockFunc: No function proto");
3344 S += '(';
3345 // first add the implicit argument.
3346 S += StructRef + " *__cself, ";
3347 std::string ParamStr;
3348 for (BlockDecl::param_iterator AI = BD->param_begin(),
3349 E = BD->param_end(); AI != E; ++AI) {
3350 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003351 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003352 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003353 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00003354 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003355 else
Douglas Gregor30c42402011-09-27 22:38:19 +00003356 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003357 S += ParamStr;
3358 }
3359 if (FT->isVariadic()) {
3360 if (!BD->param_empty()) S += ", ";
3361 S += "...";
3362 }
3363 S += ')';
3364 }
3365 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003366
Steve Naroff54055232008-10-27 17:20:55 +00003367 // Create local declarations to avoid rewriting all closure decl ref exprs.
3368 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003369 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003370 E = BlockByRefDecls.end(); I != E; ++I) {
3371 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003372 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003373 std::string TypeString;
3374 RewriteByRefString(TypeString, Name, (*I));
3375 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003376 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003377 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003378 }
Steve Naroff54055232008-10-27 17:20:55 +00003379 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003380 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003381 E = BlockByCopyDecls.end(); I != E; ++I) {
3382 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00003383 // Handle nested closure invocation. For example:
3384 //
3385 // void (^myImportedClosure)(void);
3386 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003387 //
Steve Naroff54055232008-10-27 17:20:55 +00003388 // void (^anotherClosure)(void);
3389 // anotherClosure = ^(void) {
3390 // myImportedClosure(); // import and invoke the closure
3391 // };
3392 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003393 if (isTopLevelBlockPointerType((*I)->getType())) {
3394 RewriteBlockPointerTypeVariable(S, (*I));
3395 S += " = (";
3396 RewriteBlockPointerType(S, (*I)->getType());
3397 S += ")";
3398 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3399 }
3400 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00003401 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003402 QualType QT = (*I)->getType();
3403 if (HasLocalVariableExternalStorage(*I))
3404 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003405 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003406 S += Name + " = __cself->" +
3407 (*I)->getNameAsString() + "; // bound by copy\n";
3408 }
Steve Naroff54055232008-10-27 17:20:55 +00003409 }
3410 std::string RewrittenStr = RewrittenBlockExprs[CE];
3411 const char *cstr = RewrittenStr.c_str();
3412 while (*cstr++ != '{') ;
3413 S += cstr;
3414 S += "\n";
3415 return S;
3416}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003417
Steve Naroff54055232008-10-27 17:20:55 +00003418std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003419 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003420 std::string Tag) {
3421 std::string StructRef = "struct " + Tag;
3422 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003423
Steve Naroff54055232008-10-27 17:20:55 +00003424 S += funcName;
3425 S += "_block_copy_" + utostr(i);
3426 S += "(" + StructRef;
3427 S += "*dst, " + StructRef;
3428 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003429 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003430 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003431 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003432 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003433 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003434 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003435 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003436 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003437 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003438 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003439 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003440 else
3441 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003442 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003443 S += "}\n";
3444
Steve Naroff54055232008-10-27 17:20:55 +00003445 S += "\nstatic void __";
3446 S += funcName;
3447 S += "_block_dispose_" + utostr(i);
3448 S += "(" + StructRef;
3449 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003450 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003451 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003452 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003453 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003454 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003455 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003456 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003457 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003458 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003459 else
3460 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003461 }
Mike Stump1eb44332009-09-09 15:08:12 +00003462 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003463 return S;
3464}
3465
Steve Naroff01aec112009-12-06 21:14:13 +00003466std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3467 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003468 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003469 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003470
Steve Naroff54055232008-10-27 17:20:55 +00003471 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003472 S += " struct " + Desc;
3473 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003474
Steve Naroff01aec112009-12-06 21:14:13 +00003475 Constructor += "(void *fp, "; // Invoke function pointer.
3476 Constructor += "struct " + Desc; // Descriptor pointer.
3477 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003478
Steve Naroff54055232008-10-27 17:20:55 +00003479 if (BlockDeclRefs.size()) {
3480 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003481 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003482 E = BlockByCopyDecls.end(); I != E; ++I) {
3483 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003484 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003485 std::string ArgName = "_" + FieldName;
3486 // Handle nested closure invocation. For example:
3487 //
3488 // void (^myImportedBlock)(void);
3489 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003490 //
Steve Naroff54055232008-10-27 17:20:55 +00003491 // void (^anotherBlock)(void);
3492 // anotherBlock = ^(void) {
3493 // myImportedBlock(); // import and invoke the closure
3494 // };
3495 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003496 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003497 S += "struct __block_impl *";
3498 Constructor += ", void *" + ArgName;
3499 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003500 QualType QT = (*I)->getType();
3501 if (HasLocalVariableExternalStorage(*I))
3502 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003503 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3504 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003505 Constructor += ", " + ArgName;
3506 }
3507 S += FieldName + ";\n";
3508 }
3509 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003510 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003511 E = BlockByRefDecls.end(); I != E; ++I) {
3512 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003513 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003514 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003515 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003516 std::string TypeString;
3517 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003518 TypeString += " *";
3519 FieldName = TypeString + FieldName;
3520 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003521 Constructor += ", " + ArgName;
3522 }
3523 S += FieldName + "; // by ref\n";
3524 }
3525 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003526 Constructor += ", int flags=0)";
3527 // Initialize all "by copy" arguments.
3528 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003529 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003530 E = BlockByCopyDecls.end(); I != E; ++I) {
3531 std::string Name = (*I)->getNameAsString();
3532 if (firsTime) {
3533 Constructor += " : ";
3534 firsTime = false;
3535 }
3536 else
3537 Constructor += ", ";
3538 if (isTopLevelBlockPointerType((*I)->getType()))
3539 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3540 else
3541 Constructor += Name + "(_" + Name + ")";
3542 }
3543 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003544 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003545 E = BlockByRefDecls.end(); I != E; ++I) {
3546 std::string Name = (*I)->getNameAsString();
3547 if (firsTime) {
3548 Constructor += " : ";
3549 firsTime = false;
3550 }
3551 else
3552 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003553 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003554 }
3555
3556 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003557 if (GlobalVarDecl)
3558 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3559 else
3560 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003561 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003562
Steve Naroff01aec112009-12-06 21:14:13 +00003563 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003564 } else {
3565 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003566 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003567 if (GlobalVarDecl)
3568 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3569 else
3570 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003571 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3572 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003573 }
3574 Constructor += " ";
3575 Constructor += "}\n";
3576 S += Constructor;
3577 S += "};\n";
3578 return S;
3579}
3580
Steve Naroff01aec112009-12-06 21:14:13 +00003581std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3582 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003583 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00003584 unsigned hasCopy) {
3585 std::string S = "\nstatic struct " + DescTag;
3586
3587 S += " {\n unsigned long reserved;\n";
3588 S += " unsigned long Block_size;\n";
3589 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003590 S += " void (*copy)(struct ";
3591 S += ImplTag; S += "*, struct ";
3592 S += ImplTag; S += "*);\n";
3593
3594 S += " void (*dispose)(struct ";
3595 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003596 }
3597 S += "} ";
3598
3599 S += DescTag + "_DATA = { 0, sizeof(struct ";
3600 S += ImplTag + ")";
3601 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00003602 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3603 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00003604 }
3605 S += "};\n";
3606 return S;
3607}
3608
Steve Naroff54055232008-10-27 17:20:55 +00003609void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003610 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003611 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00003612 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003613 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003614 bool RewriteSC = (GlobalVarDecl &&
3615 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00003616 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003617 GlobalVarDecl->getType().getCVRQualifiers());
3618 if (RewriteSC) {
3619 std::string SC(" void __");
3620 SC += GlobalVarDecl->getNameAsString();
3621 SC += "() {}";
3622 InsertText(FunLocStart, SC);
3623 }
3624
Steve Naroff54055232008-10-27 17:20:55 +00003625 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003626 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3627 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003628 // Need to copy-in the inner copied-in variables not actually used in this
3629 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003630 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3631 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
3632 ValueDecl *VD = Exp->getDecl();
3633 BlockDeclRefs.push_back(Exp);
3634 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
3635 BlockByCopyDeclsPtrSet.insert(VD);
3636 BlockByCopyDecls.push_back(VD);
3637 }
3638 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
3639 BlockByRefDeclsPtrSet.insert(VD);
3640 BlockByRefDecls.push_back(VD);
3641 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003642 // imported objects in the inner blocks not used in the outer
3643 // blocks must be copied/disposed in the outer block as well.
3644 if (Exp->isByRef() ||
3645 VD->getType()->isObjCObjectPointerType() ||
3646 VD->getType()->isBlockPointerType())
3647 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003648 }
Steve Naroff54055232008-10-27 17:20:55 +00003649
Daniel Dunbar4087f272010-08-17 22:39:59 +00003650 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3651 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003652
Steve Naroff01aec112009-12-06 21:14:13 +00003653 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003654
Benjamin Kramerd999b372010-02-14 14:14:16 +00003655 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00003656
Steve Naroff01aec112009-12-06 21:14:13 +00003657 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00003658
Benjamin Kramerd999b372010-02-14 14:14:16 +00003659 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00003660
3661 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00003662 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003663 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00003664 }
Steve Naroff01aec112009-12-06 21:14:13 +00003665 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3666 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003667 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00003668
Steve Naroff54055232008-10-27 17:20:55 +00003669 BlockDeclRefs.clear();
3670 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003671 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003672 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003673 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003674 ImportedBlockDecls.clear();
3675 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003676 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003677 // Must insert any 'const/volatile/static here. Since it has been
3678 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003679 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00003680 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003681 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003682 if (GlobalVarDecl->getType().isConstQualified())
3683 SC += "const ";
3684 if (GlobalVarDecl->getType().isVolatileQualified())
3685 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003686 if (GlobalVarDecl->getType().isRestrictQualified())
3687 SC += "restrict ";
3688 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003689 }
3690
Steve Naroff54055232008-10-27 17:20:55 +00003691 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003692 InnerDeclRefsCount.clear();
3693 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003694 RewrittenBlockExprs.clear();
3695}
3696
3697void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3698 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003699 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00003700
Steve Naroff54055232008-10-27 17:20:55 +00003701 SynthesizeBlockLiterals(FunLocStart, FuncName);
3702}
3703
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003704static void BuildUniqueMethodName(std::string &Name,
3705 ObjCMethodDecl *MD) {
3706 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00003707 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003708 Name += "__" + MD->getSelector().getAsString();
3709 // Convert colons to underscores.
3710 std::string::size_type loc = 0;
3711 while ((loc = Name.find(":", loc)) != std::string::npos)
3712 Name.replace(loc, 1, "_");
3713}
3714
Steve Naroff54055232008-10-27 17:20:55 +00003715void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003716 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3717 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00003718 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003719 std::string FuncName;
3720 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00003721 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00003722}
3723
3724void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00003725 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00003726 if (*CI) {
3727 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3728 GetBlockDeclRefExprs(CBE->getBody());
3729 else
3730 GetBlockDeclRefExprs(*CI);
3731 }
3732 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003733 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00003734 // FIXME: Handle enums.
3735 if (!isa<FunctionDecl>(CDRE->getDecl()))
3736 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003737 }
3738 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3739 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
3740 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00003741 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
3742 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00003743 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003744 BlockDeclRefs.push_back(BDRE);
3745 }
3746
Steve Naroff54055232008-10-27 17:20:55 +00003747 return;
3748}
3749
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003750void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003751 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003752 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00003753 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003754 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003755 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3756 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003757 GetInnerBlockDeclRefExprs(CBE->getBody(),
3758 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003759 InnerContexts);
3760 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003761 else
3762 GetInnerBlockDeclRefExprs(*CI,
3763 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003764 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003765
3766 }
3767 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003768 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003769 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003770 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003771 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003772 }
3773 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3774 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3775 if (Var->isFunctionOrMethodVarDecl())
3776 ImportedLocalExternalDecls.insert(Var);
3777 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003778
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003779 return;
3780}
3781
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003782/// convertFunctionTypeOfBlocks - This routine converts a function type
3783/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003784/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003785/// all block pointers to function pointers.
3786QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3787 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3788 // FTP will be null for closures that don't take arguments.
3789 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003790 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003791 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003792 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003793
3794 if (FTP) {
3795 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3796 E = FTP->arg_type_end(); I && (I != E); ++I) {
3797 QualType t = *I;
3798 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003799 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003800 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003801 ArgTypes.push_back(t);
3802 }
3803 }
3804 QualType FuncType;
3805 // FIXME. Does this work if block takes no argument but has a return type
3806 // which is of block type?
3807 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00003808 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003809 else FuncType = QualType(FT, 0);
3810 return FuncType;
3811}
3812
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003813Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00003814 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00003815 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003816
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003817 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003818 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003819 } else if (const BlockDeclRefExpr *CDRE =
3820 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003821 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003822 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003823 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003824 }
3825 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3826 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3827 }
3828 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3829 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3830 else if (const ConditionalOperator *CEXPR =
3831 dyn_cast<ConditionalOperator>(BlockExp)) {
3832 Expr *LHSExp = CEXPR->getLHS();
3833 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3834 Expr *RHSExp = CEXPR->getRHS();
3835 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3836 Expr *CONDExp = CEXPR->getCond();
3837 ConditionalOperator *CondExpr =
3838 new (Context) ConditionalOperator(CONDExp,
3839 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003840 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00003841 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003842 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00003843 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3844 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00003845 } else if (const PseudoObjectExpr *POE
3846 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3847 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003848 } else {
3849 assert(1 && "RewriteBlockClass: Bad type");
3850 }
3851 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00003852 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00003853 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003854 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003855 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003856
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003857 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003858 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003859 &Context->Idents.get("__block_impl"));
3860 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003861
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003862 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003863 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00003864
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003865 // Push the block argument type.
3866 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003867 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00003868 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003869 E = FTP->arg_type_end(); I && (I != E); ++I) {
3870 QualType t = *I;
3871 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003872 if (!convertBlockPointerToFunctionPointer(t))
3873 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003874 ArgTypes.push_back(t);
3875 }
Steve Naroff54055232008-10-27 17:20:55 +00003876 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003877 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003878 QualType PtrToFuncCastType
3879 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003880
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003881 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00003882
John McCall9d125032010-01-15 18:39:57 +00003883 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00003884 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003885 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003886 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003887 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3888 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003889 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00003890
Douglas Gregor44b43212008-12-11 16:49:14 +00003891 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003892 SourceLocation(),
3893 &Context->Idents.get("FuncPtr"),
3894 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003895 /*BitWidth=*/0, /*Mutable=*/true,
3896 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003897 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003898 FD->getType(), VK_LValue,
3899 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00003900
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003901
John McCall9d125032010-01-15 18:39:57 +00003902 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00003903 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003904 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00003905
Chris Lattner5f9e2722011-07-23 10:55:15 +00003906 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003907 // Add the implicit argument.
3908 BlkExprs.push_back(BlkCast);
3909 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003910 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003911 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003912 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003913 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003914 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3915 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003916 Exp->getType(), VK_RValue,
3917 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003918 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003919}
3920
Steve Naroff621edce2009-04-29 16:37:50 +00003921// We need to return the rewritten expression to handle cases where the
3922// BlockDeclRefExpr is embedded in another expression being rewritten.
3923// For example:
3924//
3925// int main() {
3926// __block Foo *f;
3927// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00003928//
Steve Naroff621edce2009-04-29 16:37:50 +00003929// void (^myblock)() = ^() {
3930// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3931// i = 77;
3932// };
3933//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003934Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00003935 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003936 // for each DeclRefExp where BYREFVAR is name of the variable.
3937 ValueDecl *VD;
3938 bool isArrow = true;
3939 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
3940 VD = BDRE->getDecl();
3941 else {
3942 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
3943 isArrow = false;
3944 }
3945
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003946 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003947 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003948 &Context->Idents.get("__forwarding"),
3949 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003950 /*BitWidth=*/0, /*Mutable=*/true,
3951 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003952 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3953 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003954 FD->getType(), VK_LValue,
3955 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003956
Chris Lattner5f9e2722011-07-23 10:55:15 +00003957 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003958 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003959 &Context->Idents.get(Name),
3960 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003961 /*BitWidth=*/0, /*Mutable=*/true,
3962 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003963 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003964 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003965
3966
3967
Steve Naroffdf8570d2009-02-02 17:19:26 +00003968 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00003969 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3970 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003971 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003972 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00003973 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00003974}
3975
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003976// Rewrites the imported local variable V with external storage
3977// (static, extern, etc.) as *V
3978//
3979Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3980 ValueDecl *VD = DRE->getDecl();
3981 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3982 if (!ImportedLocalExternalDecls.count(Var))
3983 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00003984 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3985 VK_LValue, OK_Ordinary,
3986 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003987 // Need parens to enforce precedence.
3988 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3989 Exp);
3990 ReplaceStmt(DRE, PE);
3991 return PE;
3992}
3993
Steve Naroffb2f9e512008-11-03 23:29:32 +00003994void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3995 SourceLocation LocStart = CE->getLParenLoc();
3996 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003997
3998 // Need to avoid trying to rewrite synthesized casts.
3999 if (LocStart.isInvalid())
4000 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004001 // Need to avoid trying to rewrite casts contained in macros.
4002 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4003 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004004
Steve Naroff54055232008-10-27 17:20:55 +00004005 const char *startBuf = SM->getCharacterData(LocStart);
4006 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004007 QualType QT = CE->getType();
4008 const Type* TypePtr = QT->getAs<Type>();
4009 if (isa<TypeOfExprType>(TypePtr)) {
4010 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4011 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4012 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004013 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004014 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004015 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004016 return;
4017 }
Steve Naroff54055232008-10-27 17:20:55 +00004018 // advance the location to startArgList.
4019 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004020
Steve Naroff54055232008-10-27 17:20:55 +00004021 while (*argPtr++ && (argPtr < endBuf)) {
4022 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004023 case '^':
4024 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004025 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004026 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004027 break;
Steve Naroff54055232008-10-27 17:20:55 +00004028 }
4029 }
4030 return;
4031}
4032
4033void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4034 SourceLocation DeclLoc = FD->getLocation();
4035 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004036
Steve Naroff54055232008-10-27 17:20:55 +00004037 // We have 1 or more arguments that have closure pointers.
4038 const char *startBuf = SM->getCharacterData(DeclLoc);
4039 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004040
Steve Naroff54055232008-10-27 17:20:55 +00004041 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004042
Steve Naroff54055232008-10-27 17:20:55 +00004043 parenCount++;
4044 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004045 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004046 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004047
Steve Naroff54055232008-10-27 17:20:55 +00004048 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004049
Steve Naroff54055232008-10-27 17:20:55 +00004050 while (*argPtr++ && parenCount) {
4051 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004052 case '^':
4053 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004054 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004055 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004056 break;
4057 case '(':
4058 parenCount++;
4059 break;
4060 case ')':
4061 parenCount--;
4062 break;
Steve Naroff54055232008-10-27 17:20:55 +00004063 }
4064 }
4065 return;
4066}
4067
4068bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004069 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004070 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004071 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004072 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004073 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004074 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004075 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004076 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004077 }
4078 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004079 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004080 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004081 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004082 return true;
4083 }
4084 return false;
4085}
4086
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004087bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4088 const FunctionProtoType *FTP;
4089 const PointerType *PT = QT->getAs<PointerType>();
4090 if (PT) {
4091 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4092 } else {
4093 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4094 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4095 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4096 }
4097 if (FTP) {
4098 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004099 E = FTP->arg_type_end(); I != E; ++I) {
4100 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004101 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004102 if ((*I)->isObjCObjectPointerType() &&
4103 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4104 return true;
4105 }
4106
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004107 }
4108 return false;
4109}
4110
Ted Kremenek8189cde2009-02-07 01:47:29 +00004111void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4112 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004113 const char *argPtr = strchr(Name, '(');
4114 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004115
Steve Naroff54055232008-10-27 17:20:55 +00004116 LParen = argPtr; // output the start.
4117 argPtr++; // skip past the left paren.
4118 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004119
Steve Naroff54055232008-10-27 17:20:55 +00004120 while (*argPtr && parenCount) {
4121 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004122 case '(': parenCount++; break;
4123 case ')': parenCount--; break;
4124 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004125 }
4126 if (parenCount) argPtr++;
4127 }
4128 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4129 RParen = argPtr; // output the end
4130}
4131
4132void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4133 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4134 RewriteBlockPointerFunctionArgs(FD);
4135 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004136 }
Steve Naroff54055232008-10-27 17:20:55 +00004137 // Handle Variables and Typedefs.
4138 SourceLocation DeclLoc = ND->getLocation();
4139 QualType DeclT;
4140 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4141 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00004142 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00004143 DeclT = TDD->getUnderlyingType();
4144 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4145 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004146 else
David Blaikieb219cfc2011-09-23 05:06:16 +00004147 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004148
Steve Naroff54055232008-10-27 17:20:55 +00004149 const char *startBuf = SM->getCharacterData(DeclLoc);
4150 const char *endBuf = startBuf;
4151 // scan backward (from the decl location) for the end of the previous decl.
4152 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4153 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004154 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004155 std::string buf;
4156 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004157 // *startBuf != '^' if we are dealing with a pointer to function that
4158 // may take block argument types (which will be handled below).
4159 if (*startBuf == '^') {
4160 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004161 buf = '*';
4162 startBuf++;
4163 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004164 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004165 while (*startBuf != ')') {
4166 buf += *startBuf;
4167 startBuf++;
4168 OrigLength++;
4169 }
4170 buf += ')';
4171 OrigLength++;
4172
4173 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4174 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004175 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004176 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004177 DeclLoc = ND->getLocation();
4178 startBuf = SM->getCharacterData(DeclLoc);
4179 const char *argListBegin, *argListEnd;
4180 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4181 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004182 if (*argListBegin == '^')
4183 buf += '*';
4184 else if (*argListBegin == '<') {
4185 buf += "/*";
4186 buf += *argListBegin++;
4187 OrigLength++;;
4188 while (*argListBegin != '>') {
4189 buf += *argListBegin++;
4190 OrigLength++;
4191 }
4192 buf += *argListBegin;
4193 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00004194 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004195 else
4196 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00004197 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004198 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004199 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004200 buf += ')';
4201 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004202 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004203 ReplaceText(Start, OrigLength, buf);
4204
Steve Naroff54055232008-10-27 17:20:55 +00004205 return;
4206}
4207
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004208
4209/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4210/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4211/// struct Block_byref_id_object *src) {
4212/// _Block_object_assign (&_dest->object, _src->object,
4213/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4214/// [|BLOCK_FIELD_IS_WEAK]) // object
4215/// _Block_object_assign(&_dest->object, _src->object,
4216/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4217/// [|BLOCK_FIELD_IS_WEAK]) // block
4218/// }
4219/// And:
4220/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4221/// _Block_object_dispose(_src->object,
4222/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4223/// [|BLOCK_FIELD_IS_WEAK]) // object
4224/// _Block_object_dispose(_src->object,
4225/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4226/// [|BLOCK_FIELD_IS_WEAK]) // block
4227/// }
4228
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004229std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4230 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004231 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004232 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004233 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004234 CopyDestroyCache.insert(flag);
4235 S = "static void __Block_byref_id_object_copy_";
4236 S += utostr(flag);
4237 S += "(void *dst, void *src) {\n";
4238
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004239 // offset into the object pointer is computed as:
4240 // void * + void* + int + int + void* + void *
4241 unsigned IntSize =
4242 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4243 unsigned VoidPtrSize =
4244 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4245
Ken Dyck0c4e5d62011-04-30 16:08:27 +00004246 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004247 S += " _Block_object_assign((char*)dst + ";
4248 S += utostr(offset);
4249 S += ", *(void * *) ((char*)src + ";
4250 S += utostr(offset);
4251 S += "), ";
4252 S += utostr(flag);
4253 S += ");\n}\n";
4254
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004255 S += "static void __Block_byref_id_object_dispose_";
4256 S += utostr(flag);
4257 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004258 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4259 S += utostr(offset);
4260 S += "), ";
4261 S += utostr(flag);
4262 S += ");\n}\n";
4263 return S;
4264}
4265
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004266/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4267/// the declaration into:
4268/// struct __Block_byref_ND {
4269/// void *__isa; // NULL for everything except __weak pointers
4270/// struct __Block_byref_ND *__forwarding;
4271/// int32_t __flags;
4272/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004273/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4274/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004275/// typex ND;
4276/// };
4277///
4278/// It then replaces declaration of ND variable with:
4279/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4280/// __size=sizeof(struct __Block_byref_ND),
4281/// ND=initializer-if-any};
4282///
4283///
4284void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004285 // Insert declaration for the function in which block literal is
4286 // used.
4287 if (CurFunctionDeclToDeclareForBlock)
4288 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004289 int flag = 0;
4290 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004291 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004292 if (DeclLoc.isInvalid())
4293 // If type location is missing, it is because of missing type (a warning).
4294 // Use variable's location which is good for this case.
4295 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004296 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004297 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00004298 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004299 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004300 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004301 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004302 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004303 ByrefType += " {\n";
4304 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004305 RewriteByRefString(ByrefType, Name, ND);
4306 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004307 ByrefType += " int __flags;\n";
4308 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004309 // Add void *__Block_byref_id_object_copy;
4310 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004311 QualType Ty = ND->getType();
4312 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4313 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004314 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4315 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004316 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004317
4318 QualType T = Ty;
4319 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00004320 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004321
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004322 ByrefType += " " + Name + ";\n";
4323 ByrefType += "};\n";
4324 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004325 SourceLocation FunLocStart;
4326 if (CurFunctionDef)
4327 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4328 else {
4329 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4330 FunLocStart = CurMethodDef->getLocStart();
4331 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004332 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004333 if (Ty.isObjCGCWeak()) {
4334 flag |= BLOCK_FIELD_IS_WEAK;
4335 isa = 1;
4336 }
4337
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004338 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004339 flag = BLOCK_BYREF_CALLER;
4340 QualType Ty = ND->getType();
4341 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4342 if (Ty->isBlockPointerType())
4343 flag |= BLOCK_FIELD_IS_BLOCK;
4344 else
4345 flag |= BLOCK_FIELD_IS_OBJECT;
4346 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004347 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004348 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004349 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004350
4351 // struct __Block_byref_ND ND =
4352 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4353 // initializer-if-any};
4354 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004355 unsigned flags = 0;
4356 if (HasCopyAndDispose)
4357 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004358 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004359 ByrefType.clear();
4360 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004361 std::string ForwardingCastType("(");
4362 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004363 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004364 ByrefType += " " + Name + " = {(void*)";
4365 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004366 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004367 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004368 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004369 ByrefType += "sizeof(";
4370 RewriteByRefString(ByrefType, Name, ND);
4371 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004372 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004373 ByrefType += ", __Block_byref_id_object_copy_";
4374 ByrefType += utostr(flag);
4375 ByrefType += ", __Block_byref_id_object_dispose_";
4376 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004377 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004378 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004379 unsigned nameSize = Name.size();
4380 // for block or function pointer declaration. Name is aleady
4381 // part of the declaration.
4382 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4383 nameSize = 1;
4384 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004385 }
4386 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004387 SourceLocation startLoc;
4388 Expr *E = ND->getInit();
4389 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4390 startLoc = ECE->getLParenLoc();
4391 else
4392 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00004393 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004394 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004395 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004396 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004397 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004398 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004399 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004400 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004401 ByrefType += "sizeof(";
4402 RewriteByRefString(ByrefType, Name, ND);
4403 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004404 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004405 ByrefType += "__Block_byref_id_object_copy_";
4406 ByrefType += utostr(flag);
4407 ByrefType += ", __Block_byref_id_object_dispose_";
4408 ByrefType += utostr(flag);
4409 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004410 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004411 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004412
4413 // Complete the newly synthesized compound expression by inserting a right
4414 // curly brace before the end of the declaration.
4415 // FIXME: This approach avoids rewriting the initializer expression. It
4416 // also assumes there is only one declarator. For example, the following
4417 // isn't currently supported by this routine (in general):
4418 //
4419 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4420 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00004421 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4422 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00004423 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4424 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004425 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00004426
Benjamin Kramerd999b372010-02-14 14:14:16 +00004427 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004428 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004429 return;
4430}
4431
Mike Stump1eb44332009-09-09 15:08:12 +00004432void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004433 // Add initializers for any closure decl refs.
4434 GetBlockDeclRefExprs(Exp->getBody());
4435 if (BlockDeclRefs.size()) {
4436 // Unique all "by copy" declarations.
4437 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004438 if (!BlockDeclRefs[i]->isByRef()) {
4439 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4440 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4441 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4442 }
4443 }
Steve Naroff54055232008-10-27 17:20:55 +00004444 // Unique all "by ref" declarations.
4445 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4446 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004447 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4448 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4449 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4450 }
Steve Naroff54055232008-10-27 17:20:55 +00004451 }
4452 // Find any imported blocks...they will need special attention.
4453 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004454 if (BlockDeclRefs[i]->isByRef() ||
4455 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00004456 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00004457 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00004458 }
4459}
4460
Chris Lattner5f9e2722011-07-23 10:55:15 +00004461FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004462 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004463 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004464 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4465 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00004466 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004467}
4468
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004469Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004470 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004471 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00004472 Blocks.push_back(Exp);
4473
4474 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004475
4476 // Add inner imported variables now used in current block.
4477 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004478 if (!InnerBlockDeclRefs.empty()) {
4479 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4480 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4481 ValueDecl *VD = Exp->getDecl();
4482 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004483 // We need to save the copied-in variables in nested
4484 // blocks because it is needed at the end for some of the API generations.
4485 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004486 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4487 BlockDeclRefs.push_back(Exp);
4488 BlockByCopyDeclsPtrSet.insert(VD);
4489 BlockByCopyDecls.push_back(VD);
4490 }
4491 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4492 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4493 BlockDeclRefs.push_back(Exp);
4494 BlockByRefDeclsPtrSet.insert(VD);
4495 BlockByRefDecls.push_back(VD);
4496 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004497 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004498 // Find any imported blocks...they will need special attention.
4499 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4500 if (InnerBlockDeclRefs[i]->isByRef() ||
4501 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4502 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4503 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004504 }
4505 InnerDeclRefsCount.push_back(countOfInnerDecls);
4506
Steve Narofffa15fd92008-10-28 20:29:00 +00004507 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004508
Steve Narofffa15fd92008-10-28 20:29:00 +00004509 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004510 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004511 else if (CurMethodDef)
4512 BuildUniqueMethodName(FuncName, CurMethodDef);
4513 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004514 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004515
Steve Narofffa15fd92008-10-28 20:29:00 +00004516 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004517
Steve Narofffa15fd92008-10-28 20:29:00 +00004518 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4519 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004520
Steve Narofffa15fd92008-10-28 20:29:00 +00004521 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004522 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4523 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00004524
4525 FunctionDecl *FD;
4526 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004527
Steve Narofffa15fd92008-10-28 20:29:00 +00004528 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00004529 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00004530 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
4531 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004532
Chris Lattner5f9e2722011-07-23 10:55:15 +00004533 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004534
Steve Narofffdc03722008-10-29 21:23:59 +00004535 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00004536 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00004537 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004538 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004539 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004540 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004541 InitExprs.push_back(castExpr);
4542
Steve Naroff01aec112009-12-06 21:14:13 +00004543 // Initialize the block descriptor.
4544 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004545
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004546 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4547 SourceLocation(), SourceLocation(),
4548 &Context->Idents.get(DescData.c_str()),
4549 Context->VoidPtrTy, 0,
4550 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00004551 UnaryOperator *DescRefExpr =
4552 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
4553 Context->VoidPtrTy,
4554 VK_LValue,
4555 SourceLocation()),
4556 UO_AddrOf,
4557 Context->getPointerType(Context->VoidPtrTy),
4558 VK_RValue, OK_Ordinary,
4559 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00004560 InitExprs.push_back(DescRefExpr);
4561
Steve Narofffa15fd92008-10-28 20:29:00 +00004562 // Add initializers for any closure decl refs.
4563 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004564 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004565 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004566 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004567 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004568 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004569 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00004570 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004571 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4572 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004573 if (HasLocalVariableExternalStorage(*I)) {
4574 QualType QT = (*I)->getType();
4575 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004576 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4577 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004578 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004579 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004580 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004581 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4582 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004583 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004584 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004585 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004586 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004587 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4588 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004589 if (HasLocalVariableExternalStorage(*I)) {
4590 QualType QT = (*I)->getType();
4591 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004592 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4593 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004594 }
4595
Steve Narofffa15fd92008-10-28 20:29:00 +00004596 }
Mike Stump1eb44332009-09-09 15:08:12 +00004597 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004598 }
4599 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004600 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004601 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004602 ValueDecl *ND = (*I);
4603 std::string Name(ND->getNameAsString());
4604 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004605 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004606 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4607 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004608 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004609 SourceLocation(), SourceLocation(),
4610 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004611 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4612 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4613
Daniel Dunbar4087f272010-08-17 22:39:59 +00004614 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004615 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4616 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004617 bool isNestedCapturedVar = false;
4618 if (block)
4619 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4620 ce = block->capture_end(); ci != ce; ++ci) {
4621 const VarDecl *variable = ci->getVariable();
4622 if (variable == ND && ci->isNested()) {
4623 assert (ci->isByRef() &&
4624 "SynthBlockInitExpr - captured block variable is not byref");
4625 isNestedCapturedVar = true;
4626 break;
4627 }
4628 }
4629 // captured nested byref variable has its address passed. Do not take
4630 // its address again.
4631 if (!isNestedCapturedVar)
4632 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00004633 Context->getPointerType(Exp->getType()),
4634 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004635 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004636 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004637 }
4638 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004639 if (ImportedBlockDecls.size()) {
4640 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4641 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004642 unsigned IntSize =
4643 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004644 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4645 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00004646 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004647 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004648 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004649 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00004650 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004651 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00004652 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004653 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004654 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004655 BlockDeclRefs.clear();
4656 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004657 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004658 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004659 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004660 ImportedBlockDecls.clear();
4661 return NewRep;
4662}
4663
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004664bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4665 if (const ObjCForCollectionStmt * CS =
4666 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4667 return CS->getElement() == DS;
4668 return false;
4669}
4670
Steve Narofffa15fd92008-10-28 20:29:00 +00004671//===----------------------------------------------------------------------===//
4672// Function Body / Expression rewriting
4673//===----------------------------------------------------------------------===//
4674
4675Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004676 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004677 isa<DoStmt>(S) || isa<ForStmt>(S))
4678 Stmts.push_back(S);
4679 else if (isa<ObjCForCollectionStmt>(S)) {
4680 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004681 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004682 }
Mike Stump1eb44332009-09-09 15:08:12 +00004683
John McCall4b9c2d22011-11-06 09:01:30 +00004684 // Pseudo-object operations and ivar references need special
4685 // treatment because we're going to recursively rewrite them.
4686 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4687 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4688 return RewritePropertyOrImplicitSetter(PseudoOp);
4689 } else {
4690 return RewritePropertyOrImplicitGetter(PseudoOp);
4691 }
4692 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4693 return RewriteObjCIvarRefExpr(IvarRefExpr);
4694 }
4695
Steve Narofffa15fd92008-10-28 20:29:00 +00004696 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004697
Steve Narofffa15fd92008-10-28 20:29:00 +00004698 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00004699 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00004700 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00004701 Stmt *childStmt = (*CI);
4702 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004703 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00004704 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004705 }
Nick Lewycky7e749242010-10-31 21:07:24 +00004706 }
Mike Stump1eb44332009-09-09 15:08:12 +00004707
Steve Narofffa15fd92008-10-28 20:29:00 +00004708 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004709 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004710 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4711 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004712 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004713 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004714 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00004715 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004716 Stmt *SaveCurrentBody = CurrentBody;
4717 CurrentBody = BE->getBody();
4718 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004719 // block literal on rhs of a property-dot-sytax assignment
4720 // must be replaced by its synthesize ast so getRewrittenText
4721 // works as expected. In this case, what actually ends up on RHS
4722 // is the blockTranscribed which is the helper function for the
4723 // block literal; as in: self.c = ^() {[ace ARR];};
4724 bool saveDisableReplaceStmt = DisableReplaceStmt;
4725 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00004726 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004727 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004728 CurrentBody = SaveCurrentBody;
4729 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004730 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004731 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004732 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004733 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004734
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004735 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4736
Steve Narofffa15fd92008-10-28 20:29:00 +00004737 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004738 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004739 return blockTranscribed;
4740 }
4741 // Handle specific things.
4742 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4743 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004744
Steve Narofffa15fd92008-10-28 20:29:00 +00004745 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4746 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004747
Steve Narofffa15fd92008-10-28 20:29:00 +00004748 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4749 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004750
Steve Narofffa15fd92008-10-28 20:29:00 +00004751 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004752#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004753 // Before we rewrite it, put the original message expression in a comment.
4754 SourceLocation startLoc = MessExpr->getLocStart();
4755 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004756
Steve Narofffa15fd92008-10-28 20:29:00 +00004757 const char *startBuf = SM->getCharacterData(startLoc);
4758 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004759
Steve Narofffa15fd92008-10-28 20:29:00 +00004760 std::string messString;
4761 messString += "// ";
4762 messString.append(startBuf, endBuf-startBuf+1);
4763 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004764
4765 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004766 // InsertText(clang::SourceLocation, char const*, unsigned int).
4767 // InsertText(startLoc, messString.c_str(), messString.size());
4768 // Tried this, but it didn't work either...
4769 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004770#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004771 return RewriteMessageExpr(MessExpr);
4772 }
Mike Stump1eb44332009-09-09 15:08:12 +00004773
Steve Narofffa15fd92008-10-28 20:29:00 +00004774 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4775 return RewriteObjCTryStmt(StmtTry);
4776
4777 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4778 return RewriteObjCSynchronizedStmt(StmtTry);
4779
4780 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4781 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004782
Steve Narofffa15fd92008-10-28 20:29:00 +00004783 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4784 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004785
4786 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004787 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004788 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004789 OrigStmtRange.getEnd());
4790 if (BreakStmt *StmtBreakStmt =
4791 dyn_cast<BreakStmt>(S))
4792 return RewriteBreakStmt(StmtBreakStmt);
4793 if (ContinueStmt *StmtContinueStmt =
4794 dyn_cast<ContinueStmt>(S))
4795 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004796
4797 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004798 // and cast exprs.
4799 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4800 // FIXME: What we're doing here is modifying the type-specifier that
4801 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004802 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004803 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4804 // the context of an ObjCForCollectionStmt. For example:
4805 // NSArray *someArray;
4806 // for (id <FooProtocol> index in someArray) ;
4807 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4808 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004809 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004810 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004811
Steve Narofffa15fd92008-10-28 20:29:00 +00004812 // Blocks rewrite rules.
4813 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4814 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004815 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004816 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004817 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004818 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004819 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004820 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004821 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004822 if (VD->hasAttr<BlocksAttr>()) {
4823 static unsigned uniqueByrefDeclCount = 0;
4824 assert(!BlockByRefDeclNo.count(ND) &&
4825 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4826 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004827 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004828 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004829 else
4830 RewriteTypeOfDecl(VD);
4831 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004832 }
Richard Smith162e1c12011-04-15 14:24:37 +00004833 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004834 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004835 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004836 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004837 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4838 }
4839 }
4840 }
Mike Stump1eb44332009-09-09 15:08:12 +00004841
Steve Narofffa15fd92008-10-28 20:29:00 +00004842 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4843 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004844
4845 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004846 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4847 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004848 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4849 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004850 && "Statement stack mismatch");
4851 Stmts.pop_back();
4852 }
4853 // Handle blocks rewriting.
4854 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4855 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00004856 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004857 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004858 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4859 ValueDecl *VD = DRE->getDecl();
4860 if (VD->hasAttr<BlocksAttr>())
4861 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004862 if (HasLocalVariableExternalStorage(VD))
4863 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004864 }
4865
Steve Narofffa15fd92008-10-28 20:29:00 +00004866 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004867 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004868 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004869 ReplaceStmt(S, BlockCall);
4870 return BlockCall;
4871 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004872 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004873 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004874 RewriteCastExpr(CE);
4875 }
4876#if 0
4877 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00004878 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4879 ICE->getSubExpr(),
4880 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004881 // Get the new text.
4882 std::string SStr;
4883 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00004884 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00004885 const std::string &Str = Buf.str();
4886
4887 printf("CAST = %s\n", &Str[0]);
4888 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4889 delete S;
4890 return Replacement;
4891 }
4892#endif
4893 // Return this stmt unmodified.
4894 return S;
4895}
4896
Steve Naroff3d7e7862009-12-05 15:55:59 +00004897void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4898 for (RecordDecl::field_iterator i = RD->field_begin(),
4899 e = RD->field_end(); i != e; ++i) {
4900 FieldDecl *FD = *i;
4901 if (isTopLevelBlockPointerType(FD->getType()))
4902 RewriteBlockPointerDecl(FD);
4903 if (FD->getType()->isObjCQualifiedIdType() ||
4904 FD->getType()->isObjCQualifiedInterfaceType())
4905 RewriteObjCQualifiedInterfaceTypes(FD);
4906 }
4907}
4908
Steve Narofffa15fd92008-10-28 20:29:00 +00004909/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4910/// main file of the input.
4911void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004912 switch (D->getKind()) {
4913 case Decl::Function: {
4914 FunctionDecl *FD = cast<FunctionDecl>(D);
4915 if (FD->isOverloadedOperator())
4916 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004917
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004918 // Since function prototypes don't have ParmDecl's, we check the function
4919 // prototype. This enables us to rewrite function declarations and
4920 // definitions using the same code.
4921 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004922
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004923 // FIXME: If this should support Obj-C++, support CXXTryStmt
4924 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4925 CurFunctionDef = FD;
4926 CurFunctionDeclToDeclareForBlock = FD;
4927 CurrentBody = Body;
4928 Body =
4929 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4930 FD->setBody(Body);
4931 CurrentBody = 0;
4932 if (PropParentMap) {
4933 delete PropParentMap;
4934 PropParentMap = 0;
4935 }
4936 // This synthesizes and inserts the block "impl" struct, invoke function,
4937 // and any copy/dispose helper functions.
4938 InsertBlockLiteralsWithinFunction(FD);
4939 CurFunctionDef = 0;
4940 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004941 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004942 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004943 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004944 case Decl::ObjCMethod: {
4945 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4946 if (CompoundStmt *Body = MD->getCompoundBody()) {
4947 CurMethodDef = MD;
4948 CurrentBody = Body;
4949 Body =
4950 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4951 MD->setBody(Body);
4952 CurrentBody = 0;
4953 if (PropParentMap) {
4954 delete PropParentMap;
4955 PropParentMap = 0;
4956 }
4957 InsertBlockLiteralsWithinMethod(MD);
4958 CurMethodDef = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004959 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004960 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004961 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004962 case Decl::ObjCImplementation: {
4963 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4964 ClassImplementation.push_back(CI);
4965 break;
4966 }
4967 case Decl::ObjCCategoryImpl: {
4968 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4969 CategoryImplementation.push_back(CI);
4970 break;
4971 }
4972 case Decl::Var: {
4973 VarDecl *VD = cast<VarDecl>(D);
4974 RewriteObjCQualifiedInterfaceTypes(VD);
4975 if (isTopLevelBlockPointerType(VD->getType()))
4976 RewriteBlockPointerDecl(VD);
4977 else if (VD->getType()->isFunctionPointerType()) {
4978 CheckFunctionPointerDecl(VD->getType(), VD);
4979 if (VD->getInit()) {
4980 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4981 RewriteCastExpr(CE);
4982 }
4983 }
4984 } else if (VD->getType()->isRecordType()) {
4985 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4986 if (RD->isCompleteDefinition())
4987 RewriteRecordBody(RD);
4988 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004989 if (VD->getInit()) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004990 GlobalVarDecl = VD;
4991 CurrentBody = VD->getInit();
4992 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4993 CurrentBody = 0;
4994 if (PropParentMap) {
4995 delete PropParentMap;
4996 PropParentMap = 0;
4997 }
4998 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4999 GlobalVarDecl = 0;
5000
5001 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005002 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005003 RewriteCastExpr(CE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005004 }
5005 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005006 break;
5007 }
5008 case Decl::TypeAlias:
5009 case Decl::Typedef: {
5010 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5011 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5012 RewriteBlockPointerDecl(TD);
5013 else if (TD->getUnderlyingType()->isFunctionPointerType())
5014 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5015 }
5016 break;
5017 }
5018 case Decl::CXXRecord:
5019 case Decl::Record: {
5020 RecordDecl *RD = cast<RecordDecl>(D);
5021 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005022 RewriteRecordBody(RD);
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005023 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00005024 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005025 default:
5026 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00005027 }
5028 // Nothing yet.
5029}
5030
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005031void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005032 if (Diags.hasErrorOccurred())
5033 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005034
Steve Narofffa15fd92008-10-28 20:29:00 +00005035 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005036
Steve Naroff621edce2009-04-29 16:37:50 +00005037 // Here's a great place to add any extra declarations that may be needed.
5038 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005039 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005040 E = ProtocolExprDecls.end(); I != E; ++I)
5041 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5042
Benjamin Kramerd999b372010-02-14 14:14:16 +00005043 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005044 if (ClassImplementation.size() || CategoryImplementation.size())
5045 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005046
Steve Narofffa15fd92008-10-28 20:29:00 +00005047 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5048 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005049 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005050 Rewrite.getRewriteBufferFor(MainFileID)) {
5051 //printf("Changed:\n");
5052 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5053 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005054 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005055 }
Steve Narofface66252008-11-13 20:07:04 +00005056
Steve Naroff621edce2009-04-29 16:37:50 +00005057 if (ClassImplementation.size() || CategoryImplementation.size() ||
5058 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005059 // Rewrite Objective-c meta data*
5060 std::string ResultStr;
Fariborz Jahanian58457172011-12-05 18:43:13 +00005061 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff0aab7962008-11-14 14:10:01 +00005062 // Emit metadata.
5063 *OutFile << ResultStr;
5064 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005065 OutFile->flush();
5066}
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005067
5068void RewriteObjCFragileABI::Initialize(ASTContext &context) {
5069 InitializeCommon(context);
5070
5071 // declaring objc_selector outside the parameter list removes a silly
5072 // scope related warning...
5073 if (IsHeader)
5074 Preamble = "#pragma once\n";
5075 Preamble += "struct objc_selector; struct objc_class;\n";
5076 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5077 Preamble += "struct objc_object *superClass; ";
5078 if (LangOpts.MicrosoftExt) {
5079 // Add a constructor for creating temporary objects.
5080 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5081 ": ";
5082 Preamble += "object(o), superClass(s) {} ";
5083 }
5084 Preamble += "};\n";
5085 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5086 Preamble += "typedef struct objc_object Protocol;\n";
5087 Preamble += "#define _REWRITER_typedef_Protocol\n";
5088 Preamble += "#endif\n";
5089 if (LangOpts.MicrosoftExt) {
5090 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5091 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5092 } else
5093 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5094 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5095 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5096 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5097 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5098 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5099 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5100 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5101 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5102 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5103 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5104 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5105 Preamble += "(const char *);\n";
5106 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5107 Preamble += "(struct objc_class *);\n";
5108 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5109 Preamble += "(const char *);\n";
5110 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5111 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5112 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5113 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5114 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5115 Preamble += "(struct objc_class *, struct objc_object *);\n";
5116 // @synchronized hooks.
5117 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5118 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5119 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5120 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5121 Preamble += "struct __objcFastEnumerationState {\n\t";
5122 Preamble += "unsigned long state;\n\t";
5123 Preamble += "void **itemsPtr;\n\t";
5124 Preamble += "unsigned long *mutationsPtr;\n\t";
5125 Preamble += "unsigned long extra[5];\n};\n";
5126 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5127 Preamble += "#define __FASTENUMERATIONSTATE\n";
5128 Preamble += "#endif\n";
5129 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5130 Preamble += "struct __NSConstantStringImpl {\n";
5131 Preamble += " int *isa;\n";
5132 Preamble += " int flags;\n";
5133 Preamble += " char *str;\n";
5134 Preamble += " long length;\n";
5135 Preamble += "};\n";
5136 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5137 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5138 Preamble += "#else\n";
5139 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5140 Preamble += "#endif\n";
5141 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5142 Preamble += "#endif\n";
5143 // Blocks preamble.
5144 Preamble += "#ifndef BLOCK_IMPL\n";
5145 Preamble += "#define BLOCK_IMPL\n";
5146 Preamble += "struct __block_impl {\n";
5147 Preamble += " void *isa;\n";
5148 Preamble += " int Flags;\n";
5149 Preamble += " int Reserved;\n";
5150 Preamble += " void *FuncPtr;\n";
5151 Preamble += "};\n";
5152 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5153 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5154 Preamble += "extern \"C\" __declspec(dllexport) "
5155 "void _Block_object_assign(void *, const void *, const int);\n";
5156 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5157 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5158 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5159 Preamble += "#else\n";
5160 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5161 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5162 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5163 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5164 Preamble += "#endif\n";
5165 Preamble += "#endif\n";
5166 if (LangOpts.MicrosoftExt) {
5167 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5168 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5169 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5170 Preamble += "#define __attribute__(X)\n";
5171 Preamble += "#endif\n";
5172 Preamble += "#define __weak\n";
5173 }
5174 else {
5175 Preamble += "#define __block\n";
5176 Preamble += "#define __weak\n";
5177 }
5178 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5179 // as this avoids warning in any 64bit/32bit compilation model.
5180 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5181}
5182
5183/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5184/// ivar offset.
5185void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5186 std::string &Result) {
5187 if (ivar->isBitField()) {
5188 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5189 // place all bitfields at offset 0.
5190 Result += "0";
5191 } else {
5192 Result += "__OFFSETOFIVAR__(struct ";
5193 Result += ivar->getContainingInterface()->getNameAsString();
5194 if (LangOpts.MicrosoftExt)
5195 Result += "_IMPL";
5196 Result += ", ";
5197 Result += ivar->getNameAsString();
5198 Result += ")";
5199 }
5200}
5201
5202/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5203void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5204 ObjCProtocolDecl *PDecl, StringRef prefix,
5205 StringRef ClassName, std::string &Result) {
5206 static bool objc_protocol_methods = false;
5207
5208 // Output struct protocol_methods holder of method selector and type.
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005209 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005210 /* struct protocol_methods {
5211 SEL _cmd;
5212 char *method_types;
5213 }
5214 */
5215 Result += "\nstruct _protocol_methods {\n";
5216 Result += "\tstruct objc_selector *_cmd;\n";
5217 Result += "\tchar *method_types;\n";
5218 Result += "};\n";
5219
5220 objc_protocol_methods = true;
5221 }
5222 // Do not synthesize the protocol more than once.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005223 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005224 return;
5225
5226 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5227 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5228 PDecl->instmeth_end());
5229 /* struct _objc_protocol_method_list {
5230 int protocol_method_count;
5231 struct protocol_methods protocols[];
5232 }
5233 */
5234 Result += "\nstatic struct {\n";
5235 Result += "\tint protocol_method_count;\n";
5236 Result += "\tstruct _protocol_methods protocol_methods[";
5237 Result += utostr(NumMethods);
5238 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5239 Result += PDecl->getNameAsString();
5240 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5241 "{\n\t" + utostr(NumMethods) + "\n";
5242
5243 // Output instance methods declared in this protocol.
5244 for (ObjCProtocolDecl::instmeth_iterator
5245 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5246 I != E; ++I) {
5247 if (I == PDecl->instmeth_begin())
5248 Result += "\t ,{{(struct objc_selector *)\"";
5249 else
5250 Result += "\t ,{(struct objc_selector *)\"";
5251 Result += (*I)->getSelector().getAsString();
5252 std::string MethodTypeString;
5253 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5254 Result += "\", \"";
5255 Result += MethodTypeString;
5256 Result += "\"}\n";
5257 }
5258 Result += "\t }\n};\n";
5259 }
5260
5261 // Output class methods declared in this protocol.
5262 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5263 PDecl->classmeth_end());
5264 if (NumMethods > 0) {
5265 /* struct _objc_protocol_method_list {
5266 int protocol_method_count;
5267 struct protocol_methods protocols[];
5268 }
5269 */
5270 Result += "\nstatic struct {\n";
5271 Result += "\tint protocol_method_count;\n";
5272 Result += "\tstruct _protocol_methods protocol_methods[";
5273 Result += utostr(NumMethods);
5274 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5275 Result += PDecl->getNameAsString();
5276 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5277 "{\n\t";
5278 Result += utostr(NumMethods);
5279 Result += "\n";
5280
5281 // Output instance methods declared in this protocol.
5282 for (ObjCProtocolDecl::classmeth_iterator
5283 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5284 I != E; ++I) {
5285 if (I == PDecl->classmeth_begin())
5286 Result += "\t ,{{(struct objc_selector *)\"";
5287 else
5288 Result += "\t ,{(struct objc_selector *)\"";
5289 Result += (*I)->getSelector().getAsString();
5290 std::string MethodTypeString;
5291 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5292 Result += "\", \"";
5293 Result += MethodTypeString;
5294 Result += "\"}\n";
5295 }
5296 Result += "\t }\n};\n";
5297 }
5298
5299 // Output:
5300 /* struct _objc_protocol {
5301 // Objective-C 1.0 extensions
5302 struct _objc_protocol_extension *isa;
5303 char *protocol_name;
5304 struct _objc_protocol **protocol_list;
5305 struct _objc_protocol_method_list *instance_methods;
5306 struct _objc_protocol_method_list *class_methods;
5307 };
5308 */
5309 static bool objc_protocol = false;
5310 if (!objc_protocol) {
5311 Result += "\nstruct _objc_protocol {\n";
5312 Result += "\tstruct _objc_protocol_extension *isa;\n";
5313 Result += "\tchar *protocol_name;\n";
5314 Result += "\tstruct _objc_protocol **protocol_list;\n";
5315 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5316 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5317 Result += "};\n";
5318
5319 objc_protocol = true;
5320 }
5321
5322 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5323 Result += PDecl->getNameAsString();
5324 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5325 "{\n\t0, \"";
5326 Result += PDecl->getNameAsString();
5327 Result += "\", 0, ";
5328 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5329 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5330 Result += PDecl->getNameAsString();
5331 Result += ", ";
5332 }
5333 else
5334 Result += "0, ";
5335 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5336 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5337 Result += PDecl->getNameAsString();
5338 Result += "\n";
5339 }
5340 else
5341 Result += "0\n";
5342 Result += "};\n";
5343
5344 // Mark this protocol as having been generated.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005345 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005346 llvm_unreachable("protocol already synthesized");
5347
5348}
5349
5350void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5351 const ObjCList<ObjCProtocolDecl> &Protocols,
5352 StringRef prefix, StringRef ClassName,
5353 std::string &Result) {
5354 if (Protocols.empty()) return;
5355
5356 for (unsigned i = 0; i != Protocols.size(); i++)
5357 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5358
5359 // Output the top lovel protocol meta-data for the class.
5360 /* struct _objc_protocol_list {
5361 struct _objc_protocol_list *next;
5362 int protocol_count;
5363 struct _objc_protocol *class_protocols[];
5364 }
5365 */
5366 Result += "\nstatic struct {\n";
5367 Result += "\tstruct _objc_protocol_list *next;\n";
5368 Result += "\tint protocol_count;\n";
5369 Result += "\tstruct _objc_protocol *class_protocols[";
5370 Result += utostr(Protocols.size());
5371 Result += "];\n} _OBJC_";
5372 Result += prefix;
5373 Result += "_PROTOCOLS_";
5374 Result += ClassName;
5375 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5376 "{\n\t0, ";
5377 Result += utostr(Protocols.size());
5378 Result += "\n";
5379
5380 Result += "\t,{&_OBJC_PROTOCOL_";
5381 Result += Protocols[0]->getNameAsString();
5382 Result += " \n";
5383
5384 for (unsigned i = 1; i != Protocols.size(); i++) {
5385 Result += "\t ,&_OBJC_PROTOCOL_";
5386 Result += Protocols[i]->getNameAsString();
5387 Result += "\n";
5388 }
5389 Result += "\t }\n};\n";
5390}
5391
5392void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5393 std::string &Result) {
5394 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5395
5396 // Explicitly declared @interface's are already synthesized.
5397 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregor7723fec2011-12-15 20:29:51 +00005398 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005399 // produce correct synthesis as yet.
5400 RewriteObjCInternalStruct(CDecl, Result);
5401 }
5402
5403 // Build _objc_ivar_list metadata for classes ivars if needed
5404 unsigned NumIvars = !IDecl->ivar_empty()
5405 ? IDecl->ivar_size()
5406 : (CDecl ? CDecl->ivar_size() : 0);
5407 if (NumIvars > 0) {
5408 static bool objc_ivar = false;
5409 if (!objc_ivar) {
5410 /* struct _objc_ivar {
5411 char *ivar_name;
5412 char *ivar_type;
5413 int ivar_offset;
5414 };
5415 */
5416 Result += "\nstruct _objc_ivar {\n";
5417 Result += "\tchar *ivar_name;\n";
5418 Result += "\tchar *ivar_type;\n";
5419 Result += "\tint ivar_offset;\n";
5420 Result += "};\n";
5421
5422 objc_ivar = true;
5423 }
5424
5425 /* struct {
5426 int ivar_count;
5427 struct _objc_ivar ivar_list[nIvars];
5428 };
5429 */
5430 Result += "\nstatic struct {\n";
5431 Result += "\tint ivar_count;\n";
5432 Result += "\tstruct _objc_ivar ivar_list[";
5433 Result += utostr(NumIvars);
5434 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5435 Result += IDecl->getNameAsString();
5436 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5437 "{\n\t";
5438 Result += utostr(NumIvars);
5439 Result += "\n";
5440
5441 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5442 SmallVector<ObjCIvarDecl *, 8> IVars;
5443 if (!IDecl->ivar_empty()) {
5444 for (ObjCInterfaceDecl::ivar_iterator
5445 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
5446 IV != IVEnd; ++IV)
5447 IVars.push_back(*IV);
5448 IVI = IDecl->ivar_begin();
5449 IVE = IDecl->ivar_end();
5450 } else {
5451 IVI = CDecl->ivar_begin();
5452 IVE = CDecl->ivar_end();
5453 }
5454 Result += "\t,{{\"";
5455 Result += (*IVI)->getNameAsString();
5456 Result += "\", \"";
5457 std::string TmpString, StrEncoding;
5458 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5459 QuoteDoublequotes(TmpString, StrEncoding);
5460 Result += StrEncoding;
5461 Result += "\", ";
5462 RewriteIvarOffsetComputation(*IVI, Result);
5463 Result += "}\n";
5464 for (++IVI; IVI != IVE; ++IVI) {
5465 Result += "\t ,{\"";
5466 Result += (*IVI)->getNameAsString();
5467 Result += "\", \"";
5468 std::string TmpString, StrEncoding;
5469 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5470 QuoteDoublequotes(TmpString, StrEncoding);
5471 Result += StrEncoding;
5472 Result += "\", ";
5473 RewriteIvarOffsetComputation((*IVI), Result);
5474 Result += "}\n";
5475 }
5476
5477 Result += "\t }\n};\n";
5478 }
5479
5480 // Build _objc_method_list for class's instance methods if needed
5481 SmallVector<ObjCMethodDecl *, 32>
5482 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5483
5484 // If any of our property implementations have associated getters or
5485 // setters, produce metadata for them as well.
5486 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5487 PropEnd = IDecl->propimpl_end();
5488 Prop != PropEnd; ++Prop) {
5489 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5490 continue;
5491 if (!(*Prop)->getPropertyIvarDecl())
5492 continue;
5493 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5494 if (!PD)
5495 continue;
5496 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5497 if (!Getter->isDefined())
5498 InstanceMethods.push_back(Getter);
5499 if (PD->isReadOnly())
5500 continue;
5501 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5502 if (!Setter->isDefined())
5503 InstanceMethods.push_back(Setter);
5504 }
5505 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5506 true, "", IDecl->getName(), Result);
5507
5508 // Build _objc_method_list for class's class methods if needed
5509 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5510 false, "", IDecl->getName(), Result);
5511
5512 // Protocols referenced in class declaration?
5513 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5514 "CLASS", CDecl->getName(), Result);
5515
5516 // Declaration of class/meta-class metadata
5517 /* struct _objc_class {
5518 struct _objc_class *isa; // or const char *root_class_name when metadata
5519 const char *super_class_name;
5520 char *name;
5521 long version;
5522 long info;
5523 long instance_size;
5524 struct _objc_ivar_list *ivars;
5525 struct _objc_method_list *methods;
5526 struct objc_cache *cache;
5527 struct objc_protocol_list *protocols;
5528 const char *ivar_layout;
5529 struct _objc_class_ext *ext;
5530 };
5531 */
5532 static bool objc_class = false;
5533 if (!objc_class) {
5534 Result += "\nstruct _objc_class {\n";
5535 Result += "\tstruct _objc_class *isa;\n";
5536 Result += "\tconst char *super_class_name;\n";
5537 Result += "\tchar *name;\n";
5538 Result += "\tlong version;\n";
5539 Result += "\tlong info;\n";
5540 Result += "\tlong instance_size;\n";
5541 Result += "\tstruct _objc_ivar_list *ivars;\n";
5542 Result += "\tstruct _objc_method_list *methods;\n";
5543 Result += "\tstruct objc_cache *cache;\n";
5544 Result += "\tstruct _objc_protocol_list *protocols;\n";
5545 Result += "\tconst char *ivar_layout;\n";
5546 Result += "\tstruct _objc_class_ext *ext;\n";
5547 Result += "};\n";
5548 objc_class = true;
5549 }
5550
5551 // Meta-class metadata generation.
5552 ObjCInterfaceDecl *RootClass = 0;
5553 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5554 while (SuperClass) {
5555 RootClass = SuperClass;
5556 SuperClass = SuperClass->getSuperClass();
5557 }
5558 SuperClass = CDecl->getSuperClass();
5559
5560 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5561 Result += CDecl->getNameAsString();
5562 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5563 "{\n\t(struct _objc_class *)\"";
5564 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5565 Result += "\"";
5566
5567 if (SuperClass) {
5568 Result += ", \"";
5569 Result += SuperClass->getNameAsString();
5570 Result += "\", \"";
5571 Result += CDecl->getNameAsString();
5572 Result += "\"";
5573 }
5574 else {
5575 Result += ", 0, \"";
5576 Result += CDecl->getNameAsString();
5577 Result += "\"";
5578 }
5579 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5580 // 'info' field is initialized to CLS_META(2) for metaclass
5581 Result += ", 0,2, sizeof(struct _objc_class), 0";
5582 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5583 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5584 Result += IDecl->getNameAsString();
5585 Result += "\n";
5586 }
5587 else
5588 Result += ", 0\n";
5589 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5590 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5591 Result += CDecl->getNameAsString();
5592 Result += ",0,0\n";
5593 }
5594 else
5595 Result += "\t,0,0,0,0\n";
5596 Result += "};\n";
5597
5598 // class metadata generation.
5599 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5600 Result += CDecl->getNameAsString();
5601 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5602 "{\n\t&_OBJC_METACLASS_";
5603 Result += CDecl->getNameAsString();
5604 if (SuperClass) {
5605 Result += ", \"";
5606 Result += SuperClass->getNameAsString();
5607 Result += "\", \"";
5608 Result += CDecl->getNameAsString();
5609 Result += "\"";
5610 }
5611 else {
5612 Result += ", 0, \"";
5613 Result += CDecl->getNameAsString();
5614 Result += "\"";
5615 }
5616 // 'info' field is initialized to CLS_CLASS(1) for class
5617 Result += ", 0,1";
5618 if (!ObjCSynthesizedStructs.count(CDecl))
5619 Result += ",0";
5620 else {
5621 // class has size. Must synthesize its size.
5622 Result += ",sizeof(struct ";
5623 Result += CDecl->getNameAsString();
5624 if (LangOpts.MicrosoftExt)
5625 Result += "_IMPL";
5626 Result += ")";
5627 }
5628 if (NumIvars > 0) {
5629 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5630 Result += CDecl->getNameAsString();
5631 Result += "\n\t";
5632 }
5633 else
5634 Result += ",0";
5635 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5636 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5637 Result += CDecl->getNameAsString();
5638 Result += ", 0\n\t";
5639 }
5640 else
5641 Result += ",0,0";
5642 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5643 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5644 Result += CDecl->getNameAsString();
5645 Result += ", 0,0\n";
5646 }
5647 else
5648 Result += ",0,0,0\n";
5649 Result += "};\n";
5650}
5651
5652void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5653 int ClsDefCount = ClassImplementation.size();
5654 int CatDefCount = CategoryImplementation.size();
5655
5656 // For each implemented class, write out all its meta data.
5657 for (int i = 0; i < ClsDefCount; i++)
5658 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5659
5660 // For each implemented category, write out all its meta data.
5661 for (int i = 0; i < CatDefCount; i++)
5662 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5663
5664 // Write objc_symtab metadata
5665 /*
5666 struct _objc_symtab
5667 {
5668 long sel_ref_cnt;
5669 SEL *refs;
5670 short cls_def_cnt;
5671 short cat_def_cnt;
5672 void *defs[cls_def_cnt + cat_def_cnt];
5673 };
5674 */
5675
5676 Result += "\nstruct _objc_symtab {\n";
5677 Result += "\tlong sel_ref_cnt;\n";
5678 Result += "\tSEL *refs;\n";
5679 Result += "\tshort cls_def_cnt;\n";
5680 Result += "\tshort cat_def_cnt;\n";
5681 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5682 Result += "};\n\n";
5683
5684 Result += "static struct _objc_symtab "
5685 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5686 Result += "\t0, 0, " + utostr(ClsDefCount)
5687 + ", " + utostr(CatDefCount) + "\n";
5688 for (int i = 0; i < ClsDefCount; i++) {
5689 Result += "\t,&_OBJC_CLASS_";
5690 Result += ClassImplementation[i]->getNameAsString();
5691 Result += "\n";
5692 }
5693
5694 for (int i = 0; i < CatDefCount; i++) {
5695 Result += "\t,&_OBJC_CATEGORY_";
5696 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5697 Result += "_";
5698 Result += CategoryImplementation[i]->getNameAsString();
5699 Result += "\n";
5700 }
5701
5702 Result += "};\n\n";
5703
5704 // Write objc_module metadata
5705
5706 /*
5707 struct _objc_module {
5708 long version;
5709 long size;
5710 const char *name;
5711 struct _objc_symtab *symtab;
5712 }
5713 */
5714
5715 Result += "\nstruct _objc_module {\n";
5716 Result += "\tlong version;\n";
5717 Result += "\tlong size;\n";
5718 Result += "\tconst char *name;\n";
5719 Result += "\tstruct _objc_symtab *symtab;\n";
5720 Result += "};\n\n";
5721 Result += "static struct _objc_module "
5722 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5723 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5724 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5725 Result += "};\n\n";
5726
5727 if (LangOpts.MicrosoftExt) {
5728 if (ProtocolExprDecls.size()) {
5729 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5730 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5731 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5732 E = ProtocolExprDecls.end(); I != E; ++I) {
5733 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5734 Result += (*I)->getNameAsString();
5735 Result += " = &_OBJC_PROTOCOL_";
5736 Result += (*I)->getNameAsString();
5737 Result += ";\n";
5738 }
5739 Result += "#pragma data_seg(pop)\n\n";
5740 }
5741 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5742 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5743 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5744 Result += "&_OBJC_MODULES;\n";
5745 Result += "#pragma data_seg(pop)\n\n";
5746 }
5747}
5748
5749/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5750/// implementation.
5751void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5752 std::string &Result) {
5753 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5754 // Find category declaration for this implementation.
5755 ObjCCategoryDecl *CDecl;
5756 for (CDecl = ClassDecl->getCategoryList(); CDecl;
5757 CDecl = CDecl->getNextClassCategory())
5758 if (CDecl->getIdentifier() == IDecl->getIdentifier())
5759 break;
5760
5761 std::string FullCategoryName = ClassDecl->getNameAsString();
5762 FullCategoryName += '_';
5763 FullCategoryName += IDecl->getNameAsString();
5764
5765 // Build _objc_method_list for class's instance methods if needed
5766 SmallVector<ObjCMethodDecl *, 32>
5767 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5768
5769 // If any of our property implementations have associated getters or
5770 // setters, produce metadata for them as well.
5771 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5772 PropEnd = IDecl->propimpl_end();
5773 Prop != PropEnd; ++Prop) {
5774 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5775 continue;
5776 if (!(*Prop)->getPropertyIvarDecl())
5777 continue;
5778 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5779 if (!PD)
5780 continue;
5781 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5782 InstanceMethods.push_back(Getter);
5783 if (PD->isReadOnly())
5784 continue;
5785 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5786 InstanceMethods.push_back(Setter);
5787 }
5788 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5789 true, "CATEGORY_", FullCategoryName.c_str(),
5790 Result);
5791
5792 // Build _objc_method_list for class's class methods if needed
5793 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5794 false, "CATEGORY_", FullCategoryName.c_str(),
5795 Result);
5796
5797 // Protocols referenced in class declaration?
5798 // Null CDecl is case of a category implementation with no category interface
5799 if (CDecl)
5800 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5801 FullCategoryName, Result);
5802 /* struct _objc_category {
5803 char *category_name;
5804 char *class_name;
5805 struct _objc_method_list *instance_methods;
5806 struct _objc_method_list *class_methods;
5807 struct _objc_protocol_list *protocols;
5808 // Objective-C 1.0 extensions
5809 uint32_t size; // sizeof (struct _objc_category)
5810 struct _objc_property_list *instance_properties; // category's own
5811 // @property decl.
5812 };
5813 */
5814
5815 static bool objc_category = false;
5816 if (!objc_category) {
5817 Result += "\nstruct _objc_category {\n";
5818 Result += "\tchar *category_name;\n";
5819 Result += "\tchar *class_name;\n";
5820 Result += "\tstruct _objc_method_list *instance_methods;\n";
5821 Result += "\tstruct _objc_method_list *class_methods;\n";
5822 Result += "\tstruct _objc_protocol_list *protocols;\n";
5823 Result += "\tunsigned int size;\n";
5824 Result += "\tstruct _objc_property_list *instance_properties;\n";
5825 Result += "};\n";
5826 objc_category = true;
5827 }
5828 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5829 Result += FullCategoryName;
5830 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5831 Result += IDecl->getNameAsString();
5832 Result += "\"\n\t, \"";
5833 Result += ClassDecl->getNameAsString();
5834 Result += "\"\n";
5835
5836 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5837 Result += "\t, (struct _objc_method_list *)"
5838 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5839 Result += FullCategoryName;
5840 Result += "\n";
5841 }
5842 else
5843 Result += "\t, 0\n";
5844 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5845 Result += "\t, (struct _objc_method_list *)"
5846 "&_OBJC_CATEGORY_CLASS_METHODS_";
5847 Result += FullCategoryName;
5848 Result += "\n";
5849 }
5850 else
5851 Result += "\t, 0\n";
5852
5853 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5854 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5855 Result += FullCategoryName;
5856 Result += "\n";
5857 }
5858 else
5859 Result += "\t, 0\n";
5860 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5861}
5862
5863// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5864/// class methods.
5865template<typename MethodIterator>
5866void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5867 MethodIterator MethodEnd,
5868 bool IsInstanceMethod,
5869 StringRef prefix,
5870 StringRef ClassName,
5871 std::string &Result) {
5872 if (MethodBegin == MethodEnd) return;
5873
5874 if (!objc_impl_method) {
5875 /* struct _objc_method {
5876 SEL _cmd;
5877 char *method_types;
5878 void *_imp;
5879 }
5880 */
5881 Result += "\nstruct _objc_method {\n";
5882 Result += "\tSEL _cmd;\n";
5883 Result += "\tchar *method_types;\n";
5884 Result += "\tvoid *_imp;\n";
5885 Result += "};\n";
5886
5887 objc_impl_method = true;
5888 }
5889
5890 // Build _objc_method_list for class's methods if needed
5891
5892 /* struct {
5893 struct _objc_method_list *next_method;
5894 int method_count;
5895 struct _objc_method method_list[];
5896 }
5897 */
5898 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5899 Result += "\nstatic struct {\n";
5900 Result += "\tstruct _objc_method_list *next_method;\n";
5901 Result += "\tint method_count;\n";
5902 Result += "\tstruct _objc_method method_list[";
5903 Result += utostr(NumMethods);
5904 Result += "];\n} _OBJC_";
5905 Result += prefix;
5906 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5907 Result += "_METHODS_";
5908 Result += ClassName;
5909 Result += " __attribute__ ((used, section (\"__OBJC, __";
5910 Result += IsInstanceMethod ? "inst" : "cls";
5911 Result += "_meth\")))= ";
5912 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5913
5914 Result += "\t,{{(SEL)\"";
5915 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5916 std::string MethodTypeString;
5917 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5918 Result += "\", \"";
5919 Result += MethodTypeString;
5920 Result += "\", (void *)";
5921 Result += MethodInternalNames[*MethodBegin];
5922 Result += "}\n";
5923 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5924 Result += "\t ,{(SEL)\"";
5925 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5926 std::string MethodTypeString;
5927 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5928 Result += "\", \"";
5929 Result += MethodTypeString;
5930 Result += "\", (void *)";
5931 Result += MethodInternalNames[*MethodBegin];
5932 Result += "}\n";
5933 }
5934 Result += "\t }\n};\n";
5935}
5936
5937Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5938 SourceRange OldRange = IV->getSourceRange();
5939 Expr *BaseExpr = IV->getBase();
5940
5941 // Rewrite the base, but without actually doing replaces.
5942 {
5943 DisableReplaceStmtScope S(*this);
5944 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5945 IV->setBase(BaseExpr);
5946 }
5947
5948 ObjCIvarDecl *D = IV->getDecl();
5949
5950 Expr *Replacement = IV;
5951 if (CurMethodDef) {
5952 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5953 const ObjCInterfaceType *iFaceDecl =
5954 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5955 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5956 // lookup which class implements the instance variable.
5957 ObjCInterfaceDecl *clsDeclared = 0;
5958 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5959 clsDeclared);
5960 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5961
5962 // Synthesize an explicit cast to gain access to the ivar.
5963 std::string RecName = clsDeclared->getIdentifier()->getName();
5964 RecName += "_IMPL";
5965 IdentifierInfo *II = &Context->Idents.get(RecName);
5966 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5967 SourceLocation(), SourceLocation(),
5968 II);
5969 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5970 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5971 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5972 CK_BitCast,
5973 IV->getBase());
5974 // Don't forget the parens to enforce the proper binding.
5975 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5976 OldRange.getEnd(),
5977 castExpr);
5978 if (IV->isFreeIvar() &&
Douglas Gregor60ef3082011-12-15 00:29:59 +00005979 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005980 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5981 IV->getLocation(),
5982 D->getType(),
5983 VK_LValue, OK_Ordinary);
5984 Replacement = ME;
5985 } else {
5986 IV->setBase(PE);
5987 }
5988 }
5989 } else { // we are outside a method.
5990 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5991
5992 // Explicit ivar refs need to have a cast inserted.
5993 // FIXME: consider sharing some of this code with the code above.
5994 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5995 const ObjCInterfaceType *iFaceDecl =
5996 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5997 // lookup which class implements the instance variable.
5998 ObjCInterfaceDecl *clsDeclared = 0;
5999 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6000 clsDeclared);
6001 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6002
6003 // Synthesize an explicit cast to gain access to the ivar.
6004 std::string RecName = clsDeclared->getIdentifier()->getName();
6005 RecName += "_IMPL";
6006 IdentifierInfo *II = &Context->Idents.get(RecName);
6007 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6008 SourceLocation(), SourceLocation(),
6009 II);
6010 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6011 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6012 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6013 CK_BitCast,
6014 IV->getBase());
6015 // Don't forget the parens to enforce the proper binding.
6016 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
6017 IV->getBase()->getLocEnd(), castExpr);
6018 // Cannot delete IV->getBase(), since PE points to it.
6019 // Replace the old base with the cast. This is important when doing
6020 // embedded rewrites. For example, [newInv->_container addObject:0].
6021 IV->setBase(PE);
6022 }
6023 }
6024
6025 ReplaceStmtWithRange(IV, Replacement, OldRange);
6026 return Replacement;
6027}
6028