blob: 35d8dde8eaabb9d8d6fbff4ad2e561fd231a73d9 [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
Eli Friedman39d7c4d2009-05-18 22:50:54 +000014#include "clang/Frontend/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"
Chris Lattner77cd2a02007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000031
Chris Lattner77cd2a02007-10-11 00:43:27 +000032namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000034 enum {
35 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
36 block, ... */
37 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
38 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
39 __block variable */
40 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
41 helpers */
42 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
43 support routines */
44 BLOCK_BYREF_CURRENT_MAX = 256
45 };
46
47 enum {
48 BLOCK_NEEDS_FREE = (1 << 24),
49 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
50 BLOCK_HAS_CXX_OBJ = (1 << 26),
51 BLOCK_IS_GC = (1 << 27),
52 BLOCK_IS_GLOBAL = (1 << 28),
53 BLOCK_HAS_DESCRIPTOR = (1 << 29)
54 };
55
Chris Lattner2c64b7b2007-10-16 21:07:07 +000056 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000057 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000058 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000059 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000060 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000061
Chris Lattner01c57482007-10-17 22:35:30 +000062 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000063 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000064 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000065 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000066 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000067 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000068
Ted Kremeneka526c5c2008-01-07 19:49:32 +000069 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
70 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
71 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000072 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000073 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
74 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000075 llvm::SmallVector<Stmt *, 32> Stmts;
76 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000077 // Remember all the @protocol(<expr>) expressions.
78 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000079
80 llvm::DenseSet<uint64_t> CopyDestroyCache;
81
Steve Naroffd82a9ab2008-03-15 00:55:56 +000082 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000083
Steve Naroffebf2b562007-10-23 23:50:29 +000084 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000085 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000086 FunctionDecl *MsgSendStretFunctionDecl;
87 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000088 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000089 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000090 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000091 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000092 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000093 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000094
Steve Naroffbeaf2992007-11-03 11:27:19 +000095 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000096 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +000098
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000099 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000100 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Steve Naroff874e2322007-11-15 10:28:18 +0000102 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000103 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000104 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000105 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Steve Naroff621edce2009-04-29 16:37:50 +0000107 TypeDecl *ProtocolTypeDecl;
108 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000110 // Needed for header files being rewritten
111 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Steve Naroffa7b402d2008-03-28 22:26:09 +0000113 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +0000114 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000115
116 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000117 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000118
Steve Naroffba92b2e2008-03-27 22:29:16 +0000119 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000120
121 // Block expressions.
122 llvm::SmallVector<BlockExpr *, 32> Blocks;
123 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
124 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Steve Naroff54055232008-10-27 17:20:55 +0000126 // Block related declarations.
127 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000129 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
131
132 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
133
Steve Naroffc77a6362008-12-04 16:24:46 +0000134 // This maps a property to it's assignment statement.
135 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000136 // This maps a property to it's synthesied message expression.
137 // This allows us to rewrite chained getters (e.g. o.a.b.c).
138 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Steve Naroff4c3580e2008-12-04 23:50:32 +0000140 // This maps an original source AST to it's rewritten form. This allows
141 // us to avoid rewriting the same node twice (which is very uncommon).
142 // This is needed to support some of the exotic property rewriting.
143 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000144
Steve Naroff54055232008-10-27 17:20:55 +0000145 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000146 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000147 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Steve Naroffb619d952008-12-09 12:56:34 +0000149 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000151 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000152 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000153 virtual void Initialize(ASTContext &context);
154
Chris Lattnerf04da132007-10-24 17:06:59 +0000155 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000156 virtual void HandleTopLevelDecl(DeclGroupRef D) {
157 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
158 HandleTopLevelSingleDecl(*I);
159 }
160 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000161 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000162 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000163 Diagnostic &D, const LangOptions &LOpts,
164 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000165
166 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000168 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000170 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000171 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000172
Steve Naroff4c3580e2008-12-04 23:50:32 +0000173 if (ReplacingStmt)
174 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000175
Steve Naroffb619d952008-12-09 12:56:34 +0000176 if (DisableReplaceStmt)
177 return; // Used when rewriting the assignment of a property setter.
178
Steve Naroff4c3580e2008-12-04 23:50:32 +0000179 // If replacement succeeded or warning disabled return with no warning.
180 if (!Rewrite.ReplaceStmt(Old, New)) {
181 ReplacedNodes[Old] = New;
182 return;
183 }
184 if (SilenceRewriteMacroWarning)
185 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000186 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
187 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000188 }
Steve Naroffb619d952008-12-09 12:56:34 +0000189
190 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
191 // Measaure the old text.
192 int Size = Rewrite.getRangeSize(SrcRange);
193 if (Size == -1) {
194 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
195 << Old->getSourceRange();
196 return;
197 }
198 // Get the new text.
199 std::string SStr;
200 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000201 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000202 const std::string &Str = S.str();
203
204 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000205 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000206 ReplacedNodes[Old] = New;
207 return;
208 }
209 if (SilenceRewriteMacroWarning)
210 return;
211 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
212 << Old->getSourceRange();
213 }
214
Steve Naroffba92b2e2008-03-27 22:29:16 +0000215 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
216 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000217 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000218 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
219 InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000220 SilenceRewriteMacroWarning)
221 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000223 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
224 }
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Chris Lattneraadaf782008-01-31 19:51:04 +0000226 void RemoveText(SourceLocation Loc, unsigned StrLen) {
227 // If removal succeeded or warning disabled return with no warning.
228 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
229 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000230
Chris Lattneraadaf782008-01-31 19:51:04 +0000231 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
232 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000233
Chris Lattneraadaf782008-01-31 19:51:04 +0000234 void ReplaceText(SourceLocation Start, unsigned OrigLength,
235 const char *NewStr, unsigned NewLength) {
236 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000237 if (!Rewrite.ReplaceText(Start, OrigLength,
238 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 SilenceRewriteMacroWarning)
240 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattneraadaf782008-01-31 19:51:04 +0000242 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
243 }
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattnerf04da132007-10-24 17:06:59 +0000245 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000246 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000247 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000248 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000249 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000250 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
251 ObjCImplementationDecl *IMD,
252 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000253 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000254 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000255 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000256 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
257 ValueDecl *VD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000258 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
259 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
260 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
261 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000262 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000263 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000266 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000267 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000268 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000269 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000270 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000271 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Chris Lattnerf04da132007-10-24 17:06:59 +0000273 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000274 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000275 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Steve Naroff8599e7a2008-12-08 16:43:47 +0000277 Stmt *CurrentBody;
278 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Chris Lattnere64b7772007-10-24 16:57:36 +0000280 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000281 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000282 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000283 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000284 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000285 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000286 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000287 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000288 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000289 void WarnAboutReturnGotoStmts(Stmt *S);
290 void HasReturnStmts(Stmt *S, bool &hasReturns);
291 void RewriteTryReturnStmts(Stmt *S);
292 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000293 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000294 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000295 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
296 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
297 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000298 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
299 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000300 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff934f2762007-10-24 22:48:43 +0000301 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000302 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000303 Stmt *RewriteBreakStmt(BreakStmt *S);
304 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000305 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Steve Naroff09b266e2007-10-30 23:14:51 +0000307 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000308 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000309 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000310 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000311 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000312 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000313 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000314 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000315 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Chris Lattnerf04da132007-10-24 17:06:59 +0000317 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000318 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000319 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000321 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000322 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Douglas Gregor653f1b12009-04-23 01:02:12 +0000324 template<typename MethodIterator>
325 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
326 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000327 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000328 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000329 const char *ClassName,
330 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Steve Naroff621edce2009-04-29 16:37:50 +0000332 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
333 const char *prefix,
334 const char *ClassName,
335 std::string &Result);
336 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump1eb44332009-09-09 15:08:12 +0000337 const char *prefix,
Steve Naroff621edce2009-04-29 16:37:50 +0000338 const char *ClassName,
339 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000340 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000341 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000342 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
343 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000344 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000345 void RewriteImplementations();
346 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Steve Naroff54055232008-10-27 17:20:55 +0000348 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000349 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000350 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Steve Naroff54055232008-10-27 17:20:55 +0000352 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
353 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000354
355 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000356 void RewriteBlockCall(CallExpr *Exp);
357 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000358 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000359 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000360 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff54055232008-10-27 17:20:55 +0000361 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
363 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000364 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000365 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000366 const char *funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000367 std::string SynthesizeBlockImpl(BlockExpr *CE,
368 std::string Tag, std::string Desc);
369 std::string SynthesizeBlockDescriptor(std::string DescTag,
370 std::string ImplTag,
371 int i, const char *funcName,
372 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000373 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000374 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000375 const char *FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000376 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Steve Naroff54055232008-10-27 17:20:55 +0000378 void CollectBlockDeclRefInfo(BlockExpr *Exp);
379 void GetBlockCallExprs(Stmt *S);
380 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Steve Naroff54055232008-10-27 17:20:55 +0000382 // We avoid calling Type::isBlockPointerType(), since it operates on the
383 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000384 bool isTopLevelBlockPointerType(QualType T) {
385 return isa<BlockPointerType>(T);
386 }
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Steve Naroff54055232008-10-27 17:20:55 +0000388 // FIXME: This predicate seems like it would be useful to add to ASTContext.
389 bool isObjCType(QualType T) {
390 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
391 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Steve Naroff54055232008-10-27 17:20:55 +0000393 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Steve Naroff54055232008-10-27 17:20:55 +0000395 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
396 OCT == Context->getCanonicalType(Context->getObjCClassType()))
397 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Ted Kremenek6217b802009-07-29 21:53:49 +0000399 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000400 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000401 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000402 return true;
403 }
404 return false;
405 }
406 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000407 void GetExtentOfArgList(const char *Name, const char *&LParen,
408 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000409 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Steve Narofffa15fd92008-10-28 20:29:00 +0000411 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000412 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Steve Naroff621edce2009-04-29 16:37:50 +0000414 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000415 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000416 if (From[i] == '"')
417 To += "\\\"";
418 else
419 To += From[i];
420 }
421 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000422 };
John McCall9d125032010-01-15 18:39:57 +0000423
424 // Helper function: create a CStyleCastExpr with trivial type source info.
425 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
426 CastExpr::CastKind Kind, Expr *E) {
427 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
428 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
429 SourceLocation(), SourceLocation());
430 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000431}
432
Mike Stump1eb44332009-09-09 15:08:12 +0000433void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
434 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000435 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000436 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000437 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000438 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000439 // All the args are checked/rewritten. Don't call twice!
440 RewriteBlockPointerDecl(D);
441 break;
442 }
443 }
444}
445
446void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000447 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000448 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000449 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000450}
451
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000452static bool IsHeaderFile(const std::string &Filename) {
453 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000455 if (DotPos == std::string::npos) {
456 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000457 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000458 }
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000460 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
461 // C header: .h
462 // C++ header: .hh or .H;
463 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000464}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000465
Eli Friedman66d6f042009-05-18 22:20:00 +0000466RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000467 Diagnostic &D, const LangOptions &LOpts,
468 bool silenceMacroWarn)
469 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
470 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000471 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000472 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000473 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000474 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000475 "rewriter doesn't support user-specified control flow semantics "
476 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000477}
478
Eli Friedmanbce831b2009-05-18 22:29:17 +0000479ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
480 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000481 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000482 const LangOptions &LOpts,
483 bool SilenceRewriteMacroWarning) {
484 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000485}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000486
Steve Naroffb29b4272008-04-14 22:03:09 +0000487void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000488 Context = &context;
489 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000490 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000491 MsgSendFunctionDecl = 0;
492 MsgSendSuperFunctionDecl = 0;
493 MsgSendStretFunctionDecl = 0;
494 MsgSendSuperStretFunctionDecl = 0;
495 MsgSendFpretFunctionDecl = 0;
496 GetClassFunctionDecl = 0;
497 GetMetaClassFunctionDecl = 0;
498 SelGetUidFunctionDecl = 0;
499 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000500 ConstantStringClassReference = 0;
501 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000502 CurMethodDef = 0;
503 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000504 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000505 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000506 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000507 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000508 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000509 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000510 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000511 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000512 PropParentMap = 0;
513 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000514 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000515 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000517 // Get the ID and start/end of the main file.
518 MainFileID = SM->getMainFileID();
519 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
520 MainFileStart = MainBuf->getBufferStart();
521 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Chris Lattner2c78b872009-04-14 23:22:57 +0000523 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000525 // declaring objc_selector outside the parameter list removes a silly
526 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000527 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000528 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000529 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000530 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000531 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000532 if (LangOpts.Microsoft) {
533 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000534 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
535 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000536 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000537 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000538 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000539 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
540 Preamble += "typedef struct objc_object Protocol;\n";
541 Preamble += "#define _REWRITER_typedef_Protocol\n";
542 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000543 if (LangOpts.Microsoft) {
544 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
545 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
546 } else
547 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
548 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000549 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000550 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000551 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000552 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000553 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000554 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000555 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000556 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000557 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000558 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000559 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000560 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000561 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000562 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
563 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
564 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
565 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
566 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000567 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000568 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000569 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
570 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
571 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000572 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
573 Preamble += "struct __objcFastEnumerationState {\n\t";
574 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000575 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000576 Preamble += "unsigned long *mutationsPtr;\n\t";
577 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000578 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000579 Preamble += "#define __FASTENUMERATIONSTATE\n";
580 Preamble += "#endif\n";
581 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
582 Preamble += "struct __NSConstantStringImpl {\n";
583 Preamble += " int *isa;\n";
584 Preamble += " int flags;\n";
585 Preamble += " char *str;\n";
586 Preamble += " long length;\n";
587 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000588 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
589 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
590 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000591 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000592 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000593 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
594 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000595 // Blocks preamble.
596 Preamble += "#ifndef BLOCK_IMPL\n";
597 Preamble += "#define BLOCK_IMPL\n";
598 Preamble += "struct __block_impl {\n";
599 Preamble += " void *isa;\n";
600 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000601 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000602 Preamble += " void *FuncPtr;\n";
603 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000604 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000605 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000606 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
607 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
608 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
609 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
610 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000611 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
612 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000613 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
614 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
615 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000616 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000617 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000618 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
619 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000620 Preamble += "#define __attribute__(X)\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000621 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000622 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000623 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000624 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000625 Preamble += "#define __weak\n";
626 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000627}
628
629
Chris Lattnerf04da132007-10-24 17:06:59 +0000630//===----------------------------------------------------------------------===//
631// Top Level Driver Code
632//===----------------------------------------------------------------------===//
633
Chris Lattner682bf922009-03-29 16:50:03 +0000634void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000635 // Two cases: either the decl could be in the main file, or it could be in a
636 // #included file. If the former, rewrite it now. If the later, check to see
637 // if we rewrote the #include/#import.
638 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000639 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000641 // If this is for a builtin, ignore it.
642 if (Loc.isInvalid()) return;
643
Steve Naroffebf2b562007-10-23 23:50:29 +0000644 // Look for built-in declarations that we need to refer during the rewrite.
645 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000646 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000647 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000648 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000649 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000650 ConstantStringClassReference = FVD;
651 return;
652 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000653 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000654 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000655 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000656 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000657 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000658 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000659 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000660 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000661 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000662 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
663 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000664 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
665 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000666 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000667 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000668 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000669 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000670 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000671 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000672}
673
Chris Lattnerf04da132007-10-24 17:06:59 +0000674//===----------------------------------------------------------------------===//
675// Syntactic (non-AST) Rewriting Code
676//===----------------------------------------------------------------------===//
677
Steve Naroffb29b4272008-04-14 22:03:09 +0000678void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000679 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000680 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
681 const char *MainBufStart = MainBuf.first;
682 const char *MainBufEnd = MainBuf.second;
683 size_t ImportLen = strlen("import");
684 size_t IncludeLen = strlen("include");
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000686 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000687 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
688 if (*BufPtr == '#') {
689 if (++BufPtr == MainBufEnd)
690 return;
691 while (*BufPtr == ' ' || *BufPtr == '\t')
692 if (++BufPtr == MainBufEnd)
693 return;
694 if (!strncmp(BufPtr, "import", ImportLen)) {
695 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000696 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000697 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000698 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000699 BufPtr += ImportLen;
700 }
701 }
702 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000703}
704
Steve Naroffb29b4272008-04-14 22:03:09 +0000705void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000706 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
707 const char *MainBufStart = MainBuf.first;
708 const char *MainBufEnd = MainBuf.second;
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Chris Lattnerf04da132007-10-24 17:06:59 +0000710 // Loop over the whole file, looking for tabs.
711 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
712 if (*BufPtr != '\t')
713 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Chris Lattnerf04da132007-10-24 17:06:59 +0000715 // Okay, we found a tab. This tab will turn into at least one character,
716 // but it depends on which 'virtual column' it is in. Compute that now.
717 unsigned VCol = 0;
718 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
719 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
720 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Chris Lattnerf04da132007-10-24 17:06:59 +0000722 // Okay, now that we know the virtual column, we know how many spaces to
723 // insert. We assume 8-character tab-stops.
724 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Chris Lattnerf04da132007-10-24 17:06:59 +0000726 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000727 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
728 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Chris Lattnerf04da132007-10-24 17:06:59 +0000730 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000731 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000732 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000733}
734
Steve Naroffeb0646c2008-12-02 15:48:25 +0000735static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
736 ObjCIvarDecl *OID) {
737 std::string S;
738 S = "((struct ";
739 S += ClassDecl->getIdentifier()->getName();
740 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000741 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000742 return S;
743}
744
Steve Naroffa0876e82008-12-02 17:36:43 +0000745void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
746 ObjCImplementationDecl *IMD,
747 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000748 SourceLocation startLoc = PID->getLocStart();
749 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000750 const char *startBuf = SM->getCharacterData(startLoc);
751 assert((*startBuf == '@') && "bogus @synthesize location");
752 const char *semiBuf = strchr(startBuf, ';');
753 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000754 SourceLocation onePastSemiLoc =
755 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000756
757 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
758 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Steve Naroffeb0646c2008-12-02 15:48:25 +0000760 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000761 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000762 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000763 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000765 if (!OID)
766 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000768 std::string Getr;
769 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
770 Getr += "{ ";
771 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000772 // FIXME: deal with code generation implications for various property
773 // attributes (copy, retain, nonatomic).
Steve Naroff3539cdb2008-12-02 17:54:50 +0000774 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000775 Getr += "return " + getIvarAccessString(ClassDecl, OID);
776 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000777 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000778 if (PD->isReadOnly())
779 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Steve Naroffeb0646c2008-12-02 15:48:25 +0000781 // Generate the 'setter' function.
782 std::string Setr;
783 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000784 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000785 // Synthesize an explicit cast to initialize the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000786 // FIXME: deal with code generation implications for various property
787 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000788 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000789 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000790 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000791 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000792 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffd40910b2008-12-01 20:33:01 +0000793}
Chris Lattner8a12c272007-10-11 18:38:32 +0000794
Steve Naroffb29b4272008-04-14 22:03:09 +0000795void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000796 // Get the start location and compute the semi location.
797 SourceLocation startLoc = ClassDecl->getLocation();
798 const char *startBuf = SM->getCharacterData(startLoc);
799 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Chris Lattnerf04da132007-10-24 17:06:59 +0000801 // Translate to typedef's that forward reference structs with the same name
802 // as the class. As a convenience, we include the original declaration
803 // as a comment.
804 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000805 typedefString += "// @class ";
806 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
807 I != E; ++I) {
808 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
809 typedefString += ForwardDecl->getNameAsString();
810 if (I+1 != E)
811 typedefString += ", ";
812 else
813 typedefString += ";\n";
814 }
815
Chris Lattner67956052009-02-20 18:04:31 +0000816 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
817 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000818 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000819 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000820 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000821 typedefString += "\n";
822 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000823 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000824 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000825 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000826 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000827 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000828 }
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Steve Naroff934f2762007-10-24 22:48:43 +0000830 // Replace the @class with typedefs corresponding to the classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000831 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattneraadaf782008-01-31 19:51:04 +0000832 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000833}
834
Steve Naroffb29b4272008-04-14 22:03:09 +0000835void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000836 // When method is a synthesized one, such as a getter/setter there is
837 // nothing to rewrite.
838 if (Method->isSynthesized())
839 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000840 SourceLocation LocStart = Method->getLocStart();
841 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000842
Chris Lattner30fc9332009-02-04 01:06:56 +0000843 if (SM->getInstantiationLineNumber(LocEnd) >
844 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000845 InsertText(LocStart, "#if 0\n", 6);
846 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000847 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000848 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000849 }
850}
851
Mike Stump1eb44332009-09-09 15:08:12 +0000852void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000853 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Steve Naroff6327e0d2009-01-11 01:06:09 +0000855 ReplaceText(Loc, 0, "// ", 3);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000856 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000857}
858
Steve Naroffb29b4272008-04-14 22:03:09 +0000859void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000860 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000861
Steve Naroff423cb562007-10-30 13:30:57 +0000862 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000863 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000864
865 for (ObjCCategoryDecl::instmeth_iterator
866 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000867 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000868 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000869 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000870 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000871 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000872 RewriteMethodDeclaration(*I);
873
Steve Naroff423cb562007-10-30 13:30:57 +0000874 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000875 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000876}
877
Steve Naroffb29b4272008-04-14 22:03:09 +0000878void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000879 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Steve Naroff752d6ef2007-10-30 16:42:30 +0000881 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Steve Naroff752d6ef2007-10-30 16:42:30 +0000883 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000884 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000885
886 for (ObjCProtocolDecl::instmeth_iterator
887 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000888 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000889 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000890 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000891 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000892 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000893 RewriteMethodDeclaration(*I);
894
Steve Naroff752d6ef2007-10-30 16:42:30 +0000895 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000896 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattneraadaf782008-01-31 19:51:04 +0000897 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000898
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000899 // Must comment out @optional/@required
900 const char *startBuf = SM->getCharacterData(LocStart);
901 const char *endBuf = SM->getCharacterData(LocEnd);
902 for (const char *p = startBuf; p < endBuf; p++) {
903 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
904 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000905 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000906 ReplaceText(OptionalLoc, strlen("@optional"),
907 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000909 }
910 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
911 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000912 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000913 ReplaceText(OptionalLoc, strlen("@required"),
914 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000916 }
917 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000918}
919
Steve Naroffb29b4272008-04-14 22:03:09 +0000920void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000921 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000922 if (LocStart.isInvalid())
923 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000924 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000925 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000926}
927
Mike Stump1eb44332009-09-09 15:08:12 +0000928void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000929 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000930 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000931 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000932 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000933 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000934 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000935 else if (OMD->getResultType()->isFunctionPointerType() ||
936 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000937 // needs special handling, since pointer-to-functions have special
938 // syntax (where a decaration models use).
939 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000940 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +0000941 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000942 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000943 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000944 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +0000945 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Narofff4312dc2008-12-11 19:29:16 +0000946 ResultStr += FPRetType->getResultType().getAsString();
947 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000948 }
949 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000950 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000951 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000953 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000954 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000956 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000957 NameStr += "_I_";
958 else
959 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000961 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000962 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +0000963
964 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000965 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000966 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000967 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000968 }
Mike Stump1eb44332009-09-09 15:08:12 +0000969 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000970 {
971 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000972 int len = selString.size();
973 for (int i = 0; i < len; i++)
974 if (selString[i] == ':')
975 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000976 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000977 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000978 // Remember this name for metadata emission
979 MethodInternalNames[OMD] = NameStr;
980 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000982 // Rewrite arguments
983 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000985 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000986 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000987 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000988 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000989 if (!LangOpts.Microsoft) {
990 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
991 ResultStr += "struct ";
992 }
993 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000994 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000995 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000996 }
997 else
Steve Naroff621edce2009-04-29 16:37:50 +0000998 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001000 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001001 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001002 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001004 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001005 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1006 E = OMD->param_end(); PI != E; ++PI) {
1007 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001008 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001009 if (PDecl->getType()->isObjCQualifiedIdType()) {
1010 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001011 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001012 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001013 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +00001014 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001015 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek6217b802009-07-29 21:53:49 +00001016 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001017 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1018 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001019 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001020 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001021 ResultStr += Name;
1022 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001023 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001024 if (OMD->isVariadic())
1025 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001026 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Steve Naroff76e429d2008-07-16 14:40:40 +00001028 if (FPRetType) {
1029 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Steve Naroff76e429d2008-07-16 14:40:40 +00001031 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001032 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001033 ResultStr += "(";
1034 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1035 if (i) ResultStr += ", ";
1036 std::string ParamStr = FT->getArgType(i).getAsString();
1037 ResultStr += ParamStr;
1038 }
1039 if (FT->isVariadic()) {
1040 if (FT->getNumArgs()) ResultStr += ", ";
1041 ResultStr += "...";
1042 }
1043 ResultStr += ")";
1044 } else {
1045 ResultStr += "()";
1046 }
1047 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001048}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001049void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001050 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1051 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001053 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001054 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001055 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001056 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001058 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001059 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1060 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001061 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001062 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001063 ObjCMethodDecl *OMD = *I;
1064 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001065 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001066 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001067
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001068 const char *startBuf = SM->getCharacterData(LocStart);
1069 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001070 ReplaceText(LocStart, endBuf-startBuf,
1071 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001072 }
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001074 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001075 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1076 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001077 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001078 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001079 ObjCMethodDecl *OMD = *I;
1080 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001081 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001082 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001084 const char *startBuf = SM->getCharacterData(LocStart);
1085 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001086 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump1eb44332009-09-09 15:08:12 +00001087 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001088 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001089 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001090 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001091 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001092 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001093 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001094 }
1095
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001096 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001097 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001098 else
Mike Stump1eb44332009-09-09 15:08:12 +00001099 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001100}
1101
Steve Naroffb29b4272008-04-14 22:03:09 +00001102void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001103 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001104 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001105 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001106 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001107 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001108 ResultStr += "\n";
1109 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001110 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001111 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001112 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001113 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001114 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001115 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001116 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001117 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001118 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001119
1120 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001121 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001122 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001123 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001124 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001125 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001126 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001127 for (ObjCInterfaceDecl::classmeth_iterator
1128 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001129 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001130 RewriteMethodDeclaration(*I);
1131
Steve Naroff2feac5e2007-10-30 03:43:13 +00001132 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001133 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001134}
1135
Steve Naroffb619d952008-12-09 12:56:34 +00001136Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1137 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001138 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1139 // This allows us to reuse all the fun and games in SynthMessageExpr().
1140 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1141 ObjCMessageExpr *MsgExpr;
1142 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1143 llvm::SmallVector<Expr *, 1> ExprVec;
1144 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Steve Naroff8599e7a2008-12-08 16:43:47 +00001146 Stmt *Receiver = PropRefExpr->getBase();
1147 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1148 if (PRE && PropGetters[PRE]) {
1149 // This allows us to handle chain/nested property getters.
1150 Receiver = PropGetters[PRE];
1151 }
Mike Stump1eb44332009-09-09 15:08:12 +00001152 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1153 PDecl->getSetterName(), PDecl->getType(),
1154 PDecl->getSetterMethodDecl(),
1155 SourceLocation(), SourceLocation(),
Steve Naroffc77a6362008-12-04 16:24:46 +00001156 &ExprVec[0], 1);
1157 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Steve Naroffc77a6362008-12-04 16:24:46 +00001159 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001160 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001161 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001162 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1163 // to things that stay around.
1164 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001165 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001166}
1167
Steve Naroffc77a6362008-12-04 16:24:46 +00001168Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001169 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1170 // This allows us to reuse all the fun and games in SynthMessageExpr().
1171 ObjCMessageExpr *MsgExpr;
1172 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Steve Naroff8599e7a2008-12-08 16:43:47 +00001174 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Steve Naroff8599e7a2008-12-08 16:43:47 +00001176 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1177 if (PRE && PropGetters[PRE]) {
1178 // This allows us to handle chain/nested property getters.
1179 Receiver = PropGetters[PRE];
1180 }
Mike Stump1eb44332009-09-09 15:08:12 +00001181 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1182 PDecl->getGetterName(), PDecl->getType(),
1183 PDecl->getGetterMethodDecl(),
1184 SourceLocation(), SourceLocation(),
Steve Naroff15f081d2008-12-03 00:56:33 +00001185 0, 0);
1186
Steve Naroff4c3580e2008-12-04 23:50:32 +00001187 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001188
1189 if (!PropParentMap)
1190 PropParentMap = new ParentMap(CurrentBody);
1191
1192 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1193 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1194 // We stash away the ReplacingStmt since actually doing the
1195 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1196 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001197 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1198 // to things that stay around.
1199 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001200 return PropRefExpr; // return the original...
1201 } else {
1202 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001203 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001204 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1205 // to things that stay around.
1206 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001207 return ReplacingStmt;
1208 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001209}
1210
Mike Stump1eb44332009-09-09 15:08:12 +00001211Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001212 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001213 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001214 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001215 if (CurMethodDef) {
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001216 if (BaseExpr->getType()->isObjCObjectPointerType() &&
1217 isa<DeclRefExpr>(BaseExpr)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001218 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001219 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Narofff0757612008-05-08 17:52:16 +00001220 // lookup which class implements the instance variable.
1221 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001222 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001223 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001224 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Steve Narofff0757612008-05-08 17:52:16 +00001226 // Synthesize an explicit cast to gain access to the ivar.
1227 std::string RecName = clsDeclared->getIdentifier()->getName();
1228 RecName += "_IMPL";
1229 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001230 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001231 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001232 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1233 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001234 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1235 CastExpr::CK_Unknown,
1236 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001237 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001238 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1239 IV->getBase()->getLocEnd(),
1240 castExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001241 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001242 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001243 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1244 IV->getLocation(),
1245 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001246 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001247 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001248 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001249 }
Mike Stump1eb44332009-09-09 15:08:12 +00001250
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001251 ReplaceStmt(IV->getBase(), PE);
1252 // Cannot delete IV->getBase(), since PE points to it.
1253 // Replace the old base with the cast. This is important when doing
1254 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001255 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001256 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001257 }
Steve Naroff84472a82008-04-18 21:55:08 +00001258 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001259 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Steve Naroff9f525972008-05-06 23:20:07 +00001261 // Explicit ivar refs need to have a cast inserted.
1262 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001263 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001264 ObjCInterfaceType *iFaceDecl =
1265 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001266 // lookup which class implements the instance variable.
1267 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001268 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001269 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001270 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Steve Naroff9f525972008-05-06 23:20:07 +00001272 // Synthesize an explicit cast to gain access to the ivar.
1273 std::string RecName = clsDeclared->getIdentifier()->getName();
1274 RecName += "_IMPL";
1275 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001276 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001277 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001278 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1279 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001280 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1281 CastExpr::CK_Unknown,
1282 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001283 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001284 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001285 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001286 ReplaceStmt(IV->getBase(), PE);
1287 // Cannot delete IV->getBase(), since PE points to it.
1288 // Replace the old base with the cast. This is important when doing
1289 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001290 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001291 return IV;
1292 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001293 }
Steve Naroff84472a82008-04-18 21:55:08 +00001294 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001295}
1296
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001297/// SynthCountByEnumWithState - To print:
1298/// ((unsigned int (*)
1299/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001300/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001301/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001302/// "countByEnumeratingWithState:objects:count:"),
1303/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001304/// (id *)items, (unsigned int)16)
1305///
Steve Naroffb29b4272008-04-14 22:03:09 +00001306void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001307 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1308 "id *, unsigned int))(void *)objc_msgSend)";
1309 buf += "\n\t\t";
1310 buf += "((id)l_collection,\n\t\t";
1311 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1312 buf += "\n\t\t";
1313 buf += "&enumState, "
1314 "(id *)items, (unsigned int)16)";
1315}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001316
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001317/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1318/// statement to exit to its outer synthesized loop.
1319///
Steve Naroffb29b4272008-04-14 22:03:09 +00001320Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001321 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1322 return S;
1323 // replace break with goto __break_label
1324 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001326 SourceLocation startLoc = S->getLocStart();
1327 buf = "goto __break_label_";
1328 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001329 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001330
1331 return 0;
1332}
1333
1334/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1335/// statement to continue with its inner synthesized loop.
1336///
Steve Naroffb29b4272008-04-14 22:03:09 +00001337Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001338 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1339 return S;
1340 // replace continue with goto __continue_label
1341 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001342
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001343 SourceLocation startLoc = S->getLocStart();
1344 buf = "goto __continue_label_";
1345 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001346 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001348 return 0;
1349}
1350
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001351/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001352/// It rewrites:
1353/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001354
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001355/// Into:
1356/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001357/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001358/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001359/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001360/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001361/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001362/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001363/// if (limit) {
1364/// unsigned long startMutations = *enumState.mutationsPtr;
1365/// do {
1366/// unsigned long counter = 0;
1367/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001368/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001369/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001370/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001371/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001372/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001373/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001374/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001375/// objects:items count:16]);
1376/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001377/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001378/// }
1379/// else
1380/// elem = nil;
1381/// }
1382///
Steve Naroffb29b4272008-04-14 22:03:09 +00001383Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001384 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001385 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001386 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001387 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001388 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001389 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001390
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001391 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001392 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001393 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001394 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001395 std::string buf;
1396 buf = "\n{\n\t";
1397 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1398 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001399 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001400 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001401 if (ElementType->isObjCQualifiedIdType() ||
1402 ElementType->isObjCQualifiedInterfaceType())
1403 // Simply use 'id' for all qualified types.
1404 elementTypeAsString = "id";
1405 else
1406 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001407 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001408 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001409 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001410 buf += elementName;
1411 buf += ";\n\t";
1412 }
Chris Lattner06767512008-04-08 05:52:18 +00001413 else {
1414 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001415 elementName = DR->getDecl()->getNameAsCString();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001416 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1417 if (VD->getType()->isObjCQualifiedIdType() ||
1418 VD->getType()->isObjCQualifiedInterfaceType())
1419 // Simply use 'id' for all qualified types.
1420 elementTypeAsString = "id";
1421 else
1422 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001423 }
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001425 // struct __objcFastEnumerationState enumState = { 0 };
1426 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1427 // id items[16];
1428 buf += "id items[16];\n\t";
1429 // id l_collection = (id)
1430 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001431 // Find start location of 'collection' the hard way!
1432 const char *startCollectionBuf = startBuf;
1433 startCollectionBuf += 3; // skip 'for'
1434 startCollectionBuf = strchr(startCollectionBuf, '(');
1435 startCollectionBuf++; // skip '('
1436 // find 'in' and skip it.
1437 while (*startCollectionBuf != ' ' ||
1438 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1439 (*(startCollectionBuf+3) != ' ' &&
1440 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1441 startCollectionBuf++;
1442 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001443
1444 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001445 ReplaceText(startLoc, startCollectionBuf - startBuf,
1446 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001447 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001448 SourceLocation rightParenLoc = S->getRParenLoc();
1449 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1450 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001451 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001453 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1454 // objects:items count:16];
1455 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001456 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001457 // ((unsigned int (*)
1458 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001459 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001460 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001461 // "countByEnumeratingWithState:objects:count:"),
1462 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001463 // (id *)items, (unsigned int)16);
1464 buf += "unsigned long limit =\n\t\t";
1465 SynthCountByEnumWithState(buf);
1466 buf += ";\n\t";
1467 /// if (limit) {
1468 /// unsigned long startMutations = *enumState.mutationsPtr;
1469 /// do {
1470 /// unsigned long counter = 0;
1471 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001472 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001473 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001474 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001475 buf += "if (limit) {\n\t";
1476 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1477 buf += "do {\n\t\t";
1478 buf += "unsigned long counter = 0;\n\t\t";
1479 buf += "do {\n\t\t\t";
1480 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1481 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1482 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001483 buf += " = (";
1484 buf += elementTypeAsString;
1485 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001486 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001487 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001489 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001490 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001491 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001492 /// objects:items count:16]);
1493 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001494 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001495 /// }
1496 /// else
1497 /// elem = nil;
1498 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001499 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001500 buf = ";\n\t";
1501 buf += "__continue_label_";
1502 buf += utostr(ObjCBcLabelNo.back());
1503 buf += ": ;";
1504 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001505 buf += "} while (counter < limit);\n\t";
1506 buf += "} while (limit = ";
1507 SynthCountByEnumWithState(buf);
1508 buf += ");\n\t";
1509 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001510 buf += " = ((";
1511 buf += elementTypeAsString;
1512 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001513 buf += "__break_label_";
1514 buf += utostr(ObjCBcLabelNo.back());
1515 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001516 buf += "}\n\t";
1517 buf += "else\n\t\t";
1518 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001519 buf += " = ((";
1520 buf += elementTypeAsString;
1521 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001522 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001523
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001524 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001525 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001526 if (isa<CompoundStmt>(S->getBody())) {
1527 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1528 InsertText(endBodyLoc, buf.c_str(), buf.size());
1529 } else {
1530 /* Need to treat single statements specially. For example:
1531 *
1532 * for (A *a in b) if (stuff()) break;
1533 * for (A *a in b) xxxyy;
1534 *
1535 * The following code simply scans ahead to the semi to find the actual end.
1536 */
1537 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1538 const char *semiBuf = strchr(stmtBuf, ';');
1539 assert(semiBuf && "Can't find ';'");
1540 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1541 InsertText(endBodyLoc, buf.c_str(), buf.size());
1542 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001543 Stmts.pop_back();
1544 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001545 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001546}
1547
Mike Stump1eb44332009-09-09 15:08:12 +00001548/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001549/// This routine rewrites @synchronized(expr) stmt;
1550/// into:
1551/// objc_sync_enter(expr);
1552/// @try stmt @finally { objc_sync_exit(expr); }
1553///
Steve Naroffb29b4272008-04-14 22:03:09 +00001554Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001555 // Get the start location and compute the semi location.
1556 SourceLocation startLoc = S->getLocStart();
1557 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001559 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001560
1561 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001562 buf = "objc_sync_enter((id)";
1563 const char *lparenBuf = startBuf;
1564 while (*lparenBuf != '(') lparenBuf++;
1565 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001566 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1567 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001568 // been rewritten! (which implies the SourceLocation's are invalid).
1569 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001570 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001571 while (*endBuf != ')') endBuf--;
1572 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001573 buf = ");\n";
1574 // declare a new scope with two variables, _stack and _rethrow.
1575 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1576 buf += "int buf[18/*32-bit i386*/];\n";
1577 buf += "char *pointers[4];} _stack;\n";
1578 buf += "id volatile _rethrow = 0;\n";
1579 buf += "objc_exception_try_enter(&_stack);\n";
1580 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001581 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001582 startLoc = S->getSynchBody()->getLocEnd();
1583 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Steve Naroffc7089f12008-08-19 13:04:19 +00001585 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001586 SourceLocation lastCurlyLoc = startLoc;
1587 buf = "}\nelse {\n";
1588 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001589 buf += "}\n";
1590 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001591 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001592
1593 std::string syncBuf;
1594 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001595 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1596 CastExpr::CK_Unknown,
1597 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001598 std::string syncExprBufS;
1599 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001600 syncExpr->printPretty(syncExprBuf, *Context, 0,
1601 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001602 syncBuf += syncExprBuf.str();
1603 syncBuf += ");";
1604
1605 buf += syncBuf;
1606 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001607 buf += "}\n";
1608 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Chris Lattneraadaf782008-01-31 19:51:04 +00001610 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffb85e77a2009-12-05 21:43:12 +00001611
1612 bool hasReturns = false;
1613 HasReturnStmts(S->getSynchBody(), hasReturns);
1614 if (hasReturns)
1615 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1616
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001617 return 0;
1618}
1619
Steve Naroffb85e77a2009-12-05 21:43:12 +00001620void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1621{
Steve Naroff8c565152008-12-05 17:03:39 +00001622 // Perform a bottom up traversal of all children.
1623 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1624 CI != E; ++CI)
1625 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001626 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001627
Steve Naroffb85e77a2009-12-05 21:43:12 +00001628 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001629 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001630 TryFinallyContainsReturnDiag);
1631 }
1632 return;
1633}
1634
Steve Naroffb85e77a2009-12-05 21:43:12 +00001635void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1636{
1637 // Perform a bottom up traversal of all children.
1638 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1639 CI != E; ++CI)
1640 if (*CI)
1641 HasReturnStmts(*CI, hasReturns);
1642
1643 if (isa<ReturnStmt>(S))
1644 hasReturns = true;
1645 return;
1646}
1647
1648void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1649 // Perform a bottom up traversal of all children.
1650 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1651 CI != E; ++CI)
1652 if (*CI) {
1653 RewriteTryReturnStmts(*CI);
1654 }
1655 if (isa<ReturnStmt>(S)) {
1656 SourceLocation startLoc = S->getLocStart();
1657 const char *startBuf = SM->getCharacterData(startLoc);
1658
1659 const char *semiBuf = strchr(startBuf, ';');
1660 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1661 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1662
1663 std::string buf;
1664 buf = "{ objc_exception_try_exit(&_stack); return";
1665
1666 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1667 InsertText(onePastSemiLoc, "}", 1);
1668 }
1669 return;
1670}
1671
1672void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1673 // Perform a bottom up traversal of all children.
1674 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1675 CI != E; ++CI)
1676 if (*CI) {
1677 RewriteSyncReturnStmts(*CI, syncExitBuf);
1678 }
1679 if (isa<ReturnStmt>(S)) {
1680 SourceLocation startLoc = S->getLocStart();
1681 const char *startBuf = SM->getCharacterData(startLoc);
1682
1683 const char *semiBuf = strchr(startBuf, ';');
1684 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1685 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1686
1687 std::string buf;
1688 buf = "{ objc_exception_try_exit(&_stack);";
1689 buf += syncExitBuf;
1690 buf += " return";
1691
1692 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1693 InsertText(onePastSemiLoc, "}", 1);
1694 }
1695 return;
1696}
1697
Steve Naroffb29b4272008-04-14 22:03:09 +00001698Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001699 // Get the start location and compute the semi location.
1700 SourceLocation startLoc = S->getLocStart();
1701 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Steve Naroff75730982007-11-07 04:08:17 +00001703 assert((*startBuf == '@') && "bogus @try location");
1704
1705 std::string buf;
1706 // declare a new scope with two variables, _stack and _rethrow.
1707 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1708 buf += "int buf[18/*32-bit i386*/];\n";
1709 buf += "char *pointers[4];} _stack;\n";
1710 buf += "id volatile _rethrow = 0;\n";
1711 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001712 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001713
Chris Lattneraadaf782008-01-31 19:51:04 +00001714 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Steve Naroff75730982007-11-07 04:08:17 +00001716 startLoc = S->getTryBody()->getLocEnd();
1717 startBuf = SM->getCharacterData(startLoc);
1718
1719 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Steve Naroff75730982007-11-07 04:08:17 +00001721 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001722 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1723 if (catchList) {
1724 startLoc = startLoc.getFileLocWithOffset(1);
1725 buf = " /* @catch begin */ else {\n";
1726 buf += " id _caught = objc_exception_extract(&_stack);\n";
1727 buf += " objc_exception_try_enter (&_stack);\n";
1728 buf += " if (_setjmp(_stack.buf))\n";
1729 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1730 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Steve Naroffc9ba1722008-07-16 15:31:30 +00001732 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001733 } else { /* no catch list */
1734 buf = "}\nelse {\n";
1735 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1736 buf += "}";
1737 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001738 }
Steve Naroff75730982007-11-07 04:08:17 +00001739 bool sawIdTypedCatch = false;
1740 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001741 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001742 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001743
Mike Stump1eb44332009-09-09 15:08:12 +00001744 if (catchList == S->getCatchStmts())
Steve Naroff75730982007-11-07 04:08:17 +00001745 buf = "if ("; // we are generating code for the first catch clause
1746 else
1747 buf = "else if (";
1748 startLoc = catchList->getLocStart();
1749 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Steve Naroff75730982007-11-07 04:08:17 +00001751 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001752
Steve Naroff75730982007-11-07 04:08:17 +00001753 const char *lParenLoc = strchr(startBuf, '(');
1754
Steve Naroffbe4b3332008-02-01 22:08:12 +00001755 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001756 // Now rewrite the body...
1757 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001758 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1759 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001760 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1761 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001762 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Steve Naroffe12e6922008-02-01 20:02:07 +00001764 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001765 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001766 } else if (catchDecl) {
1767 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001768 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001769 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001770 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001771 sawIdTypedCatch = true;
Fariborz Jahanian66867c52010-01-12 01:22:23 +00001772 } else if (t->isObjCObjectPointerType()) {
1773 QualType InterfaceTy = t->getPointeeType();
1774 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1775 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroff75730982007-11-07 04:08:17 +00001776 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001777 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001778 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001779 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001780 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001781 }
1782 }
1783 // Now rewrite the body...
1784 lastCatchBody = catchList->getCatchBody();
1785 SourceLocation rParenLoc = catchList->getRParenLoc();
1786 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1787 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1788 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1789 assert((*rParenBuf == ')') && "bogus @catch paren location");
1790 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Steve Naroff75730982007-11-07 04:08:17 +00001792 buf = " = _caught;";
Mike Stump1eb44332009-09-09 15:08:12 +00001793 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001794 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001795 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001796 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001797 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001798 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001799 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001800 catchList = catchList->getNextCatchStmt();
1801 }
1802 // Complete the catch list...
1803 if (lastCatchBody) {
1804 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001805 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1806 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Steve Naroff378f47a2008-09-11 15:29:03 +00001808 // Insert the last (implicit) else clause *before* the right curly brace.
1809 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1810 buf = "} /* last catch end */\n";
1811 buf += "else {\n";
1812 buf += " _rethrow = _caught;\n";
1813 buf += " objc_exception_try_exit(&_stack);\n";
1814 buf += "} } /* @catch end */\n";
1815 if (!S->getFinallyStmt())
1816 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001817 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Steve Naroff75730982007-11-07 04:08:17 +00001819 // Set lastCurlyLoc
1820 lastCurlyLoc = lastCatchBody->getLocEnd();
1821 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001822 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001823 startLoc = finalStmt->getLocStart();
1824 startBuf = SM->getCharacterData(startLoc);
1825 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Steve Naroff75730982007-11-07 04:08:17 +00001827 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001828 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Steve Naroff75730982007-11-07 04:08:17 +00001830 Stmt *body = finalStmt->getFinallyBody();
1831 SourceLocation startLoc = body->getLocStart();
1832 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001833 assert(*SM->getCharacterData(startLoc) == '{' &&
1834 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001835 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001836 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Steve Naroff75730982007-11-07 04:08:17 +00001838 startLoc = startLoc.getFileLocWithOffset(1);
1839 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001840 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001841 endLoc = endLoc.getFileLocWithOffset(-1);
1842 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001843 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Steve Naroff75730982007-11-07 04:08:17 +00001845 // Set lastCurlyLoc
1846 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001847
Steve Naroff8c565152008-12-05 17:03:39 +00001848 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001849 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001850 } else { /* no finally clause - make sure we synthesize an implicit one */
1851 buf = "{ /* implicit finally clause */\n";
1852 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1853 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1854 buf += "}";
1855 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffb85e77a2009-12-05 21:43:12 +00001856
1857 // Now check for any return/continue/go statements within the @try.
1858 // The implicit finally clause won't called if the @try contains any
1859 // jump statements.
1860 bool hasReturns = false;
1861 HasReturnStmts(S->getTryBody(), hasReturns);
1862 if (hasReturns)
1863 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001864 }
1865 // Now emit the final closing curly brace...
1866 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1867 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001868 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001869 return 0;
1870}
1871
Steve Naroffb29b4272008-04-14 22:03:09 +00001872Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001873 return 0;
1874}
1875
Steve Naroffb29b4272008-04-14 22:03:09 +00001876Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001877 return 0;
1878}
1879
Mike Stump1eb44332009-09-09 15:08:12 +00001880// This can't be done with ReplaceStmt(S, ThrowExpr), since
1881// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001882// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001883Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001884 // Get the start location and compute the semi location.
1885 SourceLocation startLoc = S->getLocStart();
1886 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001887
Steve Naroff2bd03922007-11-07 15:32:26 +00001888 assert((*startBuf == '@') && "bogus @throw location");
1889
1890 std::string buf;
1891 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001892 if (S->getThrowExpr())
1893 buf = "objc_exception_throw(";
1894 else // add an implicit argument
1895 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001897 // handle "@ throw" correctly.
1898 const char *wBuf = strchr(startBuf, 'w');
1899 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1900 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Steve Naroff2bd03922007-11-07 15:32:26 +00001902 const char *semiBuf = strchr(startBuf, ';');
1903 assert((*semiBuf == ';') && "@throw: can't find ';'");
1904 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1905 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001906 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001907 return 0;
1908}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001909
Steve Naroffb29b4272008-04-14 22:03:09 +00001910Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001911 // Create a new string expression.
1912 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001913 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001914 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001915 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1916 StrEncoding.length(), false,StrType,
1917 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001918 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Chris Lattner07506182007-11-30 22:53:43 +00001920 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001921 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001922 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001923}
1924
Steve Naroffb29b4272008-04-14 22:03:09 +00001925Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001926 if (!SelGetUidFunctionDecl)
1927 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001928 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1929 // Create a call to sel_registerName("selName").
1930 llvm::SmallVector<Expr*, 8> SelExprs;
1931 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001932 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001933 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001934 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001935 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001936 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1937 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001938 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001939 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001940 return SelExp;
1941}
1942
Steve Naroffb29b4272008-04-14 22:03:09 +00001943CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001944 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001945 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001946 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Steve Naroffebf2b562007-10-23 23:50:29 +00001948 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001949 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Steve Naroffebf2b562007-10-23 23:50:29 +00001951 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001952 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump1eb44332009-09-09 15:08:12 +00001953 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001954 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00001955 DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001956 /*isLvalue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001957
John McCall183700f2009-09-21 23:43:11 +00001958 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Ted Kremenek668bf912009-02-09 20:51:47 +00001960 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1961 SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001962}
1963
Steve Naroffd5255f52007-11-01 13:24:47 +00001964static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1965 const char *&startRef, const char *&endRef) {
1966 while (startBuf < endBuf) {
1967 if (*startBuf == '<')
1968 startRef = startBuf; // mark the start.
1969 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001970 if (startRef && *startRef == '<') {
1971 endRef = startBuf; // mark the end.
1972 return true;
1973 }
1974 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001975 }
1976 startBuf++;
1977 }
1978 return false;
1979}
1980
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001981static void scanToNextArgument(const char *&argRef) {
1982 int angle = 0;
1983 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1984 if (*argRef == '<')
1985 angle++;
1986 else if (*argRef == '>')
1987 angle--;
1988 argRef++;
1989 }
1990 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1991}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001992
Steve Naroffb29b4272008-04-14 22:03:09 +00001993bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001994 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroffd5255f52007-11-01 13:24:47 +00001995}
1996
Steve Naroff4f95b752008-07-29 18:15:38 +00001997void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1998 QualType Type = E->getType();
1999 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002000 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Steve Naroffcda658e2008-11-19 21:15:47 +00002002 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2003 Loc = ECE->getLParenLoc();
2004 EndLoc = ECE->getRParenLoc();
2005 } else {
2006 Loc = E->getLocStart();
2007 EndLoc = E->getLocEnd();
2008 }
2009 // This will defend against trying to rewrite synthesized expressions.
2010 if (Loc.isInvalid() || EndLoc.isInvalid())
2011 return;
2012
Steve Naroff4f95b752008-07-29 18:15:38 +00002013 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002014 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002015 const char *startRef = 0, *endRef = 0;
2016 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2017 // Get the locations of the startRef, endRef.
2018 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2019 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2020 // Comment out the protocol references.
2021 InsertText(LessLoc, "/*", 2);
2022 InsertText(GreaterLoc, "*/", 2);
2023 }
2024 }
2025}
2026
Steve Naroffb29b4272008-04-14 22:03:09 +00002027void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002028 SourceLocation Loc;
2029 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002030 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002031 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2032 Loc = VD->getLocation();
2033 Type = VD->getType();
2034 }
2035 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2036 Loc = FD->getLocation();
2037 // Check for ObjC 'id' and class types that have been adorned with protocol
2038 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002039 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002040 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002041 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002042 if (!proto)
2043 return;
2044 Type = proto->getResultType();
2045 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002046 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2047 Loc = FD->getLocation();
2048 Type = FD->getType();
2049 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002050 else
2051 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002053 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002054 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Steve Naroffd5255f52007-11-01 13:24:47 +00002056 const char *endBuf = SM->getCharacterData(Loc);
2057 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002058 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002059 startBuf--; // scan backward (from the decl location) for return type.
2060 const char *startRef = 0, *endRef = 0;
2061 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2062 // Get the locations of the startRef, endRef.
2063 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2064 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2065 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002066 InsertText(LessLoc, "/*", 2);
2067 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00002068 }
2069 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002070 if (!proto)
2071 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002072 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002073 const char *startBuf = SM->getCharacterData(Loc);
2074 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002075 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2076 if (needToScanForQualifiers(proto->getArgType(i))) {
2077 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Steve Naroffd5255f52007-11-01 13:24:47 +00002079 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002080 // scan forward (from the decl location) for argument types.
2081 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002082 const char *startRef = 0, *endRef = 0;
2083 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2084 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002085 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002086 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002087 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002088 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002089 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002090 InsertText(LessLoc, "/*", 2);
2091 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00002092 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002093 startBuf = ++endBuf;
2094 }
2095 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002096 // If the function name is derived from a macro expansion, then the
2097 // argument buffer will not follow the name. Need to speak with Chris.
2098 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002099 startBuf++; // scan forward (from the decl location) for argument types.
2100 startBuf++;
2101 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002102 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002103}
2104
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002105// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002106void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002107 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2108 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002109 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002110 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002111 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002112 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002113 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002114 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002115 SelGetUidIdent, getFuncType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002116 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002117}
2118
Steve Naroffb29b4272008-04-14 22:03:09 +00002119void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002120 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002121 if (FD->getIdentifier() &&
2122 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002123 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002124 return;
2125 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002126 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002127}
2128
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002129void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2130 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2131 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2132 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2133 if (!proto)
2134 return;
2135 QualType Type = proto->getResultType();
2136 std::string FdStr = Type.getAsString();
2137 FdStr += " ";
2138 FdStr += FD->getNameAsCString();
2139 FdStr += "(";
2140 unsigned numArgs = proto->getNumArgs();
2141 for (unsigned i = 0; i < numArgs; i++) {
2142 QualType ArgType = proto->getArgType(i);
2143 FdStr += ArgType.getAsString();
2144
2145 if (i+1 < numArgs)
2146 FdStr += ", ";
2147 }
2148 FdStr += ");\n";
2149 InsertText(FunLocStart, FdStr.c_str(), FdStr.size());
2150 CurFunctionDeclToDeclareForBlock = 0;
2151}
2152
Steve Naroffc0a123c2008-03-11 17:37:02 +00002153// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002154void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002155 if (SuperContructorFunctionDecl)
2156 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002157 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002158 llvm::SmallVector<QualType, 16> ArgTys;
2159 QualType argT = Context->getObjCIdType();
2160 assert(!argT.isNull() && "Can't find 'id' type");
2161 ArgTys.push_back(argT);
2162 ArgTys.push_back(argT);
2163 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2164 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002165 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002166 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002167 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002168 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002169 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002170}
2171
Steve Naroff09b266e2007-10-30 23:14:51 +00002172// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002173void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002174 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2175 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002176 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002177 assert(!argT.isNull() && "Can't find 'id' type");
2178 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002179 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002180 assert(!argT.isNull() && "Can't find 'SEL' type");
2181 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002182 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002183 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002184 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002185 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002186 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002187 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002188 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002189}
2190
Steve Naroff874e2322007-11-15 10:28:18 +00002191// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002192void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002193 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2194 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002195 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002196 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002197 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002198 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2199 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2200 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002201 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002202 assert(!argT.isNull() && "Can't find 'SEL' type");
2203 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002204 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002205 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002206 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002207 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002208 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002209 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002210 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002211}
2212
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002213// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002214void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002215 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2216 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002217 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002218 assert(!argT.isNull() && "Can't find 'id' type");
2219 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002220 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002221 assert(!argT.isNull() && "Can't find 'SEL' type");
2222 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002223 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002224 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002225 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002226 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002227 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002228 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002229 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002230}
2231
Mike Stump1eb44332009-09-09 15:08:12 +00002232// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002233// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002234void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002235 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002236 &Context->Idents.get("objc_msgSendSuper_stret");
2237 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002238 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002239 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002240 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002241 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2242 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2243 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002244 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002245 assert(!argT.isNull() && "Can't find 'SEL' type");
2246 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002247 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002248 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002249 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002250 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002251 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002252 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002253 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002254}
2255
Steve Naroff1284db82008-05-08 22:02:18 +00002256// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002257void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002258 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2259 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002260 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002261 assert(!argT.isNull() && "Can't find 'id' type");
2262 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002263 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002264 assert(!argT.isNull() && "Can't find 'SEL' type");
2265 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002266 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002267 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002268 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002269 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002270 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002271 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002272 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002273}
2274
Steve Naroff09b266e2007-10-30 23:14:51 +00002275// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002276void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002277 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2278 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002279 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002280 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002281 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002282 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002283 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002284 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002285 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002286 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002287}
2288
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002289// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002290void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002291 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2292 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002293 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002294 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002295 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002296 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002297 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002298 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002299 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002300 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002301}
2302
Steve Naroffb29b4272008-04-14 22:03:09 +00002303Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002304 QualType strType = getConstantStringStructType();
2305
2306 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002307
2308 std::string tmpName = InFileName;
2309 unsigned i;
2310 for (i=0; i < tmpName.length(); i++) {
2311 char c = tmpName.at(i);
2312 // replace any non alphanumeric characters with '_'.
2313 if (!isalpha(c) && (c < '0' || c > '9'))
2314 tmpName[i] = '_';
2315 }
2316 S += tmpName;
2317 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002318 S += utostr(NumObjCStringLiterals++);
2319
Steve Naroffba92b2e2008-03-27 22:29:16 +00002320 Preamble += "static __NSConstantStringImpl " + S;
2321 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2322 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002323 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002324 std::string prettyBufS;
2325 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002326 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2327 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002328 Preamble += prettyBuf.str();
2329 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002330 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002331
2332 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2333 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002334 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002335 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2336 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002337 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002338 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002339 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002340 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2341 CastExpr::CK_Unknown, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002342 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002343 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002344 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002345}
2346
Steve Naroffb29b4272008-04-14 22:03:09 +00002347ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002348 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002349 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002350
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002351 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002352 const ObjCObjectPointerType *OPT =
John McCall183700f2009-09-21 23:43:11 +00002353 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00002354 assert(OPT);
2355 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002356 return IT->getDecl();
2357 }
2358 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002359}
2360
2361// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002362QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002363 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002364 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002365 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002366 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002367 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002368
Steve Naroff874e2322007-11-15 10:28:18 +00002369 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002370 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002371 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002372 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002373
Steve Naroff874e2322007-11-15 10:28:18 +00002374 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002375 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002376 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2377 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002378 FieldTypes[i], 0,
2379 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002380 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002381 }
Mike Stump1eb44332009-09-09 15:08:12 +00002382
Douglas Gregor44b43212008-12-11 16:49:14 +00002383 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002384 }
2385 return Context->getTagDeclType(SuperStructDecl);
2386}
2387
Steve Naroffb29b4272008-04-14 22:03:09 +00002388QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002389 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002390 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002391 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002392 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002393 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002394
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002395 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002396 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002397 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002398 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002399 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002400 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002401 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002402 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002403
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002404 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002405 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002406 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2407 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002408 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002409 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002410 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002411 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002412 }
2413
2414 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002415 }
2416 return Context->getTagDeclType(ConstantStringDecl);
2417}
2418
Steve Naroffb29b4272008-04-14 22:03:09 +00002419Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002420 if (!SelGetUidFunctionDecl)
2421 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002422 if (!MsgSendFunctionDecl)
2423 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002424 if (!MsgSendSuperFunctionDecl)
2425 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002426 if (!MsgSendStretFunctionDecl)
2427 SynthMsgSendStretFunctionDecl();
2428 if (!MsgSendSuperStretFunctionDecl)
2429 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002430 if (!MsgSendFpretFunctionDecl)
2431 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002432 if (!GetClassFunctionDecl)
2433 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002434 if (!GetMetaClassFunctionDecl)
2435 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002436
Steve Naroff874e2322007-11-15 10:28:18 +00002437 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002438 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2439 // May need to use objc_msgSend_stret() as well.
2440 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002441 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2442 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002443 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002444 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002445 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002446 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002447 }
Mike Stump1eb44332009-09-09 15:08:12 +00002448
Steve Naroff934f2762007-10-24 22:48:43 +00002449 // Synthesize a call to objc_msgSend().
2450 llvm::SmallVector<Expr*, 8> MsgExprs;
2451 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump1eb44332009-09-09 15:08:12 +00002452
Steve Naroff934f2762007-10-24 22:48:43 +00002453 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2454 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002455 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2456 // the 'super' idiom within a class method.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00002457 if (clsName->getName() == "super") {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002458 MsgSendFlavor = MsgSendSuperFunctionDecl;
2459 if (MsgSendStretFlavor)
2460 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2461 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002462
2463 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002464 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002465
2466 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002467
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002468 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002469 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002470 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2471 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002472 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff621edce2009-04-29 16:37:50 +00002473 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002474 SourceLocation()))
2475 ); // set the 'receiver'.
Steve Naroff621edce2009-04-29 16:37:50 +00002476
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002477 llvm::SmallVector<Expr*, 8> ClsExprs;
2478 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002479 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002480 SuperDecl->getIdentifier()->getNameStart(),
2481 SuperDecl->getIdentifier()->getLength(),
2482 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002483 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002484 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002485 ClsExprs.size());
2486 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002487 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall9d125032010-01-15 18:39:57 +00002488 NoTypeInfoCStyleCastExpr(Context,
2489 Context->getObjCIdType(),
2490 CastExpr::CK_Unknown, Cls));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002491 // struct objc_super
2492 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002493 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002494
Steve Naroff23f41272008-03-11 18:14:26 +00002495 if (LangOpts.Microsoft) {
2496 SynthSuperContructorFunctionDecl();
2497 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002498 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002499 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002500 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002501 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002502 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002503 // The code for super is a little tricky to prevent collision with
2504 // the structure definition in the header. The rewriter has it's own
2505 // internal definition (__rw_objc_super) that is uses. This is why
2506 // we need the cast below. For example:
2507 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2508 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002509 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002510 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002511 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002512 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2513 Context->getPointerType(superType),
2514 CastExpr::CK_Unknown, SuperRep);
Mike Stump1eb44332009-09-09 15:08:12 +00002515 } else {
Steve Naroff23f41272008-03-11 18:14:26 +00002516 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002517 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2518 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002519 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002520 TypeSourceInfo *superTInfo
2521 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002522 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2523 superType, ILE, false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002524 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002525 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002526 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002527 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002528 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002529 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002530 } else {
2531 llvm::SmallVector<Expr*, 8> ClsExprs;
2532 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002533 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002534 clsName->getNameStart(),
Chris Lattner2085fd62009-02-18 06:40:38 +00002535 clsName->getLength(),
2536 false, argType,
2537 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002538 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002539 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002540 ClsExprs.size());
2541 MsgExprs.push_back(Cls);
2542 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002543 } else { // instance message.
2544 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002545
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002546 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002547 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002548 if (MsgSendStretFlavor)
2549 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002550 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002551
Steve Naroff874e2322007-11-15 10:28:18 +00002552 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002553
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002554 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002555 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2556 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002557 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002558 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002559 SourceLocation()))
2560 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002561
Steve Naroff874e2322007-11-15 10:28:18 +00002562 llvm::SmallVector<Expr*, 8> ClsExprs;
2563 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002564 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002565 SuperDecl->getIdentifier()->getNameStart(),
2566 SuperDecl->getIdentifier()->getLength(),
2567 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002568 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002569 &ClsExprs[0],
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002570 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002571 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002572 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002573 // set 'super class', using objc_getClass().
John McCall9d125032010-01-15 18:39:57 +00002574 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2575 CastExpr::CK_Unknown, Cls));
Steve Naroff874e2322007-11-15 10:28:18 +00002576 // struct objc_super
2577 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002578 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002579
Steve Naroffc0a123c2008-03-11 17:37:02 +00002580 if (LangOpts.Microsoft) {
2581 SynthSuperContructorFunctionDecl();
2582 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002583 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002584 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002585 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002586 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002587 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002588 // The code for super is a little tricky to prevent collision with
2589 // the structure definition in the header. The rewriter has it's own
2590 // internal definition (__rw_objc_super) that is uses. This is why
2591 // we need the cast below. For example:
2592 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2593 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002594 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002595 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002596 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002597 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2598 Context->getPointerType(superType),
2599 CastExpr::CK_Unknown, SuperRep);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002600 } else {
2601 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002602 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2603 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002604 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002605 TypeSourceInfo *superTInfo
2606 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002607 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2608 superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002609 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002610 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002611 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002612 // Remove all type-casts because it may contain objc-style types; e.g.
2613 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002614 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002615 recExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002616 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2617 CastExpr::CK_Unknown, recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +00002618 MsgExprs.push_back(recExpr);
2619 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002620 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002621 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002622 llvm::SmallVector<Expr*, 8> SelExprs;
2623 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002624 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002625 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002626 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002627 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002628 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2629 &SelExprs[0], SelExprs.size());
2630 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002631
Steve Naroff934f2762007-10-24 22:48:43 +00002632 // Now push any user supplied arguments.
2633 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002634 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002635 // Make all implicit casts explicit...ICE comes in handy:-)
2636 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2637 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002638 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002639 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002640 : ICE->getType();
John McCall9d125032010-01-15 18:39:57 +00002641 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2642 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002643 }
2644 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002645 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002646 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002647 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002648 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002649 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2650 CastExpr::CK_Unknown, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002651 }
Mike Stump1eb44332009-09-09 15:08:12 +00002652 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002653 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002654 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2655 // out the argument in the original expression (since we aren't deleting
2656 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2657 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002658 }
Steve Naroffab972d32007-11-04 22:37:50 +00002659 // Generate the funky cast.
2660 CastExpr *cast;
2661 llvm::SmallVector<QualType, 8> ArgTypes;
2662 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002663
Steve Naroffab972d32007-11-04 22:37:50 +00002664 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002665 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2666 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2667 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002668 ArgTypes.push_back(Context->getObjCIdType());
2669 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002670 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002671 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002672 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2673 E = OMD->param_end(); PI != E; ++PI) {
2674 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002675 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002676 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002677 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002678 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002679 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002680 t = Context->getPointerType(BPT->getPointeeType());
2681 }
Steve Naroff352336b2007-11-05 14:36:37 +00002682 ArgTypes.push_back(t);
2683 }
Chris Lattner89951a82009-02-20 18:43:26 +00002684 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2685 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002686 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002687 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002688 }
2689 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002690 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002691
Steve Naroffab972d32007-11-04 22:37:50 +00002692 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002693 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002694 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002695
Mike Stump1eb44332009-09-09 15:08:12 +00002696 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002697 // If we don't do this cast, we get the following bizarre warning/note:
2698 // xx.m:13: warning: function called through a non-compatible type
2699 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002700 cast = NoTypeInfoCStyleCastExpr(Context,
2701 Context->getPointerType(Context->VoidTy),
2702 CastExpr::CK_Unknown, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00002703
Steve Naroffab972d32007-11-04 22:37:50 +00002704 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002705 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002706 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002707 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002708 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002709 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00002710 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2711 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002712
2713 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002714 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002715
John McCall183700f2009-09-21 23:43:11 +00002716 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002717 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002718 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002719 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002720 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002721 if (MsgSendStretFlavor) {
2722 // We have the method which returns a struct/union. Must also generate
2723 // call to objc_msgSend_stret and hang both varieties on a conditional
2724 // expression which dictate which one to envoke depending on size of
2725 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002727 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002728 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002729 SourceLocation());
2730 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00002731 cast = NoTypeInfoCStyleCastExpr(Context,
2732 Context->getPointerType(Context->VoidTy),
2733 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002734 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002735 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002736 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002737 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002738 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00002739 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2740 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002742 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002743 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002744
John McCall183700f2009-09-21 23:43:11 +00002745 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002746 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002747 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002748 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002749
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002750 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00002751 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00002752 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00002753 Context->getSizeType(),
2754 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002755 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2756 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2757 // For X86 it is more complicated and some kind of target specific routine
2758 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00002759 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00002760 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002761 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002762 Context->IntTy,
2763 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002764 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2765 BinaryOperator::LE,
2766 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002767 SourceLocation());
2768 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00002769 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00002770 new (Context) ConditionalOperator(lessThanExpr,
2771 SourceLocation(), CE,
2772 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002773 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002774 }
Mike Stump1eb44332009-09-09 15:08:12 +00002775 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002776 return ReplacingStmt;
2777}
2778
Steve Naroffb29b4272008-04-14 22:03:09 +00002779Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002780 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00002781
Steve Naroff934f2762007-10-24 22:48:43 +00002782 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002783 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00002784
2785 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002786 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002787}
2788
Steve Naroff621edce2009-04-29 16:37:50 +00002789// typedef struct objc_object Protocol;
2790QualType RewriteObjC::getProtocolType() {
2791 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00002792 TypeSourceInfo *TInfo
2793 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00002794 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002795 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00002796 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00002797 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00002798 }
2799 return Context->getTypeDeclType(ProtocolTypeDecl);
2800}
2801
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002802/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00002803/// a synthesized/forward data reference (to the protocol's metadata).
2804/// The forward references (and metadata) are generated in
2805/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00002806Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00002807 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2808 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00002809 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor0da76df2009-11-23 11:41:28 +00002810 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroff621edce2009-04-29 16:37:50 +00002811 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2812 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2813 Context->getPointerType(DRE->getType()),
2814 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002815 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
2816 CastExpr::CK_Unknown,
2817 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002818 ReplaceStmt(Exp, castExpr);
2819 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00002820 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002821 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002822
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002823}
2824
Mike Stump1eb44332009-09-09 15:08:12 +00002825bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00002826 const char *endBuf) {
2827 while (startBuf < endBuf) {
2828 if (*startBuf == '#') {
2829 // Skip whitespace.
2830 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2831 ;
2832 if (!strncmp(startBuf, "if", strlen("if")) ||
2833 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2834 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2835 !strncmp(startBuf, "define", strlen("define")) ||
2836 !strncmp(startBuf, "undef", strlen("undef")) ||
2837 !strncmp(startBuf, "else", strlen("else")) ||
2838 !strncmp(startBuf, "elif", strlen("elif")) ||
2839 !strncmp(startBuf, "endif", strlen("endif")) ||
2840 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2841 !strncmp(startBuf, "include", strlen("include")) ||
2842 !strncmp(startBuf, "import", strlen("import")) ||
2843 !strncmp(startBuf, "include_next", strlen("include_next")))
2844 return true;
2845 }
2846 startBuf++;
2847 }
2848 return false;
2849}
2850
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002851/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002852/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002853void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002854 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002855 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00002856 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002857 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002858 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002859 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002860 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002861 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002862 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002863 SourceLocation LocStart = CDecl->getLocStart();
2864 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002865
Steve Narofffea763e82007-11-14 19:25:57 +00002866 const char *startBuf = SM->getCharacterData(LocStart);
2867 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00002868
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002869 // If no ivars and no root or if its root, directly or indirectly,
2870 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002871 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2872 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00002873 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattneraadaf782008-01-31 19:51:04 +00002874 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002875 return;
2876 }
Mike Stump1eb44332009-09-09 15:08:12 +00002877
2878 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002879 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002880 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002881 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002882 if (LangOpts.Microsoft)
2883 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002884
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002885 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002886 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00002887 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002888 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002889 // If the buffer contains preprocessor directives, we do more fine-grained
2890 // rewrites. This is intended to fix code that looks like (which occurs in
2891 // NSURL.h, for example):
2892 //
2893 // #ifdef XYZ
2894 // @interface Foo : NSObject
2895 // #else
2896 // @interface FooBar : NSObject
2897 // #endif
2898 // {
2899 // int i;
2900 // }
2901 // @end
2902 //
2903 // This clause is segregated to avoid breaking the common case.
2904 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002905 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00002906 CDecl->getClassLoc();
2907 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00002908 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002909
Chris Lattnercafeb352009-02-20 18:18:36 +00002910 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002911 // advance to the end of the referenced protocols.
2912 while (endHeader < cursor && *endHeader != '>') endHeader++;
2913 endHeader++;
2914 }
2915 // rewrite the original header
2916 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2917 } else {
2918 // rewrite the original header *without* disturbing the '{'
Steve Naroff17c87782009-12-04 21:36:32 +00002919 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffbaf58c32008-05-31 14:15:04 +00002920 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002921 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002922 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002923 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002924 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002925 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002926 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002927
Steve Narofffea763e82007-11-14 19:25:57 +00002928 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002929 SourceLocation OnePastCurly =
2930 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2931 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002932 }
2933 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00002934
Steve Narofffea763e82007-11-14 19:25:57 +00002935 // Now comment out any visibility specifiers.
2936 while (cursor < endBuf) {
2937 if (*cursor == '@') {
2938 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002939 // Skip whitespace.
2940 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2941 /*scan*/;
2942
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002943 // FIXME: presence of @public, etc. inside comment results in
2944 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002945 if (!strncmp(cursor, "public", strlen("public")) ||
2946 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002947 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002948 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002949 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002950 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002951 // FIXME: If there are cases where '<' is used in ivar declaration part
2952 // of user code, then scan the ivar list and use needToScanForQualifiers
2953 // for type checking.
2954 else if (*cursor == '<') {
2955 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002956 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002957 cursor = strchr(cursor, '>');
2958 cursor++;
2959 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002960 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002961 } else if (*cursor == '^') { // rewrite block specifier.
2962 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2963 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002964 }
Steve Narofffea763e82007-11-14 19:25:57 +00002965 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002966 }
Steve Narofffea763e82007-11-14 19:25:57 +00002967 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002968 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002969 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00002970 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00002971 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002972 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002973 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002974 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002975 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002976 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002977 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002978 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002979 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002980 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002981}
2982
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002983// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002984/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00002985template<typename MethodIterator>
2986void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2987 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002988 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002989 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002990 const char *ClassName,
2991 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002992 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00002993
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002994 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002995 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002996 SEL _cmd;
2997 char *method_types;
2998 void *_imp;
2999 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003000 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003001 Result += "\nstruct _objc_method {\n";
3002 Result += "\tSEL _cmd;\n";
3003 Result += "\tchar *method_types;\n";
3004 Result += "\tvoid *_imp;\n";
3005 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003006
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003007 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003008 }
Mike Stump1eb44332009-09-09 15:08:12 +00003009
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003010 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003011
Steve Naroff946a6932008-03-11 00:12:29 +00003012 /* struct {
3013 struct _objc_method_list *next_method;
3014 int method_count;
3015 struct _objc_method method_list[];
3016 }
3017 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003018 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003019 Result += "\nstatic struct {\n";
3020 Result += "\tstruct _objc_method_list *next_method;\n";
3021 Result += "\tint method_count;\n";
3022 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003023 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003024 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003025 Result += prefix;
3026 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3027 Result += "_METHODS_";
3028 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003029 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003030 Result += IsInstanceMethod ? "inst" : "cls";
3031 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003032 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003033
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003034 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003035 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003036 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003037 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003038 Result += "\", \"";
3039 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003040 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003041 Result += MethodInternalNames[*MethodBegin];
3042 Result += "}\n";
3043 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3044 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003045 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003046 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003047 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003048 Result += "\", \"";
3049 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003050 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003051 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003052 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003053 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003054 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003055}
3056
Steve Naroff621edce2009-04-29 16:37:50 +00003057/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003058void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00003059RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3060 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003061 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003062
3063 // Output struct protocol_methods holder of method selector and type.
3064 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3065 /* struct protocol_methods {
3066 SEL _cmd;
3067 char *method_types;
3068 }
3069 */
3070 Result += "\nstruct _protocol_methods {\n";
3071 Result += "\tstruct objc_selector *_cmd;\n";
3072 Result += "\tchar *method_types;\n";
3073 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003074
Steve Naroff621edce2009-04-29 16:37:50 +00003075 objc_protocol_methods = true;
3076 }
3077 // Do not synthesize the protocol more than once.
3078 if (ObjCSynthesizedProtocols.count(PDecl))
3079 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003080
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003081 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3082 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3083 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003084 /* struct _objc_protocol_method_list {
3085 int protocol_method_count;
3086 struct protocol_methods protocols[];
3087 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003088 */
Steve Naroff621edce2009-04-29 16:37:50 +00003089 Result += "\nstatic struct {\n";
3090 Result += "\tint protocol_method_count;\n";
3091 Result += "\tstruct _protocol_methods protocol_methods[";
3092 Result += utostr(NumMethods);
3093 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3094 Result += PDecl->getNameAsString();
3095 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3096 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003097
Steve Naroff621edce2009-04-29 16:37:50 +00003098 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003099 for (ObjCProtocolDecl::instmeth_iterator
3100 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003101 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003102 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003103 Result += "\t ,{{(struct objc_selector *)\"";
3104 else
3105 Result += "\t ,{(struct objc_selector *)\"";
3106 Result += (*I)->getSelector().getAsString().c_str();
3107 std::string MethodTypeString;
3108 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3109 Result += "\", \"";
3110 Result += MethodTypeString;
3111 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003112 }
Steve Naroff621edce2009-04-29 16:37:50 +00003113 Result += "\t }\n};\n";
3114 }
Mike Stump1eb44332009-09-09 15:08:12 +00003115
Steve Naroff621edce2009-04-29 16:37:50 +00003116 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003117 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3118 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003119 if (NumMethods > 0) {
3120 /* struct _objc_protocol_method_list {
3121 int protocol_method_count;
3122 struct protocol_methods protocols[];
3123 }
3124 */
3125 Result += "\nstatic struct {\n";
3126 Result += "\tint protocol_method_count;\n";
3127 Result += "\tstruct _protocol_methods protocol_methods[";
3128 Result += utostr(NumMethods);
3129 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3130 Result += PDecl->getNameAsString();
3131 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3132 "{\n\t";
3133 Result += utostr(NumMethods);
3134 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003135
Steve Naroff621edce2009-04-29 16:37:50 +00003136 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003137 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003138 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003139 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003140 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003141 Result += "\t ,{{(struct objc_selector *)\"";
3142 else
3143 Result += "\t ,{(struct objc_selector *)\"";
3144 Result += (*I)->getSelector().getAsString().c_str();
3145 std::string MethodTypeString;
3146 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3147 Result += "\", \"";
3148 Result += MethodTypeString;
3149 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003150 }
Steve Naroff621edce2009-04-29 16:37:50 +00003151 Result += "\t }\n};\n";
3152 }
3153
3154 // Output:
3155 /* struct _objc_protocol {
3156 // Objective-C 1.0 extensions
3157 struct _objc_protocol_extension *isa;
3158 char *protocol_name;
3159 struct _objc_protocol **protocol_list;
3160 struct _objc_protocol_method_list *instance_methods;
3161 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003162 };
Steve Naroff621edce2009-04-29 16:37:50 +00003163 */
3164 static bool objc_protocol = false;
3165 if (!objc_protocol) {
3166 Result += "\nstruct _objc_protocol {\n";
3167 Result += "\tstruct _objc_protocol_extension *isa;\n";
3168 Result += "\tchar *protocol_name;\n";
3169 Result += "\tstruct _objc_protocol **protocol_list;\n";
3170 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3171 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003172 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003173
Steve Naroff621edce2009-04-29 16:37:50 +00003174 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003175 }
Mike Stump1eb44332009-09-09 15:08:12 +00003176
Steve Naroff621edce2009-04-29 16:37:50 +00003177 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3178 Result += PDecl->getNameAsString();
3179 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3180 "{\n\t0, \"";
3181 Result += PDecl->getNameAsString();
3182 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003183 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003184 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3185 Result += PDecl->getNameAsString();
3186 Result += ", ";
3187 }
3188 else
3189 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003190 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003191 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3192 Result += PDecl->getNameAsString();
3193 Result += "\n";
3194 }
3195 else
3196 Result += "0\n";
3197 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003198
Steve Naroff621edce2009-04-29 16:37:50 +00003199 // Mark this protocol as having been generated.
3200 if (!ObjCSynthesizedProtocols.insert(PDecl))
3201 assert(false && "protocol already synthesized");
3202
3203}
3204
3205void RewriteObjC::
3206RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3207 const char *prefix, const char *ClassName,
3208 std::string &Result) {
3209 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003210
Steve Naroff621edce2009-04-29 16:37:50 +00003211 for (unsigned i = 0; i != Protocols.size(); i++)
3212 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3213
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003214 // Output the top lovel protocol meta-data for the class.
3215 /* struct _objc_protocol_list {
3216 struct _objc_protocol_list *next;
3217 int protocol_count;
3218 struct _objc_protocol *class_protocols[];
3219 }
3220 */
3221 Result += "\nstatic struct {\n";
3222 Result += "\tstruct _objc_protocol_list *next;\n";
3223 Result += "\tint protocol_count;\n";
3224 Result += "\tstruct _objc_protocol *class_protocols[";
3225 Result += utostr(Protocols.size());
3226 Result += "];\n} _OBJC_";
3227 Result += prefix;
3228 Result += "_PROTOCOLS_";
3229 Result += ClassName;
3230 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3231 "{\n\t0, ";
3232 Result += utostr(Protocols.size());
3233 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003234
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003235 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003236 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003237 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003238
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003239 for (unsigned i = 1; i != Protocols.size(); i++) {
3240 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003241 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003242 Result += "\n";
3243 }
3244 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003245}
3246
Steve Naroff621edce2009-04-29 16:37:50 +00003247
Mike Stump1eb44332009-09-09 15:08:12 +00003248/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003249/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003250void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003251 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003252 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003253 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003254 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003255 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003256 CDecl = CDecl->getNextClassCategory())
3257 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3258 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003259
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003260 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003261 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003262 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003263
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003264 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003265 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003266 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003267
3268 // If any of our property implementations have associated getters or
3269 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003270 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3271 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003272 Prop != PropEnd; ++Prop) {
3273 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3274 continue;
3275 if (!(*Prop)->getPropertyIvarDecl())
3276 continue;
3277 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3278 if (!PD)
3279 continue;
3280 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3281 InstanceMethods.push_back(Getter);
3282 if (PD->isReadOnly())
3283 continue;
3284 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3285 InstanceMethods.push_back(Setter);
3286 }
3287 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003288 true, "CATEGORY_", FullCategoryName.c_str(),
3289 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003290
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003291 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003292 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003293 false, "CATEGORY_", FullCategoryName.c_str(),
3294 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003295
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003296 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003297 // Null CDecl is case of a category implementation with no category interface
3298 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003299 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3300 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003301 /* struct _objc_category {
3302 char *category_name;
3303 char *class_name;
3304 struct _objc_method_list *instance_methods;
3305 struct _objc_method_list *class_methods;
3306 struct _objc_protocol_list *protocols;
3307 // Objective-C 1.0 extensions
3308 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003309 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003310 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003311 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003312 */
Mike Stump1eb44332009-09-09 15:08:12 +00003313
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003314 static bool objc_category = false;
3315 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003316 Result += "\nstruct _objc_category {\n";
3317 Result += "\tchar *category_name;\n";
3318 Result += "\tchar *class_name;\n";
3319 Result += "\tstruct _objc_method_list *instance_methods;\n";
3320 Result += "\tstruct _objc_method_list *class_methods;\n";
3321 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003322 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003323 Result += "\tstruct _objc_property_list *instance_properties;\n";
3324 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003325 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003326 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003327 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3328 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003329 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003330 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003331 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003332 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003333 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003334
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003335 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003336 Result += "\t, (struct _objc_method_list *)"
3337 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3338 Result += FullCategoryName;
3339 Result += "\n";
3340 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003341 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003342 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003343 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003344 Result += "\t, (struct _objc_method_list *)"
3345 "&_OBJC_CATEGORY_CLASS_METHODS_";
3346 Result += FullCategoryName;
3347 Result += "\n";
3348 }
3349 else
3350 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003351
Chris Lattnercafeb352009-02-20 18:18:36 +00003352 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003353 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003354 Result += FullCategoryName;
3355 Result += "\n";
3356 }
3357 else
3358 Result += "\t, 0\n";
3359 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003360}
3361
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003362/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3363/// ivar offset.
Mike Stump1eb44332009-09-09 15:08:12 +00003364void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3365 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003366 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003367 if (ivar->isBitField()) {
3368 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3369 // place all bitfields at offset 0.
3370 Result += "0";
3371 } else {
3372 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003373 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003374 if (LangOpts.Microsoft)
3375 Result += "_IMPL";
3376 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003377 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003378 Result += ")";
3379 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003380}
3381
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003382//===----------------------------------------------------------------------===//
3383// Meta Data Emission
3384//===----------------------------------------------------------------------===//
3385
Steve Naroffb29b4272008-04-14 22:03:09 +00003386void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003387 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003388 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003389
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003390 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003391 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003392 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003393 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003394 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003395 }
Mike Stump1eb44332009-09-09 15:08:12 +00003396
Chris Lattnerbe6df082007-12-12 07:56:42 +00003397 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003398 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003399 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003400 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003401 if (NumIvars > 0) {
3402 static bool objc_ivar = false;
3403 if (!objc_ivar) {
3404 /* struct _objc_ivar {
3405 char *ivar_name;
3406 char *ivar_type;
3407 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003408 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003409 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003410 Result += "\nstruct _objc_ivar {\n";
3411 Result += "\tchar *ivar_name;\n";
3412 Result += "\tchar *ivar_type;\n";
3413 Result += "\tint ivar_offset;\n";
3414 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003415
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003416 objc_ivar = true;
3417 }
3418
Steve Naroff946a6932008-03-11 00:12:29 +00003419 /* struct {
3420 int ivar_count;
3421 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003422 };
Steve Naroff946a6932008-03-11 00:12:29 +00003423 */
Mike Stump1eb44332009-09-09 15:08:12 +00003424 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003425 Result += "\tint ivar_count;\n";
3426 Result += "\tstruct _objc_ivar ivar_list[";
3427 Result += utostr(NumIvars);
3428 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003429 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003430 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003431 "{\n\t";
3432 Result += utostr(NumIvars);
3433 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003434
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003435 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003436 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003437 if (!IDecl->ivar_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003438 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003439 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003440 IV != IVEnd; ++IV)
3441 IVars.push_back(*IV);
3442 IVI = IVars.begin();
3443 IVE = IVars.end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003444 } else {
3445 IVI = CDecl->ivar_begin();
3446 IVE = CDecl->ivar_end();
3447 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003448 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003449 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003450 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003451 std::string TmpString, StrEncoding;
3452 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3453 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003454 Result += StrEncoding;
3455 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003456 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003457 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003458 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003459 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003460 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003461 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003462 std::string TmpString, StrEncoding;
3463 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3464 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003465 Result += StrEncoding;
3466 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003467 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003468 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003469 }
Mike Stump1eb44332009-09-09 15:08:12 +00003470
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003471 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003472 }
Mike Stump1eb44332009-09-09 15:08:12 +00003473
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003474 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003475 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003476 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003477
3478 // If any of our property implementations have associated getters or
3479 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003480 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3481 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003482 Prop != PropEnd; ++Prop) {
3483 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3484 continue;
3485 if (!(*Prop)->getPropertyIvarDecl())
3486 continue;
3487 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3488 if (!PD)
3489 continue;
3490 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3491 InstanceMethods.push_back(Getter);
3492 if (PD->isReadOnly())
3493 continue;
3494 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3495 InstanceMethods.push_back(Setter);
3496 }
3497 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003498 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003499
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003500 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003501 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003502 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003503
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003504 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003505 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3506 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003508 // Declaration of class/meta-class metadata
3509 /* struct _objc_class {
3510 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003511 const char *super_class_name;
3512 char *name;
3513 long version;
3514 long info;
3515 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003516 struct _objc_ivar_list *ivars;
3517 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003518 struct objc_cache *cache;
3519 struct objc_protocol_list *protocols;
3520 const char *ivar_layout;
3521 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003522 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003523 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003524 static bool objc_class = false;
3525 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003526 Result += "\nstruct _objc_class {\n";
3527 Result += "\tstruct _objc_class *isa;\n";
3528 Result += "\tconst char *super_class_name;\n";
3529 Result += "\tchar *name;\n";
3530 Result += "\tlong version;\n";
3531 Result += "\tlong info;\n";
3532 Result += "\tlong instance_size;\n";
3533 Result += "\tstruct _objc_ivar_list *ivars;\n";
3534 Result += "\tstruct _objc_method_list *methods;\n";
3535 Result += "\tstruct objc_cache *cache;\n";
3536 Result += "\tstruct _objc_protocol_list *protocols;\n";
3537 Result += "\tconst char *ivar_layout;\n";
3538 Result += "\tstruct _objc_class_ext *ext;\n";
3539 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003540 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003541 }
Mike Stump1eb44332009-09-09 15:08:12 +00003542
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003543 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003544 ObjCInterfaceDecl *RootClass = 0;
3545 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003546 while (SuperClass) {
3547 RootClass = SuperClass;
3548 SuperClass = SuperClass->getSuperClass();
3549 }
3550 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003551
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003552 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003553 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003554 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003555 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003556 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003557 Result += "\"";
3558
3559 if (SuperClass) {
3560 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003561 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003562 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003563 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003564 Result += "\"";
3565 }
3566 else {
3567 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003568 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003569 Result += "\"";
3570 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003571 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003572 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003573 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003574 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003575 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003576 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003577 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003578 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003579 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003580 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003581 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003582 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003583 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003584 Result += ",0,0\n";
3585 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003586 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003587 Result += "\t,0,0,0,0\n";
3588 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003589
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003590 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003591 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003592 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003593 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003594 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003595 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003596 if (SuperClass) {
3597 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003598 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003599 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003600 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003601 Result += "\"";
3602 }
3603 else {
3604 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003605 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003606 Result += "\"";
3607 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003608 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003609 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003610 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003611 Result += ",0";
3612 else {
3613 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003614 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003615 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003616 if (LangOpts.Microsoft)
3617 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003618 Result += ")";
3619 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003620 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003621 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003622 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003623 Result += "\n\t";
3624 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003625 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003626 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003627 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003628 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003629 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003630 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003631 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003632 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003633 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003634 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003635 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003636 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003637 Result += ", 0,0\n";
3638 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003639 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003640 Result += ",0,0,0\n";
3641 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003642}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003643
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003644/// RewriteImplementations - This routine rewrites all method implementations
3645/// and emits meta-data.
3646
Steve Narofface66252008-11-13 20:07:04 +00003647void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003648 int ClsDefCount = ClassImplementation.size();
3649 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003650
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003651 // Rewrite implemented methods
3652 for (int i = 0; i < ClsDefCount; i++)
3653 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003654
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003655 for (int i = 0; i < CatDefCount; i++)
3656 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003657}
Mike Stump1eb44332009-09-09 15:08:12 +00003658
Steve Narofface66252008-11-13 20:07:04 +00003659void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3660 int ClsDefCount = ClassImplementation.size();
3661 int CatDefCount = CategoryImplementation.size();
3662
Steve Naroff5df5b762008-05-07 21:23:49 +00003663 // This is needed for determining instance variable offsets.
Fariborz Jahanianc98cbb42010-01-07 18:31:42 +00003664 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003665 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003666 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003667 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003668
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003669 // For each implemented category, write out all its meta data.
3670 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003671 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003672
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003673 // Write objc_symtab metadata
3674 /*
3675 struct _objc_symtab
3676 {
3677 long sel_ref_cnt;
3678 SEL *refs;
3679 short cls_def_cnt;
3680 short cat_def_cnt;
3681 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003682 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003683 */
Mike Stump1eb44332009-09-09 15:08:12 +00003684
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003685 Result += "\nstruct _objc_symtab {\n";
3686 Result += "\tlong sel_ref_cnt;\n";
3687 Result += "\tSEL *refs;\n";
3688 Result += "\tshort cls_def_cnt;\n";
3689 Result += "\tshort cat_def_cnt;\n";
3690 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3691 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003692
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003693 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003694 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003695 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003696 + ", " + utostr(CatDefCount) + "\n";
3697 for (int i = 0; i < ClsDefCount; i++) {
3698 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003699 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003700 Result += "\n";
3701 }
Mike Stump1eb44332009-09-09 15:08:12 +00003702
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003703 for (int i = 0; i < CatDefCount; i++) {
3704 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003705 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003706 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003707 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003708 Result += "\n";
3709 }
Mike Stump1eb44332009-09-09 15:08:12 +00003710
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003711 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003712
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003713 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00003714
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003715 /*
3716 struct _objc_module {
3717 long version;
3718 long size;
3719 const char *name;
3720 struct _objc_symtab *symtab;
3721 }
3722 */
Mike Stump1eb44332009-09-09 15:08:12 +00003723
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003724 Result += "\nstruct _objc_module {\n";
3725 Result += "\tlong version;\n";
3726 Result += "\tlong size;\n";
3727 Result += "\tconst char *name;\n";
3728 Result += "\tstruct _objc_symtab *symtab;\n";
3729 Result += "};\n\n";
3730 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003731 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003732 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003733 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003734 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003735
3736 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00003737 if (ProtocolExprDecls.size()) {
3738 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3739 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003740 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00003741 E = ProtocolExprDecls.end(); I != E; ++I) {
3742 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3743 Result += (*I)->getNameAsString();
3744 Result += " = &_OBJC_PROTOCOL_";
3745 Result += (*I)->getNameAsString();
3746 Result += ";\n";
3747 }
3748 Result += "#pragma data_seg(pop)\n\n";
3749 }
Steve Naroff4f943c22008-03-10 20:43:59 +00003750 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003751 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003752 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3753 Result += "&_OBJC_MODULES;\n";
3754 Result += "#pragma data_seg(pop)\n\n";
3755 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003756}
Chris Lattner311ff022007-10-16 22:36:42 +00003757
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003758void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3759 const std::string &Name,
3760 ValueDecl *VD) {
3761 assert(BlockByRefDeclNo.count(VD) &&
3762 "RewriteByRefString: ByRef decl missing");
3763 ResultStr += "struct __Block_byref_" + Name +
3764 "_" + utostr(BlockByRefDeclNo[VD]) ;
3765}
3766
Steve Naroff54055232008-10-27 17:20:55 +00003767std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3768 const char *funcName,
3769 std::string Tag) {
3770 const FunctionType *AFT = CE->getFunctionType();
3771 QualType RT = AFT->getResultType();
3772 std::string StructRef = "struct " + Tag;
3773 std::string S = "static " + RT.getAsString() + " __" +
3774 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003775
Steve Naroff54055232008-10-27 17:20:55 +00003776 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003777
Douglas Gregor72564e72009-02-26 23:50:07 +00003778 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003779 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003780 // block (to reference imported block decl refs).
3781 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003782 } else if (BD->param_empty()) {
3783 S += "(" + StructRef + " *__cself)";
3784 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003785 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003786 assert(FT && "SynthesizeBlockFunc: No function proto");
3787 S += '(';
3788 // first add the implicit argument.
3789 S += StructRef + " *__cself, ";
3790 std::string ParamStr;
3791 for (BlockDecl::param_iterator AI = BD->param_begin(),
3792 E = BD->param_end(); AI != E; ++AI) {
3793 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003794 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003795 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003796 S += ParamStr;
3797 }
3798 if (FT->isVariadic()) {
3799 if (!BD->param_empty()) S += ", ";
3800 S += "...";
3801 }
3802 S += ')';
3803 }
3804 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003805
Steve Naroff54055232008-10-27 17:20:55 +00003806 // Create local declarations to avoid rewriting all closure decl ref exprs.
3807 // First, emit a declaration for all "by ref" decls.
Mike Stump1eb44332009-09-09 15:08:12 +00003808 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003809 E = BlockByRefDecls.end(); I != E; ++I) {
3810 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003811 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003812 std::string TypeString;
3813 RewriteByRefString(TypeString, Name, (*I));
3814 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003815 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003816 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003817 }
Steve Naroff54055232008-10-27 17:20:55 +00003818 // Next, emit a declaration for all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003819 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003820 E = BlockByCopyDecls.end(); I != E; ++I) {
3821 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003822 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003823 // Handle nested closure invocation. For example:
3824 //
3825 // void (^myImportedClosure)(void);
3826 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003827 //
Steve Naroff54055232008-10-27 17:20:55 +00003828 // void (^anotherClosure)(void);
3829 // anotherClosure = ^(void) {
3830 // myImportedClosure(); // import and invoke the closure
3831 // };
3832 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003833 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003834 S += "struct __block_impl *";
3835 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003836 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003837 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003838 }
3839 std::string RewrittenStr = RewrittenBlockExprs[CE];
3840 const char *cstr = RewrittenStr.c_str();
3841 while (*cstr++ != '{') ;
3842 S += cstr;
3843 S += "\n";
3844 return S;
3845}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003846
Steve Naroff54055232008-10-27 17:20:55 +00003847std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3848 const char *funcName,
3849 std::string Tag) {
3850 std::string StructRef = "struct " + Tag;
3851 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003852
Steve Naroff54055232008-10-27 17:20:55 +00003853 S += funcName;
3854 S += "_block_copy_" + utostr(i);
3855 S += "(" + StructRef;
3856 S += "*dst, " + StructRef;
3857 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003858 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003859 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003860 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003861 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003862 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003863 S += (*I)->getNameAsString();
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003864 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003865 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003866 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003867 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003868 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003869 S += "}\n";
3870
Steve Naroff54055232008-10-27 17:20:55 +00003871 S += "\nstatic void __";
3872 S += funcName;
3873 S += "_block_dispose_" + utostr(i);
3874 S += "(" + StructRef;
3875 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003876 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003877 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003878 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003879 S += (*I)->getNameAsString();
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003880 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003881 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003882 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003883 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003884 }
Mike Stump1eb44332009-09-09 15:08:12 +00003885 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003886 return S;
3887}
3888
Steve Naroff01aec112009-12-06 21:14:13 +00003889std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3890 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003891 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003892 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003893
Steve Naroff54055232008-10-27 17:20:55 +00003894 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003895 S += " struct " + Desc;
3896 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003897
Steve Naroff01aec112009-12-06 21:14:13 +00003898 Constructor += "(void *fp, "; // Invoke function pointer.
3899 Constructor += "struct " + Desc; // Descriptor pointer.
3900 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003901
Steve Naroff54055232008-10-27 17:20:55 +00003902 if (BlockDeclRefs.size()) {
3903 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003904 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003905 E = BlockByCopyDecls.end(); I != E; ++I) {
3906 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003907 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003908 std::string ArgName = "_" + FieldName;
3909 // Handle nested closure invocation. For example:
3910 //
3911 // void (^myImportedBlock)(void);
3912 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003913 //
Steve Naroff54055232008-10-27 17:20:55 +00003914 // void (^anotherBlock)(void);
3915 // anotherBlock = ^(void) {
3916 // myImportedBlock(); // import and invoke the closure
3917 // };
3918 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003919 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003920 S += "struct __block_impl *";
3921 Constructor += ", void *" + ArgName;
3922 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003923 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3924 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003925 Constructor += ", " + ArgName;
3926 }
3927 S += FieldName + ";\n";
3928 }
3929 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003930 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003931 E = BlockByRefDecls.end(); I != E; ++I) {
3932 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003933 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003934 std::string ArgName = "_" + FieldName;
3935 // Handle nested closure invocation. For example:
3936 //
3937 // void (^myImportedBlock)(void);
3938 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003939 //
Steve Naroff54055232008-10-27 17:20:55 +00003940 // void (^anotherBlock)(void);
3941 // anotherBlock = ^(void) {
3942 // myImportedBlock(); // import and invoke the closure
3943 // };
3944 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003945 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003946 S += "struct __block_impl *";
3947 Constructor += ", void *" + ArgName;
3948 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003949 std::string TypeString;
3950 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003951 TypeString += " *";
3952 FieldName = TypeString + FieldName;
3953 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003954 Constructor += ", " + ArgName;
3955 }
3956 S += FieldName + "; // by ref\n";
3957 }
3958 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003959 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003960 if (GlobalVarDecl)
3961 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3962 else
3963 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003964 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003965
Steve Naroff01aec112009-12-06 21:14:13 +00003966 Constructor += " Desc = desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003967
Steve Naroff54055232008-10-27 17:20:55 +00003968 // Initialize all "by copy" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003969 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003970 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003971 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003972 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003973 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003974 Constructor += Name + " = (struct __block_impl *)_";
3975 else
3976 Constructor += Name + " = _";
3977 Constructor += Name + ";\n";
3978 }
3979 // Initialize all "by ref" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003980 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003981 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003982 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003983 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003984 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003985 Constructor += Name + " = (struct __block_impl *)_";
3986 else
3987 Constructor += Name + " = _";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003988 Constructor += Name + "->__forwarding;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003989 }
3990 } else {
3991 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003992 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003993 if (GlobalVarDecl)
3994 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3995 else
3996 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003997 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3998 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003999 }
4000 Constructor += " ";
4001 Constructor += "}\n";
4002 S += Constructor;
4003 S += "};\n";
4004 return S;
4005}
4006
Steve Naroff01aec112009-12-06 21:14:13 +00004007std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4008 std::string ImplTag, int i,
4009 const char *FunName,
4010 unsigned hasCopy) {
4011 std::string S = "\nstatic struct " + DescTag;
4012
4013 S += " {\n unsigned long reserved;\n";
4014 S += " unsigned long Block_size;\n";
4015 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004016 S += " void (*copy)(struct ";
4017 S += ImplTag; S += "*, struct ";
4018 S += ImplTag; S += "*);\n";
4019
4020 S += " void (*dispose)(struct ";
4021 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004022 }
4023 S += "} ";
4024
4025 S += DescTag + "_DATA = { 0, sizeof(struct ";
4026 S += ImplTag + ")";
4027 if (hasCopy) {
4028 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4029 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4030 }
4031 S += "};\n";
4032 return S;
4033}
4034
Steve Naroff54055232008-10-27 17:20:55 +00004035void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004036 const char *FunName) {
4037 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004038 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004039 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004040 // Insert closures that were part of the function.
4041 for (unsigned i = 0; i < Blocks.size(); i++) {
4042
4043 CollectBlockDeclRefInfo(Blocks[i]);
4044
Steve Naroff01aec112009-12-06 21:14:13 +00004045 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4046 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004047
Steve Naroff01aec112009-12-06 21:14:13 +00004048 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004049
4050 InsertText(FunLocStart, CI.c_str(), CI.size());
4051
Steve Naroff01aec112009-12-06 21:14:13 +00004052 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004053
Steve Naroff54055232008-10-27 17:20:55 +00004054 InsertText(FunLocStart, CF.c_str(), CF.size());
4055
4056 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004057 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff54055232008-10-27 17:20:55 +00004058 InsertText(FunLocStart, HF.c_str(), HF.size());
4059 }
Steve Naroff01aec112009-12-06 21:14:13 +00004060 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4061 ImportedBlockDecls.size() > 0);
4062 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004063
Steve Naroff54055232008-10-27 17:20:55 +00004064 BlockDeclRefs.clear();
4065 BlockByRefDecls.clear();
4066 BlockByCopyDecls.clear();
4067 BlockCallExprs.clear();
4068 ImportedBlockDecls.clear();
4069 }
4070 Blocks.clear();
4071 RewrittenBlockExprs.clear();
4072}
4073
4074void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4075 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00004076 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00004077
Steve Naroff54055232008-10-27 17:20:55 +00004078 SynthesizeBlockLiterals(FunLocStart, FuncName);
4079}
4080
4081void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004082 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4083 //SourceLocation FunLocStart = MD->getLocStart();
4084 // FIXME: This hack works around a bug in Rewrite.InsertText().
4085 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00004086 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004087 // Convert colons to underscores.
4088 std::string::size_type loc = 0;
4089 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4090 FuncName.replace(loc, 1, "_");
Mike Stump1eb44332009-09-09 15:08:12 +00004091
Steve Naroff54055232008-10-27 17:20:55 +00004092 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4093}
4094
4095void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4096 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4097 CI != E; ++CI)
4098 if (*CI) {
4099 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4100 GetBlockDeclRefExprs(CBE->getBody());
4101 else
4102 GetBlockDeclRefExprs(*CI);
4103 }
4104 // Handle specific things.
4105 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4106 // FIXME: Handle enums.
4107 if (!isa<FunctionDecl>(CDRE->getDecl()))
4108 BlockDeclRefs.push_back(CDRE);
4109 return;
4110}
4111
4112void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4113 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4114 CI != E; ++CI)
4115 if (*CI) {
4116 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4117 GetBlockCallExprs(CBE->getBody());
4118 else
4119 GetBlockCallExprs(*CI);
4120 }
Mike Stump1eb44332009-09-09 15:08:12 +00004121
Steve Naroff54055232008-10-27 17:20:55 +00004122 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4123 if (CE->getCallee()->getType()->isBlockPointerType()) {
4124 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4125 }
4126 }
4127 return;
4128}
4129
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004130Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004131 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004132 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004133
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004134 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004135 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004136 } else if (const BlockDeclRefExpr *CDRE =
4137 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004138 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004139 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004140 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004141 }
4142 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4143 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4144 }
4145 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4146 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4147 else if (const ConditionalOperator *CEXPR =
4148 dyn_cast<ConditionalOperator>(BlockExp)) {
4149 Expr *LHSExp = CEXPR->getLHS();
4150 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4151 Expr *RHSExp = CEXPR->getRHS();
4152 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4153 Expr *CONDExp = CEXPR->getCond();
4154 ConditionalOperator *CondExpr =
4155 new (Context) ConditionalOperator(CONDExp,
4156 SourceLocation(), cast<Expr>(LHSStmt),
4157 SourceLocation(), cast<Expr>(RHSStmt),
4158 Exp->getType());
4159 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004160 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4161 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004162 } else {
4163 assert(1 && "RewriteBlockClass: Bad type");
4164 }
4165 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004166 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004167 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004168 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004169 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004170
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004171 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4172 SourceLocation(),
4173 &Context->Idents.get("__block_impl"));
4174 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004175
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004176 // Generate a funky cast.
4177 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004178
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004179 // Push the block argument type.
4180 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004181 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004182 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004183 E = FTP->arg_type_end(); I && (I != E); ++I) {
4184 QualType t = *I;
4185 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004186 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004187 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004188 t = Context->getPointerType(BPT->getPointeeType());
4189 }
4190 ArgTypes.push_back(t);
4191 }
Steve Naroff54055232008-10-27 17:20:55 +00004192 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004193 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004194 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004195 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004196
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004197 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004198
John McCall9d125032010-01-15 18:39:57 +00004199 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4200 CastExpr::CK_Unknown,
4201 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004202 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004203 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4204 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004205 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004206
Douglas Gregor44b43212008-12-11 16:49:14 +00004207 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004208 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004209 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004210 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4211 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004212
John McCall9d125032010-01-15 18:39:57 +00004213 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4214 CastExpr::CK_Unknown, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004215 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004216
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004217 llvm::SmallVector<Expr*, 8> BlkExprs;
4218 // Add the implicit argument.
4219 BlkExprs.push_back(BlkCast);
4220 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004221 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004222 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004223 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004224 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004225 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4226 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004227 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004228 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004229}
4230
4231void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004232 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004233 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00004234}
4235
Steve Naroff621edce2009-04-29 16:37:50 +00004236// We need to return the rewritten expression to handle cases where the
4237// BlockDeclRefExpr is embedded in another expression being rewritten.
4238// For example:
4239//
4240// int main() {
4241// __block Foo *f;
4242// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004243//
Steve Naroff621edce2009-04-29 16:37:50 +00004244// void (^myblock)() = ^() {
4245// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4246// i = 77;
4247// };
4248//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004249Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004250 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004251 // for each DeclRefExp where BYREFVAR is name of the variable.
4252 ValueDecl *VD;
4253 bool isArrow = true;
4254 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4255 VD = BDRE->getDecl();
4256 else {
4257 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4258 isArrow = false;
4259 }
4260
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004261 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4262 &Context->Idents.get("__forwarding"),
4263 Context->VoidPtrTy, 0,
4264 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004265 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4266 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004267 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004268
4269 const char *Name = VD->getNameAsCString();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004270 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4271 &Context->Idents.get(Name),
4272 Context->VoidPtrTy, 0,
4273 /*BitWidth=*/0, /*Mutable=*/true);
4274 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004275 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004276
4277
4278
Steve Naroffdf8570d2009-02-02 17:19:26 +00004279 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004280 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4281 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004282 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004283 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004284}
4285
Steve Naroffb2f9e512008-11-03 23:29:32 +00004286void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4287 SourceLocation LocStart = CE->getLParenLoc();
4288 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004289
4290 // Need to avoid trying to rewrite synthesized casts.
4291 if (LocStart.isInvalid())
4292 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004293 // Need to avoid trying to rewrite casts contained in macros.
4294 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4295 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004296
Steve Naroff54055232008-10-27 17:20:55 +00004297 const char *startBuf = SM->getCharacterData(LocStart);
4298 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004299 QualType QT = CE->getType();
4300 const Type* TypePtr = QT->getAs<Type>();
4301 if (isa<TypeOfExprType>(TypePtr)) {
4302 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4303 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4304 std::string TypeAsString = "(";
4305 TypeAsString += QT.getAsString();
4306 TypeAsString += ")";
4307 ReplaceText(LocStart, endBuf-startBuf+1,
4308 TypeAsString.c_str(), TypeAsString.size());
4309 return;
4310 }
4311
Steve Naroff54055232008-10-27 17:20:55 +00004312 // advance the location to startArgList.
4313 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004314
Steve Naroff54055232008-10-27 17:20:55 +00004315 while (*argPtr++ && (argPtr < endBuf)) {
4316 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004317 case '^':
4318 // Replace the '^' with '*'.
4319 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4320 ReplaceText(LocStart, 1, "*", 1);
4321 break;
Steve Naroff54055232008-10-27 17:20:55 +00004322 }
4323 }
4324 return;
4325}
4326
4327void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4328 SourceLocation DeclLoc = FD->getLocation();
4329 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004330
Steve Naroff54055232008-10-27 17:20:55 +00004331 // We have 1 or more arguments that have closure pointers.
4332 const char *startBuf = SM->getCharacterData(DeclLoc);
4333 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004334
Steve Naroff54055232008-10-27 17:20:55 +00004335 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004336
Steve Naroff54055232008-10-27 17:20:55 +00004337 parenCount++;
4338 // advance the location to startArgList.
4339 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4340 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004341
Steve Naroff54055232008-10-27 17:20:55 +00004342 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004343
Steve Naroff54055232008-10-27 17:20:55 +00004344 while (*argPtr++ && parenCount) {
4345 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004346 case '^':
4347 // Replace the '^' with '*'.
4348 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4349 ReplaceText(DeclLoc, 1, "*", 1);
4350 break;
4351 case '(':
4352 parenCount++;
4353 break;
4354 case ')':
4355 parenCount--;
4356 break;
Steve Naroff54055232008-10-27 17:20:55 +00004357 }
4358 }
4359 return;
4360}
4361
4362bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004363 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004364 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004365 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004366 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004367 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004368 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004369 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004370 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004371 }
4372 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004373 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004374 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004375 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004376 return true;
4377 }
4378 return false;
4379}
4380
Ted Kremenek8189cde2009-02-07 01:47:29 +00004381void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4382 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004383 const char *argPtr = strchr(Name, '(');
4384 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004385
Steve Naroff54055232008-10-27 17:20:55 +00004386 LParen = argPtr; // output the start.
4387 argPtr++; // skip past the left paren.
4388 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004389
Steve Naroff54055232008-10-27 17:20:55 +00004390 while (*argPtr && parenCount) {
4391 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004392 case '(': parenCount++; break;
4393 case ')': parenCount--; break;
4394 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004395 }
4396 if (parenCount) argPtr++;
4397 }
4398 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4399 RParen = argPtr; // output the end
4400}
4401
4402void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4403 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4404 RewriteBlockPointerFunctionArgs(FD);
4405 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004406 }
Steve Naroff54055232008-10-27 17:20:55 +00004407 // Handle Variables and Typedefs.
4408 SourceLocation DeclLoc = ND->getLocation();
4409 QualType DeclT;
4410 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4411 DeclT = VD->getType();
4412 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4413 DeclT = TDD->getUnderlyingType();
4414 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4415 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004416 else
Steve Naroff54055232008-10-27 17:20:55 +00004417 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004418
Steve Naroff54055232008-10-27 17:20:55 +00004419 const char *startBuf = SM->getCharacterData(DeclLoc);
4420 const char *endBuf = startBuf;
4421 // scan backward (from the decl location) for the end of the previous decl.
4422 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4423 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004424
Steve Naroff54055232008-10-27 17:20:55 +00004425 // *startBuf != '^' if we are dealing with a pointer to function that
4426 // may take block argument types (which will be handled below).
4427 if (*startBuf == '^') {
4428 // Replace the '^' with '*', computing a negative offset.
4429 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4430 ReplaceText(DeclLoc, 1, "*", 1);
4431 }
4432 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4433 // Replace the '^' with '*' for arguments.
4434 DeclLoc = ND->getLocation();
4435 startBuf = SM->getCharacterData(DeclLoc);
4436 const char *argListBegin, *argListEnd;
4437 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4438 while (argListBegin < argListEnd) {
4439 if (*argListBegin == '^') {
4440 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4441 ReplaceText(CaretLoc, 1, "*", 1);
4442 }
4443 argListBegin++;
4444 }
4445 }
4446 return;
4447}
4448
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004449
4450/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4451/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4452/// struct Block_byref_id_object *src) {
4453/// _Block_object_assign (&_dest->object, _src->object,
4454/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4455/// [|BLOCK_FIELD_IS_WEAK]) // object
4456/// _Block_object_assign(&_dest->object, _src->object,
4457/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4458/// [|BLOCK_FIELD_IS_WEAK]) // block
4459/// }
4460/// And:
4461/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4462/// _Block_object_dispose(_src->object,
4463/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4464/// [|BLOCK_FIELD_IS_WEAK]) // object
4465/// _Block_object_dispose(_src->object,
4466/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4467/// [|BLOCK_FIELD_IS_WEAK]) // block
4468/// }
4469
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004470std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4471 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004472 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004473 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004474 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004475 CopyDestroyCache.insert(flag);
4476 S = "static void __Block_byref_id_object_copy_";
4477 S += utostr(flag);
4478 S += "(void *dst, void *src) {\n";
4479
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004480 // offset into the object pointer is computed as:
4481 // void * + void* + int + int + void* + void *
4482 unsigned IntSize =
4483 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4484 unsigned VoidPtrSize =
4485 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4486
4487 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4488 S += " _Block_object_assign((char*)dst + ";
4489 S += utostr(offset);
4490 S += ", *(void * *) ((char*)src + ";
4491 S += utostr(offset);
4492 S += "), ";
4493 S += utostr(flag);
4494 S += ");\n}\n";
4495
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004496 S += "static void __Block_byref_id_object_dispose_";
4497 S += utostr(flag);
4498 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004499 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4500 S += utostr(offset);
4501 S += "), ";
4502 S += utostr(flag);
4503 S += ");\n}\n";
4504 return S;
4505}
4506
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004507/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4508/// the declaration into:
4509/// struct __Block_byref_ND {
4510/// void *__isa; // NULL for everything except __weak pointers
4511/// struct __Block_byref_ND *__forwarding;
4512/// int32_t __flags;
4513/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004514/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4515/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004516/// typex ND;
4517/// };
4518///
4519/// It then replaces declaration of ND variable with:
4520/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4521/// __size=sizeof(struct __Block_byref_ND),
4522/// ND=initializer-if-any};
4523///
4524///
4525void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004526 // Insert declaration for the function in which block literal is
4527 // used.
4528 if (CurFunctionDeclToDeclareForBlock)
4529 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004530 int flag = 0;
4531 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004532 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4533 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004534 SourceLocation X = ND->getLocEnd();
4535 X = SM->getInstantiationLoc(X);
4536 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004537 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004538 std::string ByrefType;
4539 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004540 ByrefType += " {\n";
4541 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004542 RewriteByRefString(ByrefType, Name, ND);
4543 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004544 ByrefType += " int __flags;\n";
4545 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004546 // Add void *__Block_byref_id_object_copy;
4547 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004548 QualType Ty = ND->getType();
4549 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4550 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004551 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4552 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004553 }
4554
4555 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004556 ByrefType += " " + Name + ";\n";
4557 ByrefType += "};\n";
4558 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004559 SourceLocation FunLocStart;
4560 if (CurFunctionDef)
4561 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4562 else {
4563 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4564 FunLocStart = CurMethodDef->getLocStart();
4565 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004566 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004567 if (Ty.isObjCGCWeak()) {
4568 flag |= BLOCK_FIELD_IS_WEAK;
4569 isa = 1;
4570 }
4571
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004572 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004573 flag = BLOCK_BYREF_CALLER;
4574 QualType Ty = ND->getType();
4575 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4576 if (Ty->isBlockPointerType())
4577 flag |= BLOCK_FIELD_IS_BLOCK;
4578 else
4579 flag |= BLOCK_FIELD_IS_OBJECT;
4580 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004581 if (!HF.empty())
4582 InsertText(FunLocStart, HF.c_str(), HF.size());
4583 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004584
4585 // struct __Block_byref_ND ND =
4586 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4587 // initializer-if-any};
4588 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004589 unsigned flags = 0;
4590 if (HasCopyAndDispose)
4591 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004592 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004593 ByrefType.clear();
4594 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004595 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004596 ByrefType += " " + Name + " = {(void*)";
4597 ByrefType += utostr(isa);
4598 ByrefType += ", &" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004599 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004600 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004601 ByrefType += "sizeof(";
4602 RewriteByRefString(ByrefType, Name, ND);
4603 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004604 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004605 ByrefType += ", __Block_byref_id_object_copy_";
4606 ByrefType += utostr(flag);
4607 ByrefType += ", __Block_byref_id_object_dispose_";
4608 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004609 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004610 ByrefType += "};\n";
4611 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4612 ByrefType.c_str(), ByrefType.size());
4613 }
4614 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004615 SourceLocation startLoc;
4616 Expr *E = ND->getInit();
4617 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4618 startLoc = ECE->getLParenLoc();
4619 else
4620 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00004621 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004622 endBuf = SM->getCharacterData(startLoc);
4623
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004624 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004625 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004626 ByrefType += utostr(isa);
4627 ByrefType += ", &" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004628 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004629 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004630 ByrefType += "sizeof(";
4631 RewriteByRefString(ByrefType, Name, ND);
4632 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004633 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004634 ByrefType += "__Block_byref_id_object_copy_";
4635 ByrefType += utostr(flag);
4636 ByrefType += ", __Block_byref_id_object_dispose_";
4637 ByrefType += utostr(flag);
4638 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004639 }
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004640 ReplaceText(DeclLoc, endBuf-startBuf,
4641 ByrefType.c_str(), ByrefType.size());
Steve Naroffc5143c52009-12-23 17:24:33 +00004642
4643 // Complete the newly synthesized compound expression by inserting a right
4644 // curly brace before the end of the declaration.
4645 // FIXME: This approach avoids rewriting the initializer expression. It
4646 // also assumes there is only one declarator. For example, the following
4647 // isn't currently supported by this routine (in general):
4648 //
4649 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4650 //
4651 const char *startBuf = SM->getCharacterData(startLoc);
4652 const char *semiBuf = strchr(startBuf, ';');
4653 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4654 SourceLocation semiLoc =
4655 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4656
4657 InsertText(semiLoc, "}", 1);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004658 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004659 return;
4660}
4661
Mike Stump1eb44332009-09-09 15:08:12 +00004662void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004663 // Add initializers for any closure decl refs.
4664 GetBlockDeclRefExprs(Exp->getBody());
4665 if (BlockDeclRefs.size()) {
4666 // Unique all "by copy" declarations.
4667 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4668 if (!BlockDeclRefs[i]->isByRef())
4669 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4670 // Unique all "by ref" declarations.
4671 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4672 if (BlockDeclRefs[i]->isByRef()) {
4673 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4674 }
4675 // Find any imported blocks...they will need special attention.
4676 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004677 if (BlockDeclRefs[i]->isByRef() ||
4678 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4679 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004680 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004681 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4682 }
4683 }
4684}
4685
Steve Narofffa15fd92008-10-28 20:29:00 +00004686FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4687 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004688 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00004689 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004690 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor2224f842009-02-25 16:33:18 +00004691 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004692}
4693
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004694Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004695 Blocks.push_back(Exp);
4696
4697 CollectBlockDeclRefInfo(Exp);
4698 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004699
Steve Narofffa15fd92008-10-28 20:29:00 +00004700 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004701 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004702 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004703 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004704 // Convert colons to underscores.
4705 std::string::size_type loc = 0;
4706 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4707 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004708 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004709 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004710
Steve Narofffa15fd92008-10-28 20:29:00 +00004711 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004712
Steve Narofffa15fd92008-10-28 20:29:00 +00004713 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4714 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004715
Steve Narofffa15fd92008-10-28 20:29:00 +00004716 // Get a pointer to the function type so we can cast appropriately.
4717 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4718
4719 FunctionDecl *FD;
4720 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004721
Steve Narofffa15fd92008-10-28 20:29:00 +00004722 // Simulate a contructor call...
4723 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004724 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004725
Steve Narofffa15fd92008-10-28 20:29:00 +00004726 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004727
Steve Narofffdc03722008-10-29 21:23:59 +00004728 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004729 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004730 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4731 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004732 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4733 CastExpr::CK_Unknown, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004734 InitExprs.push_back(castExpr);
4735
Steve Naroff01aec112009-12-06 21:14:13 +00004736 // Initialize the block descriptor.
4737 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004738
Steve Naroff01aec112009-12-06 21:14:13 +00004739 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4740 &Context->Idents.get(DescData.c_str()),
4741 Context->VoidPtrTy, 0,
4742 VarDecl::Static);
4743 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4744 new (Context) DeclRefExpr(NewVD,
4745 Context->VoidPtrTy, SourceLocation()),
4746 UnaryOperator::AddrOf,
4747 Context->getPointerType(Context->VoidPtrTy),
4748 SourceLocation());
4749 InitExprs.push_back(DescRefExpr);
4750
Steve Narofffa15fd92008-10-28 20:29:00 +00004751 // Add initializers for any closure decl refs.
4752 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004753 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004754 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004755 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004756 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004757 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004758 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004759 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004760 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004761 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004762 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004763 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004764 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4765 CastExpr::CK_Unknown, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004766 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004767 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004768 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004769 }
Mike Stump1eb44332009-09-09 15:08:12 +00004770 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004771 }
4772 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004773 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004774 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004775 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004776 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4777 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004778 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00004779 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004780 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004781 }
4782 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004783 if (ImportedBlockDecls.size()) {
4784 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4785 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004786 unsigned IntSize =
4787 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianff127882009-12-23 21:52:32 +00004788 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4789 Context->IntTy, SourceLocation());
4790 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004791 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004792 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4793 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004794 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004795 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00004796 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004797 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
4798 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004799 BlockDeclRefs.clear();
4800 BlockByRefDecls.clear();
4801 BlockByCopyDecls.clear();
4802 ImportedBlockDecls.clear();
4803 return NewRep;
4804}
4805
4806//===----------------------------------------------------------------------===//
4807// Function Body / Expression rewriting
4808//===----------------------------------------------------------------------===//
4809
Steve Naroffc77a6362008-12-04 16:24:46 +00004810// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4811// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4812// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4813// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4814// Since the rewriter isn't capable of rewriting rewritten code, it's important
4815// we get this right.
4816void RewriteObjC::CollectPropertySetters(Stmt *S) {
4817 // Perform a bottom up traversal of all children.
4818 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4819 CI != E; ++CI)
4820 if (*CI)
4821 CollectPropertySetters(*CI);
4822
4823 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4824 if (BinOp->isAssignmentOp()) {
4825 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4826 PropSetters[PRE] = BinOp;
4827 }
4828 }
4829}
4830
Steve Narofffa15fd92008-10-28 20:29:00 +00004831Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004832 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004833 isa<DoStmt>(S) || isa<ForStmt>(S))
4834 Stmts.push_back(S);
4835 else if (isa<ObjCForCollectionStmt>(S)) {
4836 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004837 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004838 }
Mike Stump1eb44332009-09-09 15:08:12 +00004839
Steve Narofffa15fd92008-10-28 20:29:00 +00004840 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004841
Steve Narofffa15fd92008-10-28 20:29:00 +00004842 // Perform a bottom up rewrite of all children.
4843 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4844 CI != E; ++CI)
4845 if (*CI) {
4846 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump1eb44332009-09-09 15:08:12 +00004847 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00004848 *CI = newStmt;
4849 }
Mike Stump1eb44332009-09-09 15:08:12 +00004850
Steve Narofffa15fd92008-10-28 20:29:00 +00004851 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4852 // Rewrite the block body in place.
4853 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00004854
Steve Narofffa15fd92008-10-28 20:29:00 +00004855 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00004856 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004857 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004858
Steve Narofffa15fd92008-10-28 20:29:00 +00004859 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4860 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004861 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004862 return blockTranscribed;
4863 }
4864 // Handle specific things.
4865 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4866 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004867
Steve Narofffa15fd92008-10-28 20:29:00 +00004868 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4869 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4870
Steve Naroffc77a6362008-12-04 16:24:46 +00004871 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4872 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4873 if (BinOp) {
4874 // Because the rewriter doesn't allow us to rewrite rewritten code,
4875 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004876 DisableReplaceStmt = true;
4877 // Save the source range. Even if we disable the replacement, the
4878 // rewritten node will have been inserted into the tree. If the synthesized
4879 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00004880 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00004881 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4882 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004883 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004884 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004885 //
4886 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4887 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4888 // to see the original expression). Consider this example:
4889 //
4890 // Foo *obj1, *obj2;
4891 //
4892 // obj1.i = [obj2 rrrr];
4893 //
4894 // 'BinOp' for the previous expression looks like:
4895 //
4896 // (BinaryOperator 0x231ccf0 'int' '='
4897 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4898 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4899 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4900 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4901 //
4902 // 'newStmt' represents the rewritten message expression. For example:
4903 //
4904 // (CallExpr 0x231d300 'id':'struct objc_object *'
4905 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4906 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4907 // (CStyleCastExpr 0x231d220 'void *'
4908 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4909 //
4910 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4911 // can be used as the setter argument. ReplaceStmt() will still 'see'
4912 // the original RHS (since we haven't altered BinOp).
4913 //
Mike Stump1eb44332009-09-09 15:08:12 +00004914 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00004915 // node. As a result, we now leak the original AST nodes.
4916 //
Steve Naroffb619d952008-12-09 12:56:34 +00004917 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004918 } else {
4919 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004920 }
4921 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004922 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4923 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004924
Steve Narofffa15fd92008-10-28 20:29:00 +00004925 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4926 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004927
Steve Narofffa15fd92008-10-28 20:29:00 +00004928 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004929#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004930 // Before we rewrite it, put the original message expression in a comment.
4931 SourceLocation startLoc = MessExpr->getLocStart();
4932 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004933
Steve Narofffa15fd92008-10-28 20:29:00 +00004934 const char *startBuf = SM->getCharacterData(startLoc);
4935 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004936
Steve Narofffa15fd92008-10-28 20:29:00 +00004937 std::string messString;
4938 messString += "// ";
4939 messString.append(startBuf, endBuf-startBuf+1);
4940 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004941
4942 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004943 // InsertText(clang::SourceLocation, char const*, unsigned int).
4944 // InsertText(startLoc, messString.c_str(), messString.size());
4945 // Tried this, but it didn't work either...
4946 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004947#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004948 return RewriteMessageExpr(MessExpr);
4949 }
Mike Stump1eb44332009-09-09 15:08:12 +00004950
Steve Narofffa15fd92008-10-28 20:29:00 +00004951 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4952 return RewriteObjCTryStmt(StmtTry);
4953
4954 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4955 return RewriteObjCSynchronizedStmt(StmtTry);
4956
4957 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4958 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004959
Steve Narofffa15fd92008-10-28 20:29:00 +00004960 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4961 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004962
4963 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004964 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004965 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004966 OrigStmtRange.getEnd());
4967 if (BreakStmt *StmtBreakStmt =
4968 dyn_cast<BreakStmt>(S))
4969 return RewriteBreakStmt(StmtBreakStmt);
4970 if (ContinueStmt *StmtContinueStmt =
4971 dyn_cast<ContinueStmt>(S))
4972 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004973
4974 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004975 // and cast exprs.
4976 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4977 // FIXME: What we're doing here is modifying the type-specifier that
4978 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004979 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004980 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4981 // the context of an ObjCForCollectionStmt. For example:
4982 // NSArray *someArray;
4983 // for (id <FooProtocol> index in someArray) ;
4984 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4985 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00004986 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004987 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004988
Steve Narofffa15fd92008-10-28 20:29:00 +00004989 // Blocks rewrite rules.
4990 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4991 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004992 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004993 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004994 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004995 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004996 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004997 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004998 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004999 if (VD->hasAttr<BlocksAttr>()) {
5000 static unsigned uniqueByrefDeclCount = 0;
5001 assert(!BlockByRefDeclNo.count(ND) &&
5002 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5003 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005004 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005005 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005006 }
5007 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005008 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005009 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005010 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005011 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5012 }
5013 }
5014 }
Mike Stump1eb44332009-09-09 15:08:12 +00005015
Steve Narofffa15fd92008-10-28 20:29:00 +00005016 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5017 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005018
5019 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005020 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5021 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005022 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5023 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005024 && "Statement stack mismatch");
5025 Stmts.pop_back();
5026 }
5027 // Handle blocks rewriting.
5028 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5029 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005030 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005031 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005032 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5033 ValueDecl *VD = DRE->getDecl();
5034 if (VD->hasAttr<BlocksAttr>())
5035 return RewriteBlockDeclRefExpr(DRE);
5036 }
5037
Steve Narofffa15fd92008-10-28 20:29:00 +00005038 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005039 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005040 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005041 ReplaceStmt(S, BlockCall);
5042 return BlockCall;
5043 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005044 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005045 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005046 RewriteCastExpr(CE);
5047 }
5048#if 0
5049 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00005050 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005051 // Get the new text.
5052 std::string SStr;
5053 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005054 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005055 const std::string &Str = Buf.str();
5056
5057 printf("CAST = %s\n", &Str[0]);
5058 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5059 delete S;
5060 return Replacement;
5061 }
5062#endif
5063 // Return this stmt unmodified.
5064 return S;
5065}
5066
Steve Naroff3d7e7862009-12-05 15:55:59 +00005067void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5068 for (RecordDecl::field_iterator i = RD->field_begin(),
5069 e = RD->field_end(); i != e; ++i) {
5070 FieldDecl *FD = *i;
5071 if (isTopLevelBlockPointerType(FD->getType()))
5072 RewriteBlockPointerDecl(FD);
5073 if (FD->getType()->isObjCQualifiedIdType() ||
5074 FD->getType()->isObjCQualifiedInterfaceType())
5075 RewriteObjCQualifiedInterfaceTypes(FD);
5076 }
5077}
5078
Steve Narofffa15fd92008-10-28 20:29:00 +00005079/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5080/// main file of the input.
5081void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5082 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005083 if (FD->isOverloadedOperator())
5084 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005085
Steve Narofffa15fd92008-10-28 20:29:00 +00005086 // Since function prototypes don't have ParmDecl's, we check the function
5087 // prototype. This enables us to rewrite function declarations and
5088 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005089 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005090
Sebastian Redld3a413d2009-04-26 20:35:05 +00005091 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005092 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005093 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005094 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005095 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005096 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005097 Body =
5098 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5099 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005100 CurrentBody = 0;
5101 if (PropParentMap) {
5102 delete PropParentMap;
5103 PropParentMap = 0;
5104 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005105 // This synthesizes and inserts the block "impl" struct, invoke function,
5106 // and any copy/dispose helper functions.
5107 InsertBlockLiteralsWithinFunction(FD);
5108 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005109 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005110 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005111 return;
5112 }
5113 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005114 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005115 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005116 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005117 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005118 Body =
5119 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5120 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005121 CurrentBody = 0;
5122 if (PropParentMap) {
5123 delete PropParentMap;
5124 PropParentMap = 0;
5125 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005126 InsertBlockLiteralsWithinMethod(MD);
5127 CurMethodDef = 0;
5128 }
5129 }
5130 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5131 ClassImplementation.push_back(CI);
5132 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5133 CategoryImplementation.push_back(CI);
5134 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5135 RewriteForwardClassDecl(CD);
5136 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5137 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005138 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005139 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005140 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005141 CheckFunctionPointerDecl(VD->getType(), VD);
5142 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005143 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005144 RewriteCastExpr(CE);
5145 }
5146 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005147 } else if (VD->getType()->isRecordType()) {
5148 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5149 if (RD->isDefinition())
5150 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005151 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005152 if (VD->getInit()) {
5153 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005154 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005155 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005156 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005157 CurrentBody = 0;
5158 if (PropParentMap) {
5159 delete PropParentMap;
5160 PropParentMap = 0;
5161 }
Mike Stump1eb44332009-09-09 15:08:12 +00005162 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00005163 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005164 GlobalVarDecl = 0;
5165
5166 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005167 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005168 RewriteCastExpr(CE);
5169 }
5170 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005171 return;
5172 }
5173 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005174 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005175 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005176 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005177 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroff3d7e7862009-12-05 15:55:59 +00005178 else if (TD->getUnderlyingType()->isRecordType()) {
5179 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5180 if (RD->isDefinition())
5181 RewriteRecordBody(RD);
5182 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005183 return;
5184 }
5185 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005186 if (RD->isDefinition())
5187 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005188 return;
5189 }
5190 // Nothing yet.
5191}
5192
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005193void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005194 // Get the top-level buffer that this corresponds to.
Mike Stump1eb44332009-09-09 15:08:12 +00005195
Steve Narofffa15fd92008-10-28 20:29:00 +00005196 // Rewrite tabs if we care.
5197 //RewriteTabs();
Mike Stump1eb44332009-09-09 15:08:12 +00005198
Steve Narofffa15fd92008-10-28 20:29:00 +00005199 if (Diags.hasErrorOccurred())
5200 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005201
Steve Narofffa15fd92008-10-28 20:29:00 +00005202 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005203
Steve Naroff621edce2009-04-29 16:37:50 +00005204 // Here's a great place to add any extra declarations that may be needed.
5205 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005206 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005207 E = ProtocolExprDecls.end(); I != E; ++I)
5208 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5209
Mike Stump1eb44332009-09-09 15:08:12 +00005210 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00005211 Preamble.c_str(), Preamble.size(), false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005212 if (ClassImplementation.size() || CategoryImplementation.size())
5213 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005214
Steve Narofffa15fd92008-10-28 20:29:00 +00005215 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5216 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005217 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005218 Rewrite.getRewriteBufferFor(MainFileID)) {
5219 //printf("Changed:\n");
5220 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5221 } else {
5222 fprintf(stderr, "No changes\n");
5223 }
Steve Narofface66252008-11-13 20:07:04 +00005224
Steve Naroff621edce2009-04-29 16:37:50 +00005225 if (ClassImplementation.size() || CategoryImplementation.size() ||
5226 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005227 // Rewrite Objective-c meta data*
5228 std::string ResultStr;
5229 SynthesizeMetaDataIntoBuffer(ResultStr);
5230 // Emit metadata.
5231 *OutFile << ResultStr;
5232 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005233 OutFile->flush();
5234}
5235