blob: 24ad69e3e0d386e4897d63573971547487847d62 [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"
Chris Lattner77cd2a02007-10-11 00:43:27 +000028using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000029using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000030
Chris Lattner77cd2a02007-10-11 00:43:27 +000031namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000032 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000033 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000034 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000035 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000036 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000037 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000038
Chris Lattner01c57482007-10-17 22:35:30 +000039 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000040 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000041 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000042 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000043 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000044 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000045
Ted Kremeneka526c5c2008-01-07 19:49:32 +000046 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
47 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
48 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000049 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000050 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
51 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000052 llvm::SmallVector<Stmt *, 32> Stmts;
53 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000054 // Remember all the @protocol(<expr>) expressions.
55 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Mike Stump1eb44332009-09-09 15:08:12 +000056
Steve Naroffd82a9ab2008-03-15 00:55:56 +000057 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000058
Steve Naroffebf2b562007-10-23 23:50:29 +000059 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000060 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000061 FunctionDecl *MsgSendStretFunctionDecl;
62 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000063 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000064 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000065 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000066 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000067 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000068 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Steve Naroffbeaf2992007-11-03 11:27:19 +000070 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000071 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000072 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +000073
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000074 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000075 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +000076
Steve Naroff874e2322007-11-15 10:28:18 +000077 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000078 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000079 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000080 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000081
Steve Naroff621edce2009-04-29 16:37:50 +000082 TypeDecl *ProtocolTypeDecl;
83 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +000084
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000085 // Needed for header files being rewritten
86 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +000087
Steve Naroffa7b402d2008-03-28 22:26:09 +000088 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +000089 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +000090
91 bool SilenceRewriteMacroWarning;
92
Steve Naroffba92b2e2008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000094
95 // Block expressions.
96 llvm::SmallVector<BlockExpr *, 32> Blocks;
97 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
98 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump1eb44332009-09-09 15:08:12 +000099
Steve Naroff54055232008-10-27 17:20:55 +0000100 // Block related declarations.
101 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
104
105 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
106
Steve Naroffc77a6362008-12-04 16:24:46 +0000107 // This maps a property to it's assignment statement.
108 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000109 // This maps a property to it's synthesied message expression.
110 // This allows us to rewrite chained getters (e.g. o.a.b.c).
111 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Steve Naroff4c3580e2008-12-04 23:50:32 +0000113 // This maps an original source AST to it's rewritten form. This allows
114 // us to avoid rewriting the same node twice (which is very uncommon).
115 // This is needed to support some of the exotic property rewriting.
116 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000117
Steve Naroff54055232008-10-27 17:20:55 +0000118 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000119 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Steve Naroffb619d952008-12-09 12:56:34 +0000121 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000122
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000123 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000124 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000125 virtual void Initialize(ASTContext &context);
126
Chris Lattnerf04da132007-10-24 17:06:59 +0000127 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000128 virtual void HandleTopLevelDecl(DeclGroupRef D) {
129 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
130 HandleTopLevelSingleDecl(*I);
131 }
132 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000133 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000134 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000135 Diagnostic &D, const LangOptions &LOpts,
136 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000137
138 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000140 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000142 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000143 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Steve Naroff4c3580e2008-12-04 23:50:32 +0000145 if (ReplacingStmt)
146 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000147
Steve Naroffb619d952008-12-09 12:56:34 +0000148 if (DisableReplaceStmt)
149 return; // Used when rewriting the assignment of a property setter.
150
Steve Naroff4c3580e2008-12-04 23:50:32 +0000151 // If replacement succeeded or warning disabled return with no warning.
152 if (!Rewrite.ReplaceStmt(Old, New)) {
153 ReplacedNodes[Old] = New;
154 return;
155 }
156 if (SilenceRewriteMacroWarning)
157 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000158 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
159 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000160 }
Steve Naroffb619d952008-12-09 12:56:34 +0000161
162 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
163 // Measaure the old text.
164 int Size = Rewrite.getRangeSize(SrcRange);
165 if (Size == -1) {
166 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
167 << Old->getSourceRange();
168 return;
169 }
170 // Get the new text.
171 std::string SStr;
172 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000173 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000174 const std::string &Str = S.str();
175
176 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000177 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000178 ReplacedNodes[Old] = New;
179 return;
180 }
181 if (SilenceRewriteMacroWarning)
182 return;
183 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
184 << Old->getSourceRange();
185 }
186
Steve Naroffba92b2e2008-03-27 22:29:16 +0000187 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
188 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000189 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000190 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
191 InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000192 SilenceRewriteMacroWarning)
193 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000195 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
196 }
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Chris Lattneraadaf782008-01-31 19:51:04 +0000198 void RemoveText(SourceLocation Loc, unsigned StrLen) {
199 // If removal succeeded or warning disabled return with no warning.
200 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
201 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Chris Lattneraadaf782008-01-31 19:51:04 +0000203 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
204 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000205
Chris Lattneraadaf782008-01-31 19:51:04 +0000206 void ReplaceText(SourceLocation Start, unsigned OrigLength,
207 const char *NewStr, unsigned NewLength) {
208 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000209 if (!Rewrite.ReplaceText(Start, OrigLength,
210 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000211 SilenceRewriteMacroWarning)
212 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Chris Lattneraadaf782008-01-31 19:51:04 +0000214 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
215 }
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Chris Lattnerf04da132007-10-24 17:06:59 +0000217 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000218 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000219 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000220 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000221 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000222 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
223 ObjCImplementationDecl *IMD,
224 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000225 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000226 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000227 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
228 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
229 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
230 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
231 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000232 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000233 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000234 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000235 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000236 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000237 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000238 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000239 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000240 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattnerf04da132007-10-24 17:06:59 +0000242 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000243 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000244 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Steve Naroff8599e7a2008-12-08 16:43:47 +0000246 Stmt *CurrentBody;
247 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000248
Chris Lattnere64b7772007-10-24 16:57:36 +0000249 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000250 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000251 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000252 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000253 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000254 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000255 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000256 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000257 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff8c565152008-12-05 17:03:39 +0000258 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000259 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000260 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000261 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
262 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
263 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000264 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
265 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000266 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff934f2762007-10-24 22:48:43 +0000267 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000268 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000269 Stmt *RewriteBreakStmt(BreakStmt *S);
270 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000271 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Steve Naroff09b266e2007-10-30 23:14:51 +0000273 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000274 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000275 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000276 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000277 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000278 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000279 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000280 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000281 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Chris Lattnerf04da132007-10-24 17:06:59 +0000283 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000284 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000285 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000287 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000288 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Douglas Gregor653f1b12009-04-23 01:02:12 +0000290 template<typename MethodIterator>
291 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
292 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000293 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000294 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000295 const char *ClassName,
296 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Steve Naroff621edce2009-04-29 16:37:50 +0000298 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
299 const char *prefix,
300 const char *ClassName,
301 std::string &Result);
302 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump1eb44332009-09-09 15:08:12 +0000303 const char *prefix,
Steve Naroff621edce2009-04-29 16:37:50 +0000304 const char *ClassName,
305 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000306 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000307 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000308 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
309 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000310 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000311 void RewriteImplementations();
312 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Steve Naroff54055232008-10-27 17:20:55 +0000314 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000315 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000316 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Steve Naroff54055232008-10-27 17:20:55 +0000318 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
319 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000320
321 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000322 void RewriteBlockCall(CallExpr *Exp);
323 void RewriteBlockPointerDecl(NamedDecl *VD);
Steve Naroff621edce2009-04-29 16:37:50 +0000324 Stmt *RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff54055232008-10-27 17:20:55 +0000325 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000326
327 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000328 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000329 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000330 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000331 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
Steve Naroff54055232008-10-27 17:20:55 +0000332 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000333 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000334 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
335 const char *FunName);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Steve Naroff54055232008-10-27 17:20:55 +0000337 void CollectBlockDeclRefInfo(BlockExpr *Exp);
338 void GetBlockCallExprs(Stmt *S);
339 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000340
Steve Naroff54055232008-10-27 17:20:55 +0000341 // We avoid calling Type::isBlockPointerType(), since it operates on the
342 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000343 bool isTopLevelBlockPointerType(QualType T) {
344 return isa<BlockPointerType>(T);
345 }
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Steve Naroff54055232008-10-27 17:20:55 +0000347 // FIXME: This predicate seems like it would be useful to add to ASTContext.
348 bool isObjCType(QualType T) {
349 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
350 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Steve Naroff54055232008-10-27 17:20:55 +0000352 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Steve Naroff54055232008-10-27 17:20:55 +0000354 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
355 OCT == Context->getCanonicalType(Context->getObjCClassType()))
356 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Ted Kremenek6217b802009-07-29 21:53:49 +0000358 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000359 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000360 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000361 return true;
362 }
363 return false;
364 }
365 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000366 void GetExtentOfArgList(const char *Name, const char *&LParen,
367 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000368 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Steve Narofffa15fd92008-10-28 20:29:00 +0000370 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000371 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Steve Naroff621edce2009-04-29 16:37:50 +0000373 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000374 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000375 if (From[i] == '"')
376 To += "\\\"";
377 else
378 To += From[i];
379 }
380 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000381 };
382}
383
Mike Stump1eb44332009-09-09 15:08:12 +0000384void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
385 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000386 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000387 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000388 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000389 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000390 // All the args are checked/rewritten. Don't call twice!
391 RewriteBlockPointerDecl(D);
392 break;
393 }
394 }
395}
396
397void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000398 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000399 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000400 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000401}
402
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000403static bool IsHeaderFile(const std::string &Filename) {
404 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000406 if (DotPos == std::string::npos) {
407 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000408 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000409 }
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000411 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
412 // C header: .h
413 // C++ header: .hh or .H;
414 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000415}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000416
Eli Friedman66d6f042009-05-18 22:20:00 +0000417RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000418 Diagnostic &D, const LangOptions &LOpts,
419 bool silenceMacroWarn)
420 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
421 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000422 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000423 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000424 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000425 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000426 "rewriter doesn't support user-specified control flow semantics "
427 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000428}
429
Eli Friedmanbce831b2009-05-18 22:29:17 +0000430ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
431 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000432 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000433 const LangOptions &LOpts,
434 bool SilenceRewriteMacroWarning) {
435 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000436}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000437
Steve Naroffb29b4272008-04-14 22:03:09 +0000438void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000439 Context = &context;
440 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000441 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000442 MsgSendFunctionDecl = 0;
443 MsgSendSuperFunctionDecl = 0;
444 MsgSendStretFunctionDecl = 0;
445 MsgSendSuperStretFunctionDecl = 0;
446 MsgSendFpretFunctionDecl = 0;
447 GetClassFunctionDecl = 0;
448 GetMetaClassFunctionDecl = 0;
449 SelGetUidFunctionDecl = 0;
450 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000451 ConstantStringClassReference = 0;
452 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000453 CurMethodDef = 0;
454 CurFunctionDef = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000455 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000456 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000457 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000458 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000459 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000460 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000461 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000462 PropParentMap = 0;
463 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000464 DisableReplaceStmt = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000466 // Get the ID and start/end of the main file.
467 MainFileID = SM->getMainFileID();
468 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
469 MainFileStart = MainBuf->getBufferStart();
470 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Chris Lattner2c78b872009-04-14 23:22:57 +0000472 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000474 // declaring objc_selector outside the parameter list removes a silly
475 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000476 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000477 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000478 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000479 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000480 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000481 if (LangOpts.Microsoft) {
482 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000483 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
484 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000485 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000486 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000487 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000488 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
489 Preamble += "typedef struct objc_object Protocol;\n";
490 Preamble += "#define _REWRITER_typedef_Protocol\n";
491 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000492 if (LangOpts.Microsoft) {
493 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
494 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
495 } else
496 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
497 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000498 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000499 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000500 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000501 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000502 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000503 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000504 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000505 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000506 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000507 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000508 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000509 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000510 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000511 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
512 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
513 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
514 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
515 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000516 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000517 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000518 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
519 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
520 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000521 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
522 Preamble += "struct __objcFastEnumerationState {\n\t";
523 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000524 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000525 Preamble += "unsigned long *mutationsPtr;\n\t";
526 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000527 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000528 Preamble += "#define __FASTENUMERATIONSTATE\n";
529 Preamble += "#endif\n";
530 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
531 Preamble += "struct __NSConstantStringImpl {\n";
532 Preamble += " int *isa;\n";
533 Preamble += " int flags;\n";
534 Preamble += " char *str;\n";
535 Preamble += " long length;\n";
536 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000537 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
538 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
539 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000540 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000541 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000542 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
543 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000544 // Blocks preamble.
545 Preamble += "#ifndef BLOCK_IMPL\n";
546 Preamble += "#define BLOCK_IMPL\n";
547 Preamble += "struct __block_impl {\n";
548 Preamble += " void *isa;\n";
549 Preamble += " int Flags;\n";
550 Preamble += " int Size;\n";
551 Preamble += " void *FuncPtr;\n";
552 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000553 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
554 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
555 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
556 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
557 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff54055232008-10-27 17:20:55 +0000558 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000559 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000560 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
561 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000562 Preamble += "#define __attribute__(X)\n";
563 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000564}
565
566
Chris Lattnerf04da132007-10-24 17:06:59 +0000567//===----------------------------------------------------------------------===//
568// Top Level Driver Code
569//===----------------------------------------------------------------------===//
570
Chris Lattner682bf922009-03-29 16:50:03 +0000571void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000572 // Two cases: either the decl could be in the main file, or it could be in a
573 // #included file. If the former, rewrite it now. If the later, check to see
574 // if we rewrote the #include/#import.
575 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000576 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000578 // If this is for a builtin, ignore it.
579 if (Loc.isInvalid()) return;
580
Steve Naroffebf2b562007-10-23 23:50:29 +0000581 // Look for built-in declarations that we need to refer during the rewrite.
582 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000583 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000584 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000585 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000586 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000587 ConstantStringClassReference = FVD;
588 return;
589 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000590 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000591 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000592 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000593 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000594 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000595 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000596 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000597 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000598 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000599 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
600 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000601 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
602 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000603 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000604 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000605 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000606 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000607 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000608 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000609}
610
Chris Lattnerf04da132007-10-24 17:06:59 +0000611//===----------------------------------------------------------------------===//
612// Syntactic (non-AST) Rewriting Code
613//===----------------------------------------------------------------------===//
614
Steve Naroffb29b4272008-04-14 22:03:09 +0000615void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000616 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000617 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
618 const char *MainBufStart = MainBuf.first;
619 const char *MainBufEnd = MainBuf.second;
620 size_t ImportLen = strlen("import");
621 size_t IncludeLen = strlen("include");
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000623 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000624 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
625 if (*BufPtr == '#') {
626 if (++BufPtr == MainBufEnd)
627 return;
628 while (*BufPtr == ' ' || *BufPtr == '\t')
629 if (++BufPtr == MainBufEnd)
630 return;
631 if (!strncmp(BufPtr, "import", ImportLen)) {
632 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000633 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000634 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000635 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000636 BufPtr += ImportLen;
637 }
638 }
639 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000640}
641
Steve Naroffb29b4272008-04-14 22:03:09 +0000642void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000643 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
644 const char *MainBufStart = MainBuf.first;
645 const char *MainBufEnd = MainBuf.second;
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattnerf04da132007-10-24 17:06:59 +0000647 // Loop over the whole file, looking for tabs.
648 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
649 if (*BufPtr != '\t')
650 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000651
Chris Lattnerf04da132007-10-24 17:06:59 +0000652 // Okay, we found a tab. This tab will turn into at least one character,
653 // but it depends on which 'virtual column' it is in. Compute that now.
654 unsigned VCol = 0;
655 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
656 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
657 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Chris Lattnerf04da132007-10-24 17:06:59 +0000659 // Okay, now that we know the virtual column, we know how many spaces to
660 // insert. We assume 8-character tab-stops.
661 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Chris Lattnerf04da132007-10-24 17:06:59 +0000663 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000664 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
665 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000666
Chris Lattnerf04da132007-10-24 17:06:59 +0000667 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000668 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000669 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000670}
671
Steve Naroffeb0646c2008-12-02 15:48:25 +0000672static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
673 ObjCIvarDecl *OID) {
674 std::string S;
675 S = "((struct ";
676 S += ClassDecl->getIdentifier()->getName();
677 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000678 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000679 return S;
680}
681
Steve Naroffa0876e82008-12-02 17:36:43 +0000682void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
683 ObjCImplementationDecl *IMD,
684 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000685 SourceLocation startLoc = PID->getLocStart();
686 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000687 const char *startBuf = SM->getCharacterData(startLoc);
688 assert((*startBuf == '@') && "bogus @synthesize location");
689 const char *semiBuf = strchr(startBuf, ';');
690 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000691 SourceLocation onePastSemiLoc =
692 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000693
694 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
695 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Steve Naroffeb0646c2008-12-02 15:48:25 +0000697 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000698 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000699 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000700 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000702 if (!OID)
703 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000704
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000705 std::string Getr;
706 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
707 Getr += "{ ";
708 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000709 // FIXME: deal with code generation implications for various property
710 // attributes (copy, retain, nonatomic).
Steve Naroff3539cdb2008-12-02 17:54:50 +0000711 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000712 Getr += "return " + getIvarAccessString(ClassDecl, OID);
713 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000714 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000715 if (PD->isReadOnly())
716 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Steve Naroffeb0646c2008-12-02 15:48:25 +0000718 // Generate the 'setter' function.
719 std::string Setr;
720 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000721 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000722 // Synthesize an explicit cast to initialize the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000723 // FIXME: deal with code generation implications for various property
724 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000725 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000726 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000727 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000728 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000729 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffd40910b2008-12-01 20:33:01 +0000730}
Chris Lattner8a12c272007-10-11 18:38:32 +0000731
Steve Naroffb29b4272008-04-14 22:03:09 +0000732void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000733 // Get the start location and compute the semi location.
734 SourceLocation startLoc = ClassDecl->getLocation();
735 const char *startBuf = SM->getCharacterData(startLoc);
736 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Chris Lattnerf04da132007-10-24 17:06:59 +0000738 // Translate to typedef's that forward reference structs with the same name
739 // as the class. As a convenience, we include the original declaration
740 // as a comment.
741 std::string typedefString;
742 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000743 typedefString.append(startBuf, semiPtr-startBuf+1);
744 typedefString += "\n";
Chris Lattner67956052009-02-20 18:04:31 +0000745 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
746 I != E; ++I) {
747 ObjCInterfaceDecl *ForwardDecl = *I;
Steve Naroff32174822007-11-09 12:50:28 +0000748 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000749 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000750 typedefString += "\n";
751 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000752 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000753 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000754 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000755 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000756 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000757 }
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Steve Naroff934f2762007-10-24 22:48:43 +0000759 // Replace the @class with typedefs corresponding to the classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000760 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattneraadaf782008-01-31 19:51:04 +0000761 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000762}
763
Steve Naroffb29b4272008-04-14 22:03:09 +0000764void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000765 SourceLocation LocStart = Method->getLocStart();
766 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Chris Lattner30fc9332009-02-04 01:06:56 +0000768 if (SM->getInstantiationLineNumber(LocEnd) >
769 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000770 InsertText(LocStart, "#if 0\n", 6);
771 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000772 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000773 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000774 }
775}
776
Mike Stump1eb44332009-09-09 15:08:12 +0000777void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff6327e0d2009-01-11 01:06:09 +0000778 SourceLocation Loc = prop->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Steve Naroff6327e0d2009-01-11 01:06:09 +0000780 ReplaceText(Loc, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Steve Naroff6327e0d2009-01-11 01:06:09 +0000782 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000783}
784
Steve Naroffb29b4272008-04-14 22:03:09 +0000785void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000786 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Steve Naroff423cb562007-10-30 13:30:57 +0000788 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000789 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000790
791 for (ObjCCategoryDecl::instmeth_iterator
792 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000793 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000794 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000795 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000796 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000797 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000798 RewriteMethodDeclaration(*I);
799
Steve Naroff423cb562007-10-30 13:30:57 +0000800 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000801 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000802}
803
Steve Naroffb29b4272008-04-14 22:03:09 +0000804void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000805 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Steve Naroff752d6ef2007-10-30 16:42:30 +0000807 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Steve Naroff752d6ef2007-10-30 16:42:30 +0000809 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000810 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000811
812 for (ObjCProtocolDecl::instmeth_iterator
813 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000814 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000815 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000816 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000817 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000818 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000819 RewriteMethodDeclaration(*I);
820
Steve Naroff752d6ef2007-10-30 16:42:30 +0000821 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000822 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000823 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000824
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000825 // Must comment out @optional/@required
826 const char *startBuf = SM->getCharacterData(LocStart);
827 const char *endBuf = SM->getCharacterData(LocEnd);
828 for (const char *p = startBuf; p < endBuf; p++) {
829 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
830 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000831 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000832 ReplaceText(OptionalLoc, strlen("@optional"),
833 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000835 }
836 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
837 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000838 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000839 ReplaceText(OptionalLoc, strlen("@required"),
840 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000842 }
843 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000844}
845
Steve Naroffb29b4272008-04-14 22:03:09 +0000846void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000847 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000848 if (LocStart.isInvalid())
849 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000850 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000851 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000852}
853
Mike Stump1eb44332009-09-09 15:08:12 +0000854void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000855 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000856 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000857 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000858 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000859 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000860 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000861 else if (OMD->getResultType()->isFunctionPointerType() ||
862 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000863 // needs special handling, since pointer-to-functions have special
864 // syntax (where a decaration models use).
865 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000866 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +0000867 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000868 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000869 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000870 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +0000871 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Narofff4312dc2008-12-11 19:29:16 +0000872 ResultStr += FPRetType->getResultType().getAsString();
873 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000874 }
875 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000876 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000877 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000879 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000880 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000881
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000882 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000883 NameStr += "_I_";
884 else
885 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000887 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000888 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +0000889
890 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000891 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000892 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000893 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000894 }
Mike Stump1eb44332009-09-09 15:08:12 +0000895 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000896 {
897 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000898 int len = selString.size();
899 for (int i = 0; i < len; i++)
900 if (selString[i] == ':')
901 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000902 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000903 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000904 // Remember this name for metadata emission
905 MethodInternalNames[OMD] = NameStr;
906 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000908 // Rewrite arguments
909 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000911 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000912 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000913 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000914 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000915 if (!LangOpts.Microsoft) {
916 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
917 ResultStr += "struct ";
918 }
919 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000920 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000921 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000922 }
923 else
Steve Naroff621edce2009-04-29 16:37:50 +0000924 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000926 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000927 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000928 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000930 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +0000931 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
932 E = OMD->param_end(); PI != E; ++PI) {
933 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000934 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000935 if (PDecl->getType()->isObjCQualifiedIdType()) {
936 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000937 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000938 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000939 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000940 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000941 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek6217b802009-07-29 21:53:49 +0000942 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000943 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
944 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000945 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000946 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +0000947 ResultStr += Name;
948 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000949 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000950 if (OMD->isVariadic())
951 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000952 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Steve Naroff76e429d2008-07-16 14:40:40 +0000954 if (FPRetType) {
955 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Steve Naroff76e429d2008-07-16 14:40:40 +0000957 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +0000958 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000959 ResultStr += "(";
960 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
961 if (i) ResultStr += ", ";
962 std::string ParamStr = FT->getArgType(i).getAsString();
963 ResultStr += ParamStr;
964 }
965 if (FT->isVariadic()) {
966 if (FT->getNumArgs()) ResultStr += ", ";
967 ResultStr += "...";
968 }
969 ResultStr += ")";
970 } else {
971 ResultStr += "()";
972 }
973 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000974}
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000975void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000976 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
977 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000979 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000980 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000981 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000982 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000984 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000985 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
986 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +0000987 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000988 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000989 ObjCMethodDecl *OMD = *I;
990 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000991 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000992 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +0000993
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000994 const char *startBuf = SM->getCharacterData(LocStart);
995 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000996 ReplaceText(LocStart, endBuf-startBuf,
997 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000998 }
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001000 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001001 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1002 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001003 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001004 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001005 ObjCMethodDecl *OMD = *I;
1006 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001007 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001008 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001010 const char *startBuf = SM->getCharacterData(LocStart);
1011 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001012 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump1eb44332009-09-09 15:08:12 +00001013 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001014 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001015 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001016 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001017 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001018 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001019 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001020 }
1021
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001022 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001023 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001024 else
Mike Stump1eb44332009-09-09 15:08:12 +00001025 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001026}
1027
Steve Naroffb29b4272008-04-14 22:03:09 +00001028void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001029 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001030 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001031 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001032 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001033 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001034 ResultStr += "\n";
1035 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001036 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001037 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001038 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001039 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001040 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001041 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001042 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001043 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001044 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001045
1046 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001047 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001048 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001049 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001050 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001051 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001052 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001053 for (ObjCInterfaceDecl::classmeth_iterator
1054 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001055 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001056 RewriteMethodDeclaration(*I);
1057
Steve Naroff2feac5e2007-10-30 03:43:13 +00001058 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001059 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001060}
1061
Steve Naroffb619d952008-12-09 12:56:34 +00001062Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1063 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001064 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1065 // This allows us to reuse all the fun and games in SynthMessageExpr().
1066 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1067 ObjCMessageExpr *MsgExpr;
1068 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1069 llvm::SmallVector<Expr *, 1> ExprVec;
1070 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Steve Naroff8599e7a2008-12-08 16:43:47 +00001072 Stmt *Receiver = PropRefExpr->getBase();
1073 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1074 if (PRE && PropGetters[PRE]) {
1075 // This allows us to handle chain/nested property getters.
1076 Receiver = PropGetters[PRE];
1077 }
Mike Stump1eb44332009-09-09 15:08:12 +00001078 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1079 PDecl->getSetterName(), PDecl->getType(),
1080 PDecl->getSetterMethodDecl(),
1081 SourceLocation(), SourceLocation(),
Steve Naroffc77a6362008-12-04 16:24:46 +00001082 &ExprVec[0], 1);
1083 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Steve Naroffc77a6362008-12-04 16:24:46 +00001085 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001086 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001087 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001088 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1089 // to things that stay around.
1090 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001091 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001092}
1093
Steve Naroffc77a6362008-12-04 16:24:46 +00001094Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001095 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1096 // This allows us to reuse all the fun and games in SynthMessageExpr().
1097 ObjCMessageExpr *MsgExpr;
1098 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Steve Naroff8599e7a2008-12-08 16:43:47 +00001100 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Steve Naroff8599e7a2008-12-08 16:43:47 +00001102 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1103 if (PRE && PropGetters[PRE]) {
1104 // This allows us to handle chain/nested property getters.
1105 Receiver = PropGetters[PRE];
1106 }
Mike Stump1eb44332009-09-09 15:08:12 +00001107 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1108 PDecl->getGetterName(), PDecl->getType(),
1109 PDecl->getGetterMethodDecl(),
1110 SourceLocation(), SourceLocation(),
Steve Naroff15f081d2008-12-03 00:56:33 +00001111 0, 0);
1112
Steve Naroff4c3580e2008-12-04 23:50:32 +00001113 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001114
1115 if (!PropParentMap)
1116 PropParentMap = new ParentMap(CurrentBody);
1117
1118 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1119 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1120 // We stash away the ReplacingStmt since actually doing the
1121 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1122 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001123 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1124 // to things that stay around.
1125 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001126 return PropRefExpr; // return the original...
1127 } else {
1128 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001129 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001130 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1131 // to things that stay around.
1132 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001133 return ReplacingStmt;
1134 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001135}
1136
Mike Stump1eb44332009-09-09 15:08:12 +00001137Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001138 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001139 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001140 if (CurMethodDef) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001141 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001142 ObjCInterfaceType *iFaceDecl =
1143 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Narofff0757612008-05-08 17:52:16 +00001144 // lookup which class implements the instance variable.
1145 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001146 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001147 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001148 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Steve Narofff0757612008-05-08 17:52:16 +00001150 // Synthesize an explicit cast to gain access to the ivar.
1151 std::string RecName = clsDeclared->getIdentifier()->getName();
1152 RecName += "_IMPL";
1153 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001154 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001155 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001156 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1157 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump1eb44332009-09-09 15:08:12 +00001158 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001159 CastExpr::CK_Unknown,
1160 IV->getBase(),
1161 castT,SourceLocation(),
1162 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001163 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001164 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1165 IV->getBase()->getLocEnd(),
1166 castExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001167 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001168 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001169 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1170 IV->getLocation(),
1171 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001172 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001173 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001174 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001175 }
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001177 ReplaceStmt(IV->getBase(), PE);
1178 // Cannot delete IV->getBase(), since PE points to it.
1179 // Replace the old base with the cast. This is important when doing
1180 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001181 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001182 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001183 }
Steve Naroff84472a82008-04-18 21:55:08 +00001184 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001185 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Steve Naroff9f525972008-05-06 23:20:07 +00001187 // Explicit ivar refs need to have a cast inserted.
1188 // FIXME: consider sharing some of this code with the code above.
Ted Kremenek6217b802009-07-29 21:53:49 +00001189 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Narofff0757612008-05-08 17:52:16 +00001190 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001191 // lookup which class implements the instance variable.
1192 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001193 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001194 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001195 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001196
Steve Naroff9f525972008-05-06 23:20:07 +00001197 // Synthesize an explicit cast to gain access to the ivar.
1198 std::string RecName = clsDeclared->getIdentifier()->getName();
1199 RecName += "_IMPL";
1200 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001201 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001202 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001203 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1204 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump1eb44332009-09-09 15:08:12 +00001205 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001206 CastExpr::CK_Unknown,
1207 IV->getBase(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00001208 castT, SourceLocation(),
1209 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001210 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001211 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001212 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001213 ReplaceStmt(IV->getBase(), PE);
1214 // Cannot delete IV->getBase(), since PE points to it.
1215 // Replace the old base with the cast. This is important when doing
1216 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001217 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001218 return IV;
1219 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001220 }
Steve Naroff84472a82008-04-18 21:55:08 +00001221 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001222}
1223
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001224/// SynthCountByEnumWithState - To print:
1225/// ((unsigned int (*)
1226/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001227/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001228/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001229/// "countByEnumeratingWithState:objects:count:"),
1230/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001231/// (id *)items, (unsigned int)16)
1232///
Steve Naroffb29b4272008-04-14 22:03:09 +00001233void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001234 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1235 "id *, unsigned int))(void *)objc_msgSend)";
1236 buf += "\n\t\t";
1237 buf += "((id)l_collection,\n\t\t";
1238 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1239 buf += "\n\t\t";
1240 buf += "&enumState, "
1241 "(id *)items, (unsigned int)16)";
1242}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001243
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001244/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1245/// statement to exit to its outer synthesized loop.
1246///
Steve Naroffb29b4272008-04-14 22:03:09 +00001247Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001248 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1249 return S;
1250 // replace break with goto __break_label
1251 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001253 SourceLocation startLoc = S->getLocStart();
1254 buf = "goto __break_label_";
1255 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001256 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001257
1258 return 0;
1259}
1260
1261/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1262/// statement to continue with its inner synthesized loop.
1263///
Steve Naroffb29b4272008-04-14 22:03:09 +00001264Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001265 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1266 return S;
1267 // replace continue with goto __continue_label
1268 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001270 SourceLocation startLoc = S->getLocStart();
1271 buf = "goto __continue_label_";
1272 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001273 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001275 return 0;
1276}
1277
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001278/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001279/// It rewrites:
1280/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001282/// Into:
1283/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001284/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001285/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001286/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001287/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001288/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001289/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001290/// if (limit) {
1291/// unsigned long startMutations = *enumState.mutationsPtr;
1292/// do {
1293/// unsigned long counter = 0;
1294/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001295/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001296/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001297/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001298/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001299/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001300/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001301/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001302/// objects:items count:16]);
1303/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001304/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001305/// }
1306/// else
1307/// elem = nil;
1308/// }
1309///
Steve Naroffb29b4272008-04-14 22:03:09 +00001310Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001311 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001312 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001313 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001314 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001315 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001316 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001318 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001319 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001320 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001321 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001322 std::string buf;
1323 buf = "\n{\n\t";
1324 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1325 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001326 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001327 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001328 elementTypeAsString = ElementType.getAsString();
1329 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001330 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001331 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001332 buf += elementName;
1333 buf += ";\n\t";
1334 }
Chris Lattner06767512008-04-08 05:52:18 +00001335 else {
1336 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001337 elementName = DR->getDecl()->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00001338 elementTypeAsString
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001339 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001340 }
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001342 // struct __objcFastEnumerationState enumState = { 0 };
1343 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1344 // id items[16];
1345 buf += "id items[16];\n\t";
1346 // id l_collection = (id)
1347 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001348 // Find start location of 'collection' the hard way!
1349 const char *startCollectionBuf = startBuf;
1350 startCollectionBuf += 3; // skip 'for'
1351 startCollectionBuf = strchr(startCollectionBuf, '(');
1352 startCollectionBuf++; // skip '('
1353 // find 'in' and skip it.
1354 while (*startCollectionBuf != ' ' ||
1355 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1356 (*(startCollectionBuf+3) != ' ' &&
1357 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1358 startCollectionBuf++;
1359 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001360
1361 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001362 ReplaceText(startLoc, startCollectionBuf - startBuf,
1363 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001364 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001365 SourceLocation rightParenLoc = S->getRParenLoc();
1366 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1367 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001368 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001369
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001370 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1371 // objects:items count:16];
1372 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001373 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001374 // ((unsigned int (*)
1375 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001376 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001377 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001378 // "countByEnumeratingWithState:objects:count:"),
1379 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001380 // (id *)items, (unsigned int)16);
1381 buf += "unsigned long limit =\n\t\t";
1382 SynthCountByEnumWithState(buf);
1383 buf += ";\n\t";
1384 /// if (limit) {
1385 /// unsigned long startMutations = *enumState.mutationsPtr;
1386 /// do {
1387 /// unsigned long counter = 0;
1388 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001389 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001390 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001391 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001392 buf += "if (limit) {\n\t";
1393 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1394 buf += "do {\n\t\t";
1395 buf += "unsigned long counter = 0;\n\t\t";
1396 buf += "do {\n\t\t\t";
1397 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1398 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1399 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001400 buf += " = (";
1401 buf += elementTypeAsString;
1402 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001403 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001404 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001406 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001407 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001408 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001409 /// objects:items count:16]);
1410 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001411 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001412 /// }
1413 /// else
1414 /// elem = nil;
1415 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001416 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001417 buf = ";\n\t";
1418 buf += "__continue_label_";
1419 buf += utostr(ObjCBcLabelNo.back());
1420 buf += ": ;";
1421 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001422 buf += "} while (counter < limit);\n\t";
1423 buf += "} while (limit = ";
1424 SynthCountByEnumWithState(buf);
1425 buf += ");\n\t";
1426 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001427 buf += " = ((id)0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001428 buf += "__break_label_";
1429 buf += utostr(ObjCBcLabelNo.back());
1430 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001431 buf += "}\n\t";
1432 buf += "else\n\t\t";
1433 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001434 buf += " = ((id)0);\n";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001435 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001437 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001438 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001439 if (isa<CompoundStmt>(S->getBody())) {
1440 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1441 InsertText(endBodyLoc, buf.c_str(), buf.size());
1442 } else {
1443 /* Need to treat single statements specially. For example:
1444 *
1445 * for (A *a in b) if (stuff()) break;
1446 * for (A *a in b) xxxyy;
1447 *
1448 * The following code simply scans ahead to the semi to find the actual end.
1449 */
1450 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1451 const char *semiBuf = strchr(stmtBuf, ';');
1452 assert(semiBuf && "Can't find ';'");
1453 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1454 InsertText(endBodyLoc, buf.c_str(), buf.size());
1455 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001456 Stmts.pop_back();
1457 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001458 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001459}
1460
Mike Stump1eb44332009-09-09 15:08:12 +00001461/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001462/// This routine rewrites @synchronized(expr) stmt;
1463/// into:
1464/// objc_sync_enter(expr);
1465/// @try stmt @finally { objc_sync_exit(expr); }
1466///
Steve Naroffb29b4272008-04-14 22:03:09 +00001467Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001468 // Get the start location and compute the semi location.
1469 SourceLocation startLoc = S->getLocStart();
1470 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001472 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001473
1474 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001475 buf = "objc_sync_enter((id)";
1476 const char *lparenBuf = startBuf;
1477 while (*lparenBuf != '(') lparenBuf++;
1478 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001479 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1480 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001481 // been rewritten! (which implies the SourceLocation's are invalid).
1482 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001483 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001484 while (*endBuf != ')') endBuf--;
1485 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001486 buf = ");\n";
1487 // declare a new scope with two variables, _stack and _rethrow.
1488 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1489 buf += "int buf[18/*32-bit i386*/];\n";
1490 buf += "char *pointers[4];} _stack;\n";
1491 buf += "id volatile _rethrow = 0;\n";
1492 buf += "objc_exception_try_enter(&_stack);\n";
1493 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001494 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001495 startLoc = S->getSynchBody()->getLocEnd();
1496 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Steve Naroffc7089f12008-08-19 13:04:19 +00001498 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001499 SourceLocation lastCurlyLoc = startLoc;
1500 buf = "}\nelse {\n";
1501 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001502 buf += "}\n";
1503 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001504 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001505 buf += " objc_sync_exit(";
Mike Stump1eb44332009-09-09 15:08:12 +00001506 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001507 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00001508 S->getSynchExpr(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00001509 Context->getObjCIdType(),
1510 SourceLocation(),
1511 SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001512 std::string syncExprBufS;
1513 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001514 syncExpr->printPretty(syncExprBuf, *Context, 0,
1515 PrintingPolicy(LangOpts));
Steve Naroffb2a39452008-07-16 19:47:39 +00001516 buf += syncExprBuf.str();
1517 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001518 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1519 buf += "}\n";
1520 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Chris Lattneraadaf782008-01-31 19:51:04 +00001522 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001523 return 0;
1524}
1525
Mike Stump1eb44332009-09-09 15:08:12 +00001526void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
Steve Naroff8c565152008-12-05 17:03:39 +00001527 // Perform a bottom up traversal of all children.
1528 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1529 CI != E; ++CI)
1530 if (*CI)
1531 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1532
Mike Stump1eb44332009-09-09 15:08:12 +00001533 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
Steve Naroff8c565152008-12-05 17:03:39 +00001534 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001535 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001536 TryFinallyContainsReturnDiag);
1537 }
1538 return;
1539}
1540
Steve Naroffb29b4272008-04-14 22:03:09 +00001541Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001542 // Get the start location and compute the semi location.
1543 SourceLocation startLoc = S->getLocStart();
1544 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Steve Naroff75730982007-11-07 04:08:17 +00001546 assert((*startBuf == '@') && "bogus @try location");
1547
1548 std::string buf;
1549 // declare a new scope with two variables, _stack and _rethrow.
1550 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1551 buf += "int buf[18/*32-bit i386*/];\n";
1552 buf += "char *pointers[4];} _stack;\n";
1553 buf += "id volatile _rethrow = 0;\n";
1554 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001555 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001556
Chris Lattneraadaf782008-01-31 19:51:04 +00001557 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Steve Naroff75730982007-11-07 04:08:17 +00001559 startLoc = S->getTryBody()->getLocEnd();
1560 startBuf = SM->getCharacterData(startLoc);
1561
1562 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Steve Naroff75730982007-11-07 04:08:17 +00001564 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001565 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1566 if (catchList) {
1567 startLoc = startLoc.getFileLocWithOffset(1);
1568 buf = " /* @catch begin */ else {\n";
1569 buf += " id _caught = objc_exception_extract(&_stack);\n";
1570 buf += " objc_exception_try_enter (&_stack);\n";
1571 buf += " if (_setjmp(_stack.buf))\n";
1572 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1573 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Steve Naroffc9ba1722008-07-16 15:31:30 +00001575 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001576 } else { /* no catch list */
1577 buf = "}\nelse {\n";
1578 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1579 buf += "}";
1580 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001581 }
Steve Naroff75730982007-11-07 04:08:17 +00001582 bool sawIdTypedCatch = false;
1583 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001584 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001585 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001586
Mike Stump1eb44332009-09-09 15:08:12 +00001587 if (catchList == S->getCatchStmts())
Steve Naroff75730982007-11-07 04:08:17 +00001588 buf = "if ("; // we are generating code for the first catch clause
1589 else
1590 buf = "else if (";
1591 startLoc = catchList->getLocStart();
1592 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Steve Naroff75730982007-11-07 04:08:17 +00001594 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Steve Naroff75730982007-11-07 04:08:17 +00001596 const char *lParenLoc = strchr(startBuf, '(');
1597
Steve Naroffbe4b3332008-02-01 22:08:12 +00001598 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001599 // Now rewrite the body...
1600 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001601 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1602 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001603 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1604 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001605 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Steve Naroffe12e6922008-02-01 20:02:07 +00001607 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001608 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001609 } else if (catchDecl) {
1610 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001611 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001612 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001613 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001614 sawIdTypedCatch = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001615 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001616 ObjCInterfaceType *cls; // Should be a pointer to a class.
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001618 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001619 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001620 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001621 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001622 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001623 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001624 }
1625 }
1626 // Now rewrite the body...
1627 lastCatchBody = catchList->getCatchBody();
1628 SourceLocation rParenLoc = catchList->getRParenLoc();
1629 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1630 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1631 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1632 assert((*rParenBuf == ')') && "bogus @catch paren location");
1633 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Steve Naroff75730982007-11-07 04:08:17 +00001635 buf = " = _caught;";
Mike Stump1eb44332009-09-09 15:08:12 +00001636 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001637 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001638 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001639 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001640 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001641 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001642 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001643 catchList = catchList->getNextCatchStmt();
1644 }
1645 // Complete the catch list...
1646 if (lastCatchBody) {
1647 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001648 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1649 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Steve Naroff378f47a2008-09-11 15:29:03 +00001651 // Insert the last (implicit) else clause *before* the right curly brace.
1652 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1653 buf = "} /* last catch end */\n";
1654 buf += "else {\n";
1655 buf += " _rethrow = _caught;\n";
1656 buf += " objc_exception_try_exit(&_stack);\n";
1657 buf += "} } /* @catch end */\n";
1658 if (!S->getFinallyStmt())
1659 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001660 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Steve Naroff75730982007-11-07 04:08:17 +00001662 // Set lastCurlyLoc
1663 lastCurlyLoc = lastCatchBody->getLocEnd();
1664 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001665 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001666 startLoc = finalStmt->getLocStart();
1667 startBuf = SM->getCharacterData(startLoc);
1668 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Steve Naroff75730982007-11-07 04:08:17 +00001670 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001671 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Steve Naroff75730982007-11-07 04:08:17 +00001673 Stmt *body = finalStmt->getFinallyBody();
1674 SourceLocation startLoc = body->getLocStart();
1675 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001676 assert(*SM->getCharacterData(startLoc) == '{' &&
1677 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001678 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001679 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001680
Steve Naroff75730982007-11-07 04:08:17 +00001681 startLoc = startLoc.getFileLocWithOffset(1);
1682 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001683 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001684 endLoc = endLoc.getFileLocWithOffset(-1);
1685 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001686 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Steve Naroff75730982007-11-07 04:08:17 +00001688 // Set lastCurlyLoc
1689 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Steve Naroff8c565152008-12-05 17:03:39 +00001691 // Now check for any return/continue/go statements within the @try.
1692 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001693 } else { /* no finally clause - make sure we synthesize an implicit one */
1694 buf = "{ /* implicit finally clause */\n";
1695 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1696 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1697 buf += "}";
1698 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001699 }
1700 // Now emit the final closing curly brace...
1701 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1702 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001703 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001704 return 0;
1705}
1706
Steve Naroffb29b4272008-04-14 22:03:09 +00001707Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001708 return 0;
1709}
1710
Steve Naroffb29b4272008-04-14 22:03:09 +00001711Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001712 return 0;
1713}
1714
Mike Stump1eb44332009-09-09 15:08:12 +00001715// This can't be done with ReplaceStmt(S, ThrowExpr), since
1716// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001717// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001718Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001719 // Get the start location and compute the semi location.
1720 SourceLocation startLoc = S->getLocStart();
1721 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Steve Naroff2bd03922007-11-07 15:32:26 +00001723 assert((*startBuf == '@') && "bogus @throw location");
1724
1725 std::string buf;
1726 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001727 if (S->getThrowExpr())
1728 buf = "objc_exception_throw(";
1729 else // add an implicit argument
1730 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001732 // handle "@ throw" correctly.
1733 const char *wBuf = strchr(startBuf, 'w');
1734 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1735 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Steve Naroff2bd03922007-11-07 15:32:26 +00001737 const char *semiBuf = strchr(startBuf, ';');
1738 assert((*semiBuf == ';') && "@throw: can't find ';'");
1739 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1740 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001741 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001742 return 0;
1743}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001744
Steve Naroffb29b4272008-04-14 22:03:09 +00001745Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001746 // Create a new string expression.
1747 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001748 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001749 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001750 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1751 StrEncoding.length(), false,StrType,
1752 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001753 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001754
Chris Lattner07506182007-11-30 22:53:43 +00001755 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001756 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001757 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001758}
1759
Steve Naroffb29b4272008-04-14 22:03:09 +00001760Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001761 if (!SelGetUidFunctionDecl)
1762 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001763 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1764 // Create a call to sel_registerName("selName").
1765 llvm::SmallVector<Expr*, 8> SelExprs;
1766 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001767 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001768 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001769 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001770 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001771 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1772 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001773 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001774 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001775 return SelExp;
1776}
1777
Steve Naroffb29b4272008-04-14 22:03:09 +00001778CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001779 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001780 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001781 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Steve Naroffebf2b562007-10-23 23:50:29 +00001783 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001784 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Steve Naroffebf2b562007-10-23 23:50:29 +00001786 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001787 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump1eb44332009-09-09 15:08:12 +00001788 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001789 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00001790 DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001791 /*isLvalue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001792
John McCall183700f2009-09-21 23:43:11 +00001793 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Ted Kremenek668bf912009-02-09 20:51:47 +00001795 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1796 SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001797}
1798
Steve Naroffd5255f52007-11-01 13:24:47 +00001799static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1800 const char *&startRef, const char *&endRef) {
1801 while (startBuf < endBuf) {
1802 if (*startBuf == '<')
1803 startRef = startBuf; // mark the start.
1804 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001805 if (startRef && *startRef == '<') {
1806 endRef = startBuf; // mark the end.
1807 return true;
1808 }
1809 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001810 }
1811 startBuf++;
1812 }
1813 return false;
1814}
1815
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001816static void scanToNextArgument(const char *&argRef) {
1817 int angle = 0;
1818 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1819 if (*argRef == '<')
1820 angle++;
1821 else if (*argRef == '>')
1822 angle--;
1823 argRef++;
1824 }
1825 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1826}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001827
Steve Naroffb29b4272008-04-14 22:03:09 +00001828bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001829 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroffd5255f52007-11-01 13:24:47 +00001830}
1831
Steve Naroff4f95b752008-07-29 18:15:38 +00001832void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1833 QualType Type = E->getType();
1834 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001835 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00001836
Steve Naroffcda658e2008-11-19 21:15:47 +00001837 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1838 Loc = ECE->getLParenLoc();
1839 EndLoc = ECE->getRParenLoc();
1840 } else {
1841 Loc = E->getLocStart();
1842 EndLoc = E->getLocEnd();
1843 }
1844 // This will defend against trying to rewrite synthesized expressions.
1845 if (Loc.isInvalid() || EndLoc.isInvalid())
1846 return;
1847
Steve Naroff4f95b752008-07-29 18:15:38 +00001848 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001849 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001850 const char *startRef = 0, *endRef = 0;
1851 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1852 // Get the locations of the startRef, endRef.
1853 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1854 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1855 // Comment out the protocol references.
1856 InsertText(LessLoc, "/*", 2);
1857 InsertText(GreaterLoc, "*/", 2);
1858 }
1859 }
1860}
1861
Steve Naroffb29b4272008-04-14 22:03:09 +00001862void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001863 SourceLocation Loc;
1864 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00001865 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001866 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1867 Loc = VD->getLocation();
1868 Type = VD->getType();
1869 }
1870 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1871 Loc = FD->getLocation();
1872 // Check for ObjC 'id' and class types that have been adorned with protocol
1873 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00001874 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001875 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00001876 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001877 if (!proto)
1878 return;
1879 Type = proto->getResultType();
1880 }
1881 else
1882 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001884 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001885 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Steve Naroffd5255f52007-11-01 13:24:47 +00001887 const char *endBuf = SM->getCharacterData(Loc);
1888 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001889 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001890 startBuf--; // scan backward (from the decl location) for return type.
1891 const char *startRef = 0, *endRef = 0;
1892 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1893 // Get the locations of the startRef, endRef.
1894 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1895 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1896 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001897 InsertText(LessLoc, "/*", 2);
1898 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001899 }
1900 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001901 if (!proto)
1902 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001903 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001904 const char *startBuf = SM->getCharacterData(Loc);
1905 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001906 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1907 if (needToScanForQualifiers(proto->getArgType(i))) {
1908 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Steve Naroffd5255f52007-11-01 13:24:47 +00001910 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001911 // scan forward (from the decl location) for argument types.
1912 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001913 const char *startRef = 0, *endRef = 0;
1914 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1915 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00001916 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001917 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001918 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001919 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001920 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001921 InsertText(LessLoc, "/*", 2);
1922 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001923 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001924 startBuf = ++endBuf;
1925 }
1926 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001927 // If the function name is derived from a macro expansion, then the
1928 // argument buffer will not follow the name. Need to speak with Chris.
1929 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001930 startBuf++; // scan forward (from the decl location) for argument types.
1931 startBuf++;
1932 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001933 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001934}
1935
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001936// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001937void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001938 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1939 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00001940 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001941 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001942 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001943 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001944 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00001945 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001946 SelGetUidIdent, getFuncType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001947 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001948}
1949
Steve Naroffb29b4272008-04-14 22:03:09 +00001950void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001951 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00001952 if (FD->getIdentifier() &&
1953 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001954 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001955 return;
1956 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001957 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001958}
1959
Steve Naroffc0a123c2008-03-11 17:37:02 +00001960// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001961void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001962 if (SuperContructorFunctionDecl)
1963 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00001964 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00001965 llvm::SmallVector<QualType, 16> ArgTys;
1966 QualType argT = Context->getObjCIdType();
1967 assert(!argT.isNull() && "Can't find 'id' type");
1968 ArgTys.push_back(argT);
1969 ArgTys.push_back(argT);
1970 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1971 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001972 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001973 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00001974 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001975 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001976 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00001977}
1978
Steve Naroff09b266e2007-10-30 23:14:51 +00001979// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001980void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001981 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1982 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001983 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001984 assert(!argT.isNull() && "Can't find 'id' type");
1985 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001986 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001987 assert(!argT.isNull() && "Can't find 'SEL' type");
1988 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001989 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001990 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001991 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001992 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001993 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001994 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001995 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00001996}
1997
Steve Naroff874e2322007-11-15 10:28:18 +00001998// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001999void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002000 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2001 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002002 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002003 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002004 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002005 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2006 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2007 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002008 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002009 assert(!argT.isNull() && "Can't find 'SEL' type");
2010 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002011 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002012 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002013 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002014 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002015 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002016 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002017 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002018}
2019
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002020// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002021void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002022 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2023 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002024 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002025 assert(!argT.isNull() && "Can't find 'id' type");
2026 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002027 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002028 assert(!argT.isNull() && "Can't find 'SEL' type");
2029 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002030 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002031 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002032 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002033 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002034 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002035 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002036 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002037}
2038
Mike Stump1eb44332009-09-09 15:08:12 +00002039// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002040// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002041void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002042 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002043 &Context->Idents.get("objc_msgSendSuper_stret");
2044 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002045 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002046 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002047 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002048 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2049 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2050 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002051 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002052 assert(!argT.isNull() && "Can't find 'SEL' type");
2053 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002054 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002055 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002056 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002057 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002058 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002059 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002060 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002061}
2062
Steve Naroff1284db82008-05-08 22:02:18 +00002063// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002064void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002065 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2066 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002067 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002068 assert(!argT.isNull() && "Can't find 'id' type");
2069 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002070 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002071 assert(!argT.isNull() && "Can't find 'SEL' type");
2072 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002073 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002074 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002075 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002076 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002077 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002078 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002079 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002080}
2081
Steve Naroff09b266e2007-10-30 23:14:51 +00002082// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002083void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002084 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2085 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002086 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002087 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002088 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002089 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002090 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002091 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002092 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002093 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002094}
2095
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002096// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002097void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002098 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2099 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002100 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002101 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002102 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002103 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002104 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002105 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002106 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002107 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002108}
2109
Steve Naroffb29b4272008-04-14 22:03:09 +00002110Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002111 QualType strType = getConstantStringStructType();
2112
2113 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002114
2115 std::string tmpName = InFileName;
2116 unsigned i;
2117 for (i=0; i < tmpName.length(); i++) {
2118 char c = tmpName.at(i);
2119 // replace any non alphanumeric characters with '_'.
2120 if (!isalpha(c) && (c < '0' || c > '9'))
2121 tmpName[i] = '_';
2122 }
2123 S += tmpName;
2124 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002125 S += utostr(NumObjCStringLiterals++);
2126
Steve Naroffba92b2e2008-03-27 22:29:16 +00002127 Preamble += "static __NSConstantStringImpl " + S;
2128 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2129 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002130 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002131 std::string prettyBufS;
2132 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002133 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2134 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002135 Preamble += prettyBuf.str();
2136 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002137 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002138 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002139
2140 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2141 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002142 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002143 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2144 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002145 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002146 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002147 // cast to NSConstantString *
Mike Stump1eb44332009-09-09 15:08:12 +00002148 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002149 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002150 Unop, Exp->getType(),
2151 SourceLocation(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002152 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002153 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002154 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002155 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002156}
2157
Steve Naroffb29b4272008-04-14 22:03:09 +00002158ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002159 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002160 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002162 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002163 const ObjCObjectPointerType *OPT =
John McCall183700f2009-09-21 23:43:11 +00002164 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00002165 assert(OPT);
2166 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002167 return IT->getDecl();
2168 }
2169 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002170}
2171
2172// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002173QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002174 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002175 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002176 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002177 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002178 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002179
Steve Naroff874e2322007-11-15 10:28:18 +00002180 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002181 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002182 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002183 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002184
Steve Naroff874e2322007-11-15 10:28:18 +00002185 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002186 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002187 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2188 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002189 FieldTypes[i], 0,
2190 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002191 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002192 }
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Douglas Gregor44b43212008-12-11 16:49:14 +00002194 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002195 }
2196 return Context->getTagDeclType(SuperStructDecl);
2197}
2198
Steve Naroffb29b4272008-04-14 22:03:09 +00002199QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002200 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002201 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002202 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002203 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002204 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002206 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002207 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002208 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002209 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002210 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002211 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002212 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002213 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002214
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002215 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002216 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002217 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2218 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002219 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002220 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002221 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002222 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002223 }
2224
2225 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002226 }
2227 return Context->getTagDeclType(ConstantStringDecl);
2228}
2229
Steve Naroffb29b4272008-04-14 22:03:09 +00002230Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002231 if (!SelGetUidFunctionDecl)
2232 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002233 if (!MsgSendFunctionDecl)
2234 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002235 if (!MsgSendSuperFunctionDecl)
2236 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002237 if (!MsgSendStretFunctionDecl)
2238 SynthMsgSendStretFunctionDecl();
2239 if (!MsgSendSuperStretFunctionDecl)
2240 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002241 if (!MsgSendFpretFunctionDecl)
2242 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002243 if (!GetClassFunctionDecl)
2244 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002245 if (!GetMetaClassFunctionDecl)
2246 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002247
Steve Naroff874e2322007-11-15 10:28:18 +00002248 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002249 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2250 // May need to use objc_msgSend_stret() as well.
2251 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002252 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2253 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002254 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002255 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002256 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002257 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002258 }
Mike Stump1eb44332009-09-09 15:08:12 +00002259
Steve Naroff934f2762007-10-24 22:48:43 +00002260 // Synthesize a call to objc_msgSend().
2261 llvm::SmallVector<Expr*, 8> MsgExprs;
2262 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Steve Naroff934f2762007-10-24 22:48:43 +00002264 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2265 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002266 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2267 // the 'super' idiom within a class method.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00002268 if (clsName->getName() == "super") {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002269 MsgSendFlavor = MsgSendSuperFunctionDecl;
2270 if (MsgSendStretFlavor)
2271 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2272 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002273
2274 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002275 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002276
2277 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002278
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002279 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002280 InitExprs.push_back(
Mike Stump1eb44332009-09-09 15:08:12 +00002281 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002282 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002283 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff621edce2009-04-29 16:37:50 +00002284 Context->getObjCIdType(),
2285 SourceLocation()),
2286 Context->getObjCIdType(),
2287 SourceLocation(), SourceLocation())); // set the 'receiver'.
2288
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002289 llvm::SmallVector<Expr*, 8> ClsExprs;
2290 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002291 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002292 SuperDecl->getIdentifier()->getNameStart(),
2293 SuperDecl->getIdentifier()->getLength(),
2294 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002295 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002296 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002297 ClsExprs.size());
2298 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002299 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump1eb44332009-09-09 15:08:12 +00002300 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002301 CastExpr::CK_Unknown,
Douglas Gregor49badde2008-10-27 19:41:14 +00002302 Cls, Context->getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00002303 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002304 // struct objc_super
2305 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002306 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Steve Naroff23f41272008-03-11 18:14:26 +00002308 if (LangOpts.Microsoft) {
2309 SynthSuperContructorFunctionDecl();
2310 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002311 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002312 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002313 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002314 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002315 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002316 // The code for super is a little tricky to prevent collision with
2317 // the structure definition in the header. The rewriter has it's own
2318 // internal definition (__rw_objc_super) that is uses. This is why
2319 // we need the cast below. For example:
2320 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2321 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002322 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002323 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002324 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002325 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2326 CastExpr::CK_Unknown, SuperRep,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002327 Context->getPointerType(superType),
Mike Stump1eb44332009-09-09 15:08:12 +00002328 SourceLocation(), SourceLocation());
2329 } else {
Steve Naroff23f41272008-03-11 18:14:26 +00002330 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002331 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2332 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002333 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002334 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner418f6c72008-10-26 23:43:26 +00002335 false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002336 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002337 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002338 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002339 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002340 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002341 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002342 } else {
2343 llvm::SmallVector<Expr*, 8> ClsExprs;
2344 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002345 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002346 clsName->getNameStart(),
Chris Lattner2085fd62009-02-18 06:40:38 +00002347 clsName->getLength(),
2348 false, argType,
2349 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002350 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002351 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002352 ClsExprs.size());
2353 MsgExprs.push_back(Cls);
2354 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002355 } else { // instance message.
2356 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002357
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002358 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002359 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002360 if (MsgSendStretFlavor)
2361 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002362 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Steve Naroff874e2322007-11-15 10:28:18 +00002364 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002366 InitExprs.push_back(
Mike Stump1eb44332009-09-09 15:08:12 +00002367 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002368 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002369 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002370 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002371 SourceLocation()),
2372 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002373 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002374
Steve Naroff874e2322007-11-15 10:28:18 +00002375 llvm::SmallVector<Expr*, 8> ClsExprs;
2376 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002377 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002378 SuperDecl->getIdentifier()->getNameStart(),
2379 SuperDecl->getIdentifier()->getLength(),
2380 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002381 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002382 &ClsExprs[0],
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002383 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002384 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002385 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002386 // set 'super class', using objc_getClass().
Mike Stump1eb44332009-09-09 15:08:12 +00002387 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002388 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002389 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002390 // struct objc_super
2391 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002392 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002393
Steve Naroffc0a123c2008-03-11 17:37:02 +00002394 if (LangOpts.Microsoft) {
2395 SynthSuperContructorFunctionDecl();
2396 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002397 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002398 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002399 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002400 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002401 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002402 // The code for super is a little tricky to prevent collision with
2403 // the structure definition in the header. The rewriter has it's own
2404 // internal definition (__rw_objc_super) that is uses. This is why
2405 // we need the cast below. For example:
2406 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2407 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002408 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002409 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002410 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002411 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002412 CastExpr::CK_Unknown,
Steve Naroff46a98a72008-12-23 20:11:22 +00002413 SuperRep, Context->getPointerType(superType),
Mike Stump1eb44332009-09-09 15:08:12 +00002414 SourceLocation(), SourceLocation());
Steve Naroffc0a123c2008-03-11 17:37:02 +00002415 } else {
2416 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002417 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2418 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002419 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002420 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002421 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002422 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002423 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002424 // Remove all type-casts because it may contain objc-style types; e.g.
2425 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002426 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002427 recExpr = CE->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002428 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002429 CastExpr::CK_Unknown, recExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002430 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002431 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002432 MsgExprs.push_back(recExpr);
2433 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002434 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002435 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002436 llvm::SmallVector<Expr*, 8> SelExprs;
2437 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002438 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002439 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002440 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002441 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002442 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2443 &SelExprs[0], SelExprs.size());
2444 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002445
Steve Naroff934f2762007-10-24 22:48:43 +00002446 // Now push any user supplied arguments.
2447 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002448 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002449 // Make all implicit casts explicit...ICE comes in handy:-)
2450 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2451 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002452 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002453 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002454 : ICE->getType();
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002455 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002456 userExpr, type, SourceLocation(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002457 SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002458 }
2459 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002460 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002461 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002462 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002463 userExpr = CE->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002464 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002465 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002466 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002467 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002468 }
Mike Stump1eb44332009-09-09 15:08:12 +00002469 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002470 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002471 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2472 // out the argument in the original expression (since we aren't deleting
2473 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2474 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002475 }
Steve Naroffab972d32007-11-04 22:37:50 +00002476 // Generate the funky cast.
2477 CastExpr *cast;
2478 llvm::SmallVector<QualType, 8> ArgTypes;
2479 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002480
Steve Naroffab972d32007-11-04 22:37:50 +00002481 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002482 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2483 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2484 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002485 ArgTypes.push_back(Context->getObjCIdType());
2486 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002487 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002488 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002489 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2490 E = OMD->param_end(); PI != E; ++PI) {
2491 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002492 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002493 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002494 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002495 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002496 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002497 t = Context->getPointerType(BPT->getPointeeType());
2498 }
Steve Naroff352336b2007-11-05 14:36:37 +00002499 ArgTypes.push_back(t);
2500 }
Chris Lattner89951a82009-02-20 18:43:26 +00002501 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2502 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002503 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002504 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002505 }
2506 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002507 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002508
Steve Naroffab972d32007-11-04 22:37:50 +00002509 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002510 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002511 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002512
Mike Stump1eb44332009-09-09 15:08:12 +00002513 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002514 // If we don't do this cast, we get the following bizarre warning/note:
2515 // xx.m:13: warning: function called through a non-compatible type
2516 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump1eb44332009-09-09 15:08:12 +00002517 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2518 CastExpr::CK_Unknown, DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002519 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002520 SourceLocation(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002521
Steve Naroffab972d32007-11-04 22:37:50 +00002522 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002523 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002524 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002525 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002526 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002527 castType = Context->getPointerType(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00002528 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2529 castType, SourceLocation(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002530 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002531
2532 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002533 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002534
John McCall183700f2009-09-21 23:43:11 +00002535 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002536 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002537 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002538 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002539 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002540 if (MsgSendStretFlavor) {
2541 // We have the method which returns a struct/union. Must also generate
2542 // call to objc_msgSend_stret and hang both varieties on a conditional
2543 // expression which dictate which one to envoke depending on size of
2544 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002545
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002546 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002547 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002548 SourceLocation());
2549 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump1eb44332009-09-09 15:08:12 +00002550 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2551 CastExpr::CK_Unknown, STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002552 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002553 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002554 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002555 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002556 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002557 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002558 castType = Context->getPointerType(castType);
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002559 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2560 cast, castType, SourceLocation(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002561
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002562 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002563 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002564
John McCall183700f2009-09-21 23:43:11 +00002565 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002566 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002567 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002568 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002569
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002570 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00002571 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCall5ab75172009-11-04 07:28:41 +00002572 Context->getTrivialDeclaratorInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00002573 Context->getSizeType(),
2574 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002575 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2576 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2577 // For X86 it is more complicated and some kind of target specific routine
2578 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00002579 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00002580 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002581 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002582 Context->IntTy,
2583 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002584 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2585 BinaryOperator::LE,
2586 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002587 SourceLocation());
2588 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00002589 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00002590 new (Context) ConditionalOperator(lessThanExpr,
2591 SourceLocation(), CE,
2592 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002593 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002594 }
Mike Stump1eb44332009-09-09 15:08:12 +00002595 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002596 return ReplacingStmt;
2597}
2598
Steve Naroffb29b4272008-04-14 22:03:09 +00002599Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002600 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00002601
Steve Naroff934f2762007-10-24 22:48:43 +00002602 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002603 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00002604
2605 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002606 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002607}
2608
Steve Naroff621edce2009-04-29 16:37:50 +00002609// typedef struct objc_object Protocol;
2610QualType RewriteObjC::getProtocolType() {
2611 if (!ProtocolTypeDecl) {
John McCallba6a9bd2009-10-24 08:00:42 +00002612 DeclaratorInfo *DInfo
2613 = Context->getTrivialDeclaratorInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00002614 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002615 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00002616 &Context->Idents.get("Protocol"),
John McCallba6a9bd2009-10-24 08:00:42 +00002617 DInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00002618 }
2619 return Context->getTypeDeclType(ProtocolTypeDecl);
2620}
2621
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002622/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00002623/// a synthesized/forward data reference (to the protocol's metadata).
2624/// The forward references (and metadata) are generated in
2625/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00002626Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00002627 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2628 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00002629 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002630 ID, QualType()/*UNUSED*/, 0, VarDecl::Extern);
Steve Naroff621edce2009-04-29 16:37:50 +00002631 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2632 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2633 Context->getPointerType(DRE->getType()),
2634 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002635 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2636 CastExpr::CK_Unknown,
2637 DerefExpr, DerefExpr->getType(),
Steve Naroff621edce2009-04-29 16:37:50 +00002638 SourceLocation(), SourceLocation());
2639 ReplaceStmt(Exp, castExpr);
2640 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00002641 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002642 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002643
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002644}
2645
Mike Stump1eb44332009-09-09 15:08:12 +00002646bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00002647 const char *endBuf) {
2648 while (startBuf < endBuf) {
2649 if (*startBuf == '#') {
2650 // Skip whitespace.
2651 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2652 ;
2653 if (!strncmp(startBuf, "if", strlen("if")) ||
2654 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2655 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2656 !strncmp(startBuf, "define", strlen("define")) ||
2657 !strncmp(startBuf, "undef", strlen("undef")) ||
2658 !strncmp(startBuf, "else", strlen("else")) ||
2659 !strncmp(startBuf, "elif", strlen("elif")) ||
2660 !strncmp(startBuf, "endif", strlen("endif")) ||
2661 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2662 !strncmp(startBuf, "include", strlen("include")) ||
2663 !strncmp(startBuf, "import", strlen("import")) ||
2664 !strncmp(startBuf, "include_next", strlen("include_next")))
2665 return true;
2666 }
2667 startBuf++;
2668 }
2669 return false;
2670}
2671
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002672/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002673/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002674void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002675 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002676 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00002677 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002678 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002679 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002680 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002681 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002682 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002683 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002684 SourceLocation LocStart = CDecl->getLocStart();
2685 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002686
Steve Narofffea763e82007-11-14 19:25:57 +00002687 const char *startBuf = SM->getCharacterData(LocStart);
2688 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00002689
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002690 // If no ivars and no root or if its root, directly or indirectly,
2691 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002692 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2693 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00002694 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattneraadaf782008-01-31 19:51:04 +00002695 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002696 return;
2697 }
Mike Stump1eb44332009-09-09 15:08:12 +00002698
2699 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002700 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002701 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002702 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002703 if (LangOpts.Microsoft)
2704 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002705
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002706 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002707 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00002708 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002709 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002710 // If the buffer contains preprocessor directives, we do more fine-grained
2711 // rewrites. This is intended to fix code that looks like (which occurs in
2712 // NSURL.h, for example):
2713 //
2714 // #ifdef XYZ
2715 // @interface Foo : NSObject
2716 // #else
2717 // @interface FooBar : NSObject
2718 // #endif
2719 // {
2720 // int i;
2721 // }
2722 // @end
2723 //
2724 // This clause is segregated to avoid breaking the common case.
2725 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002726 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00002727 CDecl->getClassLoc();
2728 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00002729 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002730
Chris Lattnercafeb352009-02-20 18:18:36 +00002731 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002732 // advance to the end of the referenced protocols.
2733 while (endHeader < cursor && *endHeader != '>') endHeader++;
2734 endHeader++;
2735 }
2736 // rewrite the original header
2737 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2738 } else {
2739 // rewrite the original header *without* disturbing the '{'
2740 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2741 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002742 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002743 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002744 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002745 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002746 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002747 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002748
Steve Narofffea763e82007-11-14 19:25:57 +00002749 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002750 SourceLocation OnePastCurly =
2751 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2752 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002753 }
2754 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00002755
Steve Narofffea763e82007-11-14 19:25:57 +00002756 // Now comment out any visibility specifiers.
2757 while (cursor < endBuf) {
2758 if (*cursor == '@') {
2759 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002760 // Skip whitespace.
2761 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2762 /*scan*/;
2763
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002764 // FIXME: presence of @public, etc. inside comment results in
2765 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002766 if (!strncmp(cursor, "public", strlen("public")) ||
2767 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002768 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002769 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002770 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002771 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002772 // FIXME: If there are cases where '<' is used in ivar declaration part
2773 // of user code, then scan the ivar list and use needToScanForQualifiers
2774 // for type checking.
2775 else if (*cursor == '<') {
2776 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002777 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002778 cursor = strchr(cursor, '>');
2779 cursor++;
2780 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002781 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002782 } else if (*cursor == '^') { // rewrite block specifier.
2783 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2784 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002785 }
Steve Narofffea763e82007-11-14 19:25:57 +00002786 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002787 }
Steve Narofffea763e82007-11-14 19:25:57 +00002788 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002789 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002790 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00002791 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00002792 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002793 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002794 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002795 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002796 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002797 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002798 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002799 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002800 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002801 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002802}
2803
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002804// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002805/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00002806template<typename MethodIterator>
2807void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2808 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002809 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002810 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002811 const char *ClassName,
2812 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002813 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00002814
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002815 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002816 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002817 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002818 SEL _cmd;
2819 char *method_types;
2820 void *_imp;
2821 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002822 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002823 Result += "\nstruct _objc_method {\n";
2824 Result += "\tSEL _cmd;\n";
2825 Result += "\tchar *method_types;\n";
2826 Result += "\tvoid *_imp;\n";
2827 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002828
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002829 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002830 }
Mike Stump1eb44332009-09-09 15:08:12 +00002831
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002832 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00002833
Steve Naroff946a6932008-03-11 00:12:29 +00002834 /* struct {
2835 struct _objc_method_list *next_method;
2836 int method_count;
2837 struct _objc_method method_list[];
2838 }
2839 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00002840 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00002841 Result += "\nstatic struct {\n";
2842 Result += "\tstruct _objc_method_list *next_method;\n";
2843 Result += "\tint method_count;\n";
2844 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00002845 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00002846 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002847 Result += prefix;
2848 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2849 Result += "_METHODS_";
2850 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002851 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002852 Result += IsInstanceMethod ? "inst" : "cls";
2853 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00002854 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002855
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002856 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002857 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002858 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002859 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002860 Result += "\", \"";
2861 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002862 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002863 Result += MethodInternalNames[*MethodBegin];
2864 Result += "}\n";
2865 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2866 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002867 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002868 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002869 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002870 Result += "\", \"";
2871 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002872 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002873 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002874 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002875 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002876 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002877}
2878
Steve Naroff621edce2009-04-29 16:37:50 +00002879/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002880void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00002881RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
2882 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002883 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00002884
2885 // Output struct protocol_methods holder of method selector and type.
2886 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2887 /* struct protocol_methods {
2888 SEL _cmd;
2889 char *method_types;
2890 }
2891 */
2892 Result += "\nstruct _protocol_methods {\n";
2893 Result += "\tstruct objc_selector *_cmd;\n";
2894 Result += "\tchar *method_types;\n";
2895 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002896
Steve Naroff621edce2009-04-29 16:37:50 +00002897 objc_protocol_methods = true;
2898 }
2899 // Do not synthesize the protocol more than once.
2900 if (ObjCSynthesizedProtocols.count(PDecl))
2901 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002902
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002903 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2904 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
2905 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00002906 /* struct _objc_protocol_method_list {
2907 int protocol_method_count;
2908 struct protocol_methods protocols[];
2909 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002910 */
Steve Naroff621edce2009-04-29 16:37:50 +00002911 Result += "\nstatic struct {\n";
2912 Result += "\tint protocol_method_count;\n";
2913 Result += "\tstruct _protocol_methods protocol_methods[";
2914 Result += utostr(NumMethods);
2915 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2916 Result += PDecl->getNameAsString();
2917 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2918 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002919
Steve Naroff621edce2009-04-29 16:37:50 +00002920 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00002921 for (ObjCProtocolDecl::instmeth_iterator
2922 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00002923 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002924 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00002925 Result += "\t ,{{(struct objc_selector *)\"";
2926 else
2927 Result += "\t ,{(struct objc_selector *)\"";
2928 Result += (*I)->getSelector().getAsString().c_str();
2929 std::string MethodTypeString;
2930 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2931 Result += "\", \"";
2932 Result += MethodTypeString;
2933 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002934 }
Steve Naroff621edce2009-04-29 16:37:50 +00002935 Result += "\t }\n};\n";
2936 }
Mike Stump1eb44332009-09-09 15:08:12 +00002937
Steve Naroff621edce2009-04-29 16:37:50 +00002938 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002939 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
2940 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00002941 if (NumMethods > 0) {
2942 /* struct _objc_protocol_method_list {
2943 int protocol_method_count;
2944 struct protocol_methods protocols[];
2945 }
2946 */
2947 Result += "\nstatic struct {\n";
2948 Result += "\tint protocol_method_count;\n";
2949 Result += "\tstruct _protocol_methods protocol_methods[";
2950 Result += utostr(NumMethods);
2951 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2952 Result += PDecl->getNameAsString();
2953 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2954 "{\n\t";
2955 Result += utostr(NumMethods);
2956 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002957
Steve Naroff621edce2009-04-29 16:37:50 +00002958 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00002959 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002960 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00002961 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002962 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00002963 Result += "\t ,{{(struct objc_selector *)\"";
2964 else
2965 Result += "\t ,{(struct objc_selector *)\"";
2966 Result += (*I)->getSelector().getAsString().c_str();
2967 std::string MethodTypeString;
2968 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2969 Result += "\", \"";
2970 Result += MethodTypeString;
2971 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002972 }
Steve Naroff621edce2009-04-29 16:37:50 +00002973 Result += "\t }\n};\n";
2974 }
2975
2976 // Output:
2977 /* struct _objc_protocol {
2978 // Objective-C 1.0 extensions
2979 struct _objc_protocol_extension *isa;
2980 char *protocol_name;
2981 struct _objc_protocol **protocol_list;
2982 struct _objc_protocol_method_list *instance_methods;
2983 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00002984 };
Steve Naroff621edce2009-04-29 16:37:50 +00002985 */
2986 static bool objc_protocol = false;
2987 if (!objc_protocol) {
2988 Result += "\nstruct _objc_protocol {\n";
2989 Result += "\tstruct _objc_protocol_extension *isa;\n";
2990 Result += "\tchar *protocol_name;\n";
2991 Result += "\tstruct _objc_protocol **protocol_list;\n";
2992 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2993 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002994 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002995
Steve Naroff621edce2009-04-29 16:37:50 +00002996 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002997 }
Mike Stump1eb44332009-09-09 15:08:12 +00002998
Steve Naroff621edce2009-04-29 16:37:50 +00002999 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3000 Result += PDecl->getNameAsString();
3001 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3002 "{\n\t0, \"";
3003 Result += PDecl->getNameAsString();
3004 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003005 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003006 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3007 Result += PDecl->getNameAsString();
3008 Result += ", ";
3009 }
3010 else
3011 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003012 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003013 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3014 Result += PDecl->getNameAsString();
3015 Result += "\n";
3016 }
3017 else
3018 Result += "0\n";
3019 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003020
Steve Naroff621edce2009-04-29 16:37:50 +00003021 // Mark this protocol as having been generated.
3022 if (!ObjCSynthesizedProtocols.insert(PDecl))
3023 assert(false && "protocol already synthesized");
3024
3025}
3026
3027void RewriteObjC::
3028RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3029 const char *prefix, const char *ClassName,
3030 std::string &Result) {
3031 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003032
Steve Naroff621edce2009-04-29 16:37:50 +00003033 for (unsigned i = 0; i != Protocols.size(); i++)
3034 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3035
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003036 // Output the top lovel protocol meta-data for the class.
3037 /* struct _objc_protocol_list {
3038 struct _objc_protocol_list *next;
3039 int protocol_count;
3040 struct _objc_protocol *class_protocols[];
3041 }
3042 */
3043 Result += "\nstatic struct {\n";
3044 Result += "\tstruct _objc_protocol_list *next;\n";
3045 Result += "\tint protocol_count;\n";
3046 Result += "\tstruct _objc_protocol *class_protocols[";
3047 Result += utostr(Protocols.size());
3048 Result += "];\n} _OBJC_";
3049 Result += prefix;
3050 Result += "_PROTOCOLS_";
3051 Result += ClassName;
3052 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3053 "{\n\t0, ";
3054 Result += utostr(Protocols.size());
3055 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003056
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003057 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003058 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003059 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003060
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003061 for (unsigned i = 1; i != Protocols.size(); i++) {
3062 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003063 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003064 Result += "\n";
3065 }
3066 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003067}
3068
Steve Naroff621edce2009-04-29 16:37:50 +00003069
Mike Stump1eb44332009-09-09 15:08:12 +00003070/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003071/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003072void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003073 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003074 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003075 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003076 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003077 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003078 CDecl = CDecl->getNextClassCategory())
3079 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3080 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003081
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003082 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003083 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003084 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003085
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003086 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003087 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003088 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003089
3090 // If any of our property implementations have associated getters or
3091 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003092 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3093 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003094 Prop != PropEnd; ++Prop) {
3095 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3096 continue;
3097 if (!(*Prop)->getPropertyIvarDecl())
3098 continue;
3099 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3100 if (!PD)
3101 continue;
3102 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3103 InstanceMethods.push_back(Getter);
3104 if (PD->isReadOnly())
3105 continue;
3106 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3107 InstanceMethods.push_back(Setter);
3108 }
3109 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003110 true, "CATEGORY_", FullCategoryName.c_str(),
3111 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003112
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003113 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003114 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003115 false, "CATEGORY_", FullCategoryName.c_str(),
3116 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003117
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003118 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003119 // Null CDecl is case of a category implementation with no category interface
3120 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003121 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3122 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003123 /* struct _objc_category {
3124 char *category_name;
3125 char *class_name;
3126 struct _objc_method_list *instance_methods;
3127 struct _objc_method_list *class_methods;
3128 struct _objc_protocol_list *protocols;
3129 // Objective-C 1.0 extensions
3130 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003131 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003132 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003133 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003134 */
Mike Stump1eb44332009-09-09 15:08:12 +00003135
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003136 static bool objc_category = false;
3137 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003138 Result += "\nstruct _objc_category {\n";
3139 Result += "\tchar *category_name;\n";
3140 Result += "\tchar *class_name;\n";
3141 Result += "\tstruct _objc_method_list *instance_methods;\n";
3142 Result += "\tstruct _objc_method_list *class_methods;\n";
3143 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003144 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003145 Result += "\tstruct _objc_property_list *instance_properties;\n";
3146 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003147 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003148 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003149 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3150 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003151 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003152 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003153 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003154 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003155 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003156
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003157 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003158 Result += "\t, (struct _objc_method_list *)"
3159 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3160 Result += FullCategoryName;
3161 Result += "\n";
3162 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003163 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003164 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003165 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003166 Result += "\t, (struct _objc_method_list *)"
3167 "&_OBJC_CATEGORY_CLASS_METHODS_";
3168 Result += FullCategoryName;
3169 Result += "\n";
3170 }
3171 else
3172 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003173
Chris Lattnercafeb352009-02-20 18:18:36 +00003174 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003175 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003176 Result += FullCategoryName;
3177 Result += "\n";
3178 }
3179 else
3180 Result += "\t, 0\n";
3181 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003182}
3183
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003184/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3185/// ivar offset.
Mike Stump1eb44332009-09-09 15:08:12 +00003186void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3187 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003188 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003189 if (ivar->isBitField()) {
3190 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3191 // place all bitfields at offset 0.
3192 Result += "0";
3193 } else {
3194 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003195 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003196 if (LangOpts.Microsoft)
3197 Result += "_IMPL";
3198 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003199 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003200 Result += ")";
3201 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003202}
3203
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003204//===----------------------------------------------------------------------===//
3205// Meta Data Emission
3206//===----------------------------------------------------------------------===//
3207
Steve Naroffb29b4272008-04-14 22:03:09 +00003208void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003209 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003210 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003211
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003212 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003213 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003214 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003215 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003216 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003217 }
Mike Stump1eb44332009-09-09 15:08:12 +00003218
Chris Lattnerbe6df082007-12-12 07:56:42 +00003219 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003220 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003221 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003222 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003223 if (NumIvars > 0) {
3224 static bool objc_ivar = false;
3225 if (!objc_ivar) {
3226 /* struct _objc_ivar {
3227 char *ivar_name;
3228 char *ivar_type;
3229 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003230 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003231 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003232 Result += "\nstruct _objc_ivar {\n";
3233 Result += "\tchar *ivar_name;\n";
3234 Result += "\tchar *ivar_type;\n";
3235 Result += "\tint ivar_offset;\n";
3236 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003237
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003238 objc_ivar = true;
3239 }
3240
Steve Naroff946a6932008-03-11 00:12:29 +00003241 /* struct {
3242 int ivar_count;
3243 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003244 };
Steve Naroff946a6932008-03-11 00:12:29 +00003245 */
Mike Stump1eb44332009-09-09 15:08:12 +00003246 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003247 Result += "\tint ivar_count;\n";
3248 Result += "\tstruct _objc_ivar ivar_list[";
3249 Result += utostr(NumIvars);
3250 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003251 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003252 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003253 "{\n\t";
3254 Result += utostr(NumIvars);
3255 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003256
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003257 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003258 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003259 if (!IDecl->ivar_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003260 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003261 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003262 IV != IVEnd; ++IV)
3263 IVars.push_back(*IV);
3264 IVI = IVars.begin();
3265 IVE = IVars.end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003266 } else {
3267 IVI = CDecl->ivar_begin();
3268 IVE = CDecl->ivar_end();
3269 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003270 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003271 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003272 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003273 std::string TmpString, StrEncoding;
3274 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3275 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003276 Result += StrEncoding;
3277 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003278 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003279 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003280 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003281 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003282 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003283 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003284 std::string TmpString, StrEncoding;
3285 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3286 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003287 Result += StrEncoding;
3288 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003289 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003290 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003291 }
Mike Stump1eb44332009-09-09 15:08:12 +00003292
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003293 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003294 }
Mike Stump1eb44332009-09-09 15:08:12 +00003295
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003296 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003297 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003298 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003299
3300 // If any of our property implementations have associated getters or
3301 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003302 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3303 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003304 Prop != PropEnd; ++Prop) {
3305 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3306 continue;
3307 if (!(*Prop)->getPropertyIvarDecl())
3308 continue;
3309 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3310 if (!PD)
3311 continue;
3312 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3313 InstanceMethods.push_back(Getter);
3314 if (PD->isReadOnly())
3315 continue;
3316 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3317 InstanceMethods.push_back(Setter);
3318 }
3319 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003320 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003321
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003322 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003323 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003324 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003325
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003326 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003327 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3328 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003329
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003330 // Declaration of class/meta-class metadata
3331 /* struct _objc_class {
3332 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003333 const char *super_class_name;
3334 char *name;
3335 long version;
3336 long info;
3337 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003338 struct _objc_ivar_list *ivars;
3339 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003340 struct objc_cache *cache;
3341 struct objc_protocol_list *protocols;
3342 const char *ivar_layout;
3343 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003344 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003345 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003346 static bool objc_class = false;
3347 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003348 Result += "\nstruct _objc_class {\n";
3349 Result += "\tstruct _objc_class *isa;\n";
3350 Result += "\tconst char *super_class_name;\n";
3351 Result += "\tchar *name;\n";
3352 Result += "\tlong version;\n";
3353 Result += "\tlong info;\n";
3354 Result += "\tlong instance_size;\n";
3355 Result += "\tstruct _objc_ivar_list *ivars;\n";
3356 Result += "\tstruct _objc_method_list *methods;\n";
3357 Result += "\tstruct objc_cache *cache;\n";
3358 Result += "\tstruct _objc_protocol_list *protocols;\n";
3359 Result += "\tconst char *ivar_layout;\n";
3360 Result += "\tstruct _objc_class_ext *ext;\n";
3361 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003362 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003363 }
Mike Stump1eb44332009-09-09 15:08:12 +00003364
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003365 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003366 ObjCInterfaceDecl *RootClass = 0;
3367 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003368 while (SuperClass) {
3369 RootClass = SuperClass;
3370 SuperClass = SuperClass->getSuperClass();
3371 }
3372 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003373
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003374 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003375 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003376 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003377 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003378 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003379 Result += "\"";
3380
3381 if (SuperClass) {
3382 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003383 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003384 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003385 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003386 Result += "\"";
3387 }
3388 else {
3389 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003390 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003391 Result += "\"";
3392 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003393 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003394 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003395 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003396 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003397 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003398 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003399 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003400 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003401 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003402 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003403 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003404 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003405 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003406 Result += ",0,0\n";
3407 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003408 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003409 Result += "\t,0,0,0,0\n";
3410 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003411
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003412 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003413 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003414 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003415 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003416 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003417 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003418 if (SuperClass) {
3419 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003420 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003421 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003422 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003423 Result += "\"";
3424 }
3425 else {
3426 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003427 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003428 Result += "\"";
3429 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003430 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003431 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003432 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003433 Result += ",0";
3434 else {
3435 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003436 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003437 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003438 if (LangOpts.Microsoft)
3439 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003440 Result += ")";
3441 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003442 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003443 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003444 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003445 Result += "\n\t";
3446 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003447 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003448 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003449 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003450 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003451 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003452 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003453 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003454 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003455 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003456 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003457 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003458 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003459 Result += ", 0,0\n";
3460 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003461 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003462 Result += ",0,0,0\n";
3463 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003464}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003465
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003466/// RewriteImplementations - This routine rewrites all method implementations
3467/// and emits meta-data.
3468
Steve Narofface66252008-11-13 20:07:04 +00003469void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003470 int ClsDefCount = ClassImplementation.size();
3471 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003472
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003473 // Rewrite implemented methods
3474 for (int i = 0; i < ClsDefCount; i++)
3475 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003476
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003477 for (int i = 0; i < CatDefCount; i++)
3478 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003479}
Mike Stump1eb44332009-09-09 15:08:12 +00003480
Steve Narofface66252008-11-13 20:07:04 +00003481void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3482 int ClsDefCount = ClassImplementation.size();
3483 int CatDefCount = CategoryImplementation.size();
3484
Steve Naroff5df5b762008-05-07 21:23:49 +00003485 // This is needed for determining instance variable offsets.
Mike Stump1eb44332009-09-09 15:08:12 +00003486 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003487 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003488 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003489 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003490
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003491 // For each implemented category, write out all its meta data.
3492 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003493 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003494
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003495 // Write objc_symtab metadata
3496 /*
3497 struct _objc_symtab
3498 {
3499 long sel_ref_cnt;
3500 SEL *refs;
3501 short cls_def_cnt;
3502 short cat_def_cnt;
3503 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003504 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003505 */
Mike Stump1eb44332009-09-09 15:08:12 +00003506
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003507 Result += "\nstruct _objc_symtab {\n";
3508 Result += "\tlong sel_ref_cnt;\n";
3509 Result += "\tSEL *refs;\n";
3510 Result += "\tshort cls_def_cnt;\n";
3511 Result += "\tshort cat_def_cnt;\n";
3512 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3513 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003514
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003515 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003516 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003517 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003518 + ", " + utostr(CatDefCount) + "\n";
3519 for (int i = 0; i < ClsDefCount; i++) {
3520 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003521 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003522 Result += "\n";
3523 }
Mike Stump1eb44332009-09-09 15:08:12 +00003524
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003525 for (int i = 0; i < CatDefCount; i++) {
3526 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003527 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003528 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003529 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003530 Result += "\n";
3531 }
Mike Stump1eb44332009-09-09 15:08:12 +00003532
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003533 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003534
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003535 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00003536
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003537 /*
3538 struct _objc_module {
3539 long version;
3540 long size;
3541 const char *name;
3542 struct _objc_symtab *symtab;
3543 }
3544 */
Mike Stump1eb44332009-09-09 15:08:12 +00003545
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003546 Result += "\nstruct _objc_module {\n";
3547 Result += "\tlong version;\n";
3548 Result += "\tlong size;\n";
3549 Result += "\tconst char *name;\n";
3550 Result += "\tstruct _objc_symtab *symtab;\n";
3551 Result += "};\n\n";
3552 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003553 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003554 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003555 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003556 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003557
3558 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00003559 if (ProtocolExprDecls.size()) {
3560 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3561 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003562 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00003563 E = ProtocolExprDecls.end(); I != E; ++I) {
3564 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3565 Result += (*I)->getNameAsString();
3566 Result += " = &_OBJC_PROTOCOL_";
3567 Result += (*I)->getNameAsString();
3568 Result += ";\n";
3569 }
3570 Result += "#pragma data_seg(pop)\n\n";
3571 }
Steve Naroff4f943c22008-03-10 20:43:59 +00003572 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003573 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003574 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3575 Result += "&_OBJC_MODULES;\n";
3576 Result += "#pragma data_seg(pop)\n\n";
3577 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003578}
Chris Lattner311ff022007-10-16 22:36:42 +00003579
Steve Naroff54055232008-10-27 17:20:55 +00003580std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3581 const char *funcName,
3582 std::string Tag) {
3583 const FunctionType *AFT = CE->getFunctionType();
3584 QualType RT = AFT->getResultType();
3585 std::string StructRef = "struct " + Tag;
3586 std::string S = "static " + RT.getAsString() + " __" +
3587 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003588
Steve Naroff54055232008-10-27 17:20:55 +00003589 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003590
Douglas Gregor72564e72009-02-26 23:50:07 +00003591 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003592 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003593 // block (to reference imported block decl refs).
3594 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003595 } else if (BD->param_empty()) {
3596 S += "(" + StructRef + " *__cself)";
3597 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003598 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003599 assert(FT && "SynthesizeBlockFunc: No function proto");
3600 S += '(';
3601 // first add the implicit argument.
3602 S += StructRef + " *__cself, ";
3603 std::string ParamStr;
3604 for (BlockDecl::param_iterator AI = BD->param_begin(),
3605 E = BD->param_end(); AI != E; ++AI) {
3606 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003607 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003608 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003609 S += ParamStr;
3610 }
3611 if (FT->isVariadic()) {
3612 if (!BD->param_empty()) S += ", ";
3613 S += "...";
3614 }
3615 S += ')';
3616 }
3617 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003618
Steve Naroff54055232008-10-27 17:20:55 +00003619 // Create local declarations to avoid rewriting all closure decl ref exprs.
3620 // First, emit a declaration for all "by ref" decls.
Mike Stump1eb44332009-09-09 15:08:12 +00003621 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003622 E = BlockByRefDecls.end(); I != E; ++I) {
3623 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003624 std::string Name = (*I)->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003625 Context->getPointerType((*I)->getType()).getAsStringInternal(Name,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003626 Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003627 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003628 }
Steve Naroff54055232008-10-27 17:20:55 +00003629 // Next, emit a declaration for all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003630 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003631 E = BlockByCopyDecls.end(); I != E; ++I) {
3632 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003633 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003634 // Handle nested closure invocation. For example:
3635 //
3636 // void (^myImportedClosure)(void);
3637 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003638 //
Steve Naroff54055232008-10-27 17:20:55 +00003639 // void (^anotherClosure)(void);
3640 // anotherClosure = ^(void) {
3641 // myImportedClosure(); // import and invoke the closure
3642 // };
3643 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003644 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003645 S += "struct __block_impl *";
3646 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003647 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003648 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003649 }
3650 std::string RewrittenStr = RewrittenBlockExprs[CE];
3651 const char *cstr = RewrittenStr.c_str();
3652 while (*cstr++ != '{') ;
3653 S += cstr;
3654 S += "\n";
3655 return S;
3656}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003657
Steve Naroff54055232008-10-27 17:20:55 +00003658std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3659 const char *funcName,
3660 std::string Tag) {
3661 std::string StructRef = "struct " + Tag;
3662 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003663
Steve Naroff54055232008-10-27 17:20:55 +00003664 S += funcName;
3665 S += "_block_copy_" + utostr(i);
3666 S += "(" + StructRef;
3667 S += "*dst, " + StructRef;
3668 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003669 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003670 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003671 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003672 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003673 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003674 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003675 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff54055232008-10-27 17:20:55 +00003676 }
3677 S += "\nstatic void __";
3678 S += funcName;
3679 S += "_block_dispose_" + utostr(i);
3680 S += "(" + StructRef;
3681 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003682 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003683 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003684 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003685 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003686 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003687 }
Mike Stump1eb44332009-09-09 15:08:12 +00003688 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003689 return S;
3690}
3691
3692std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3693 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003694 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003695 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003696
Steve Naroff54055232008-10-27 17:20:55 +00003697 S += " {\n struct __block_impl impl;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003698
Steve Naroff54055232008-10-27 17:20:55 +00003699 if (hasCopyDisposeHelpers)
3700 S += " void *copy;\n void *dispose;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003701
Steve Naroff54055232008-10-27 17:20:55 +00003702 Constructor += "(void *fp";
Mike Stump1eb44332009-09-09 15:08:12 +00003703
Steve Naroff54055232008-10-27 17:20:55 +00003704 if (hasCopyDisposeHelpers)
3705 Constructor += ", void *copyHelp, void *disposeHelp";
Mike Stump1eb44332009-09-09 15:08:12 +00003706
Steve Naroff54055232008-10-27 17:20:55 +00003707 if (BlockDeclRefs.size()) {
3708 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003709 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003710 E = BlockByCopyDecls.end(); I != E; ++I) {
3711 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003712 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003713 std::string ArgName = "_" + FieldName;
3714 // Handle nested closure invocation. For example:
3715 //
3716 // void (^myImportedBlock)(void);
3717 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003718 //
Steve Naroff54055232008-10-27 17:20:55 +00003719 // void (^anotherBlock)(void);
3720 // anotherBlock = ^(void) {
3721 // myImportedBlock(); // import and invoke the closure
3722 // };
3723 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003724 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003725 S += "struct __block_impl *";
3726 Constructor += ", void *" + ArgName;
3727 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003728 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3729 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003730 Constructor += ", " + ArgName;
3731 }
3732 S += FieldName + ";\n";
3733 }
3734 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003735 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003736 E = BlockByRefDecls.end(); I != E; ++I) {
3737 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003738 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003739 std::string ArgName = "_" + FieldName;
3740 // Handle nested closure invocation. For example:
3741 //
3742 // void (^myImportedBlock)(void);
3743 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003744 //
Steve Naroff54055232008-10-27 17:20:55 +00003745 // void (^anotherBlock)(void);
3746 // anotherBlock = ^(void) {
3747 // myImportedBlock(); // import and invoke the closure
3748 // };
3749 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003750 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003751 S += "struct __block_impl *";
3752 Constructor += ", void *" + ArgName;
3753 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003754 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003755 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00003756 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003757 Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003758 Constructor += ", " + ArgName;
3759 }
3760 S += FieldName + "; // by ref\n";
3761 }
3762 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003763 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003764 if (GlobalVarDecl)
3765 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3766 else
3767 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3768 Constructor += " impl.Size = sizeof(";
Steve Naroff54055232008-10-27 17:20:55 +00003769 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003770
Steve Naroff54055232008-10-27 17:20:55 +00003771 if (hasCopyDisposeHelpers)
3772 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003773
Steve Naroff54055232008-10-27 17:20:55 +00003774 // Initialize all "by copy" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003775 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003776 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003777 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003778 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003779 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003780 Constructor += Name + " = (struct __block_impl *)_";
3781 else
3782 Constructor += Name + " = _";
3783 Constructor += Name + ";\n";
3784 }
3785 // Initialize all "by ref" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003786 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003787 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003788 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003789 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003790 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003791 Constructor += Name + " = (struct __block_impl *)_";
3792 else
3793 Constructor += Name + " = _";
3794 Constructor += Name + ";\n";
3795 }
3796 } else {
3797 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003798 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003799 if (GlobalVarDecl)
3800 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3801 else
3802 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3803 Constructor += " impl.Size = sizeof(";
Steve Naroff54055232008-10-27 17:20:55 +00003804 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3805 if (hasCopyDisposeHelpers)
3806 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3807 }
3808 Constructor += " ";
3809 Constructor += "}\n";
3810 S += Constructor;
3811 S += "};\n";
3812 return S;
3813}
3814
3815void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3816 const char *FunName) {
3817 // Insert closures that were part of the function.
3818 for (unsigned i = 0; i < Blocks.size(); i++) {
3819
3820 CollectBlockDeclRefInfo(Blocks[i]);
3821
3822 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003823
3824 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
Steve Naroff54055232008-10-27 17:20:55 +00003825 ImportedBlockDecls.size() > 0);
3826
3827 InsertText(FunLocStart, CI.c_str(), CI.size());
3828
3829 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00003830
Steve Naroff54055232008-10-27 17:20:55 +00003831 InsertText(FunLocStart, CF.c_str(), CF.size());
3832
3833 if (ImportedBlockDecls.size()) {
3834 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3835 InsertText(FunLocStart, HF.c_str(), HF.size());
3836 }
Mike Stump1eb44332009-09-09 15:08:12 +00003837
Steve Naroff54055232008-10-27 17:20:55 +00003838 BlockDeclRefs.clear();
3839 BlockByRefDecls.clear();
3840 BlockByCopyDecls.clear();
3841 BlockCallExprs.clear();
3842 ImportedBlockDecls.clear();
3843 }
3844 Blocks.clear();
3845 RewrittenBlockExprs.clear();
3846}
3847
3848void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3849 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003850 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00003851
Steve Naroff54055232008-10-27 17:20:55 +00003852 SynthesizeBlockLiterals(FunLocStart, FuncName);
3853}
3854
3855void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003856 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3857 //SourceLocation FunLocStart = MD->getLocStart();
3858 // FIXME: This hack works around a bug in Rewrite.InsertText().
3859 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003860 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003861 // Convert colons to underscores.
3862 std::string::size_type loc = 0;
3863 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3864 FuncName.replace(loc, 1, "_");
Mike Stump1eb44332009-09-09 15:08:12 +00003865
Steve Naroff54055232008-10-27 17:20:55 +00003866 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3867}
3868
3869void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3870 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3871 CI != E; ++CI)
3872 if (*CI) {
3873 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3874 GetBlockDeclRefExprs(CBE->getBody());
3875 else
3876 GetBlockDeclRefExprs(*CI);
3877 }
3878 // Handle specific things.
3879 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3880 // FIXME: Handle enums.
3881 if (!isa<FunctionDecl>(CDRE->getDecl()))
3882 BlockDeclRefs.push_back(CDRE);
3883 return;
3884}
3885
3886void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3887 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3888 CI != E; ++CI)
3889 if (*CI) {
3890 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3891 GetBlockCallExprs(CBE->getBody());
3892 else
3893 GetBlockCallExprs(*CI);
3894 }
Mike Stump1eb44332009-09-09 15:08:12 +00003895
Steve Naroff54055232008-10-27 17:20:55 +00003896 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3897 if (CE->getCallee()->getType()->isBlockPointerType()) {
3898 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3899 }
3900 }
3901 return;
3902}
3903
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003904Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003905 // Navigate to relevant type information.
3906 const char *closureName = 0;
3907 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003908
Steve Naroff54055232008-10-27 17:20:55 +00003909 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003910 closureName = DRE->getDecl()->getNameAsCString();
Ted Kremenek6217b802009-07-29 21:53:49 +00003911 CPT = DRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003912 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003913 closureName = CDRE->getDecl()->getNameAsCString();
Ted Kremenek6217b802009-07-29 21:53:49 +00003914 CPT = CDRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003915 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003916 closureName = MExpr->getMemberDecl()->getNameAsCString();
Ted Kremenek6217b802009-07-29 21:53:49 +00003917 CPT = MExpr->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003918 } else {
3919 assert(1 && "RewriteBlockClass: Bad type");
3920 }
3921 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00003922 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00003923 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003924 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003925 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003926
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003927 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3928 SourceLocation(),
3929 &Context->Idents.get("__block_impl"));
3930 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003931
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003932 // Generate a funky cast.
3933 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00003934
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003935 // Push the block argument type.
3936 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003937 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00003938 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003939 E = FTP->arg_type_end(); I && (I != E); ++I) {
3940 QualType t = *I;
3941 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003942 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003943 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003944 t = Context->getPointerType(BPT->getPointeeType());
3945 }
3946 ArgTypes.push_back(t);
3947 }
Steve Naroff54055232008-10-27 17:20:55 +00003948 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003949 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003950 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003951 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003952
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003953 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00003954
3955 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00003956 CastExpr::CK_Unknown,
3957 Exp->getCallee(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00003958 PtrBlock, SourceLocation(),
3959 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003960 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003961 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3962 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003963 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00003964
Douglas Gregor44b43212008-12-11 16:49:14 +00003965 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003966 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003967 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003968 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3969 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00003970
Anders Carlssoncdef2b72009-07-31 00:48:10 +00003971 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
3972 CastExpr::CK_Unknown, ME,
Ted Kremenek8189cde2009-02-07 01:47:29 +00003973 PtrToFuncCastType,
3974 SourceLocation(),
3975 SourceLocation());
3976 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00003977
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003978 llvm::SmallVector<Expr*, 8> BlkExprs;
3979 // Add the implicit argument.
3980 BlkExprs.push_back(BlkCast);
3981 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003982 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003983 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003984 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003985 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003986 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3987 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00003988 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003989 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003990}
3991
3992void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003993 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3994 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003995}
3996
Steve Naroff621edce2009-04-29 16:37:50 +00003997// We need to return the rewritten expression to handle cases where the
3998// BlockDeclRefExpr is embedded in another expression being rewritten.
3999// For example:
4000//
4001// int main() {
4002// __block Foo *f;
4003// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004004//
Steve Naroff621edce2009-04-29 16:37:50 +00004005// void (^myblock)() = ^() {
4006// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4007// i = 77;
4008// };
4009//}
4010Stmt *RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
Steve Naroff54055232008-10-27 17:20:55 +00004011 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004012 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Naroffdf8570d2009-02-02 17:19:26 +00004013 Context->getPointerType(BDRE->getType()),
4014 SourceLocation());
4015 // Need parens to enforce precedence.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004016 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Naroffdf8570d2009-02-02 17:19:26 +00004017 ReplaceStmt(BDRE, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004018 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004019}
4020
Steve Naroffb2f9e512008-11-03 23:29:32 +00004021void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4022 SourceLocation LocStart = CE->getLParenLoc();
4023 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004024
4025 // Need to avoid trying to rewrite synthesized casts.
4026 if (LocStart.isInvalid())
4027 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004028 // Need to avoid trying to rewrite casts contained in macros.
4029 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4030 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004031
Steve Naroff54055232008-10-27 17:20:55 +00004032 const char *startBuf = SM->getCharacterData(LocStart);
4033 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00004034
Steve Naroff54055232008-10-27 17:20:55 +00004035 // advance the location to startArgList.
4036 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004037
Steve Naroff54055232008-10-27 17:20:55 +00004038 while (*argPtr++ && (argPtr < endBuf)) {
4039 switch (*argPtr) {
Mike Stump1eb44332009-09-09 15:08:12 +00004040 case '^':
Steve Naroff54055232008-10-27 17:20:55 +00004041 // Replace the '^' with '*'.
4042 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4043 ReplaceText(LocStart, 1, "*", 1);
4044 break;
4045 }
4046 }
4047 return;
4048}
4049
4050void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4051 SourceLocation DeclLoc = FD->getLocation();
4052 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004053
Steve Naroff54055232008-10-27 17:20:55 +00004054 // We have 1 or more arguments that have closure pointers.
4055 const char *startBuf = SM->getCharacterData(DeclLoc);
4056 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004057
Steve Naroff54055232008-10-27 17:20:55 +00004058 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004059
Steve Naroff54055232008-10-27 17:20:55 +00004060 parenCount++;
4061 // advance the location to startArgList.
4062 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4063 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004064
Steve Naroff54055232008-10-27 17:20:55 +00004065 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004066
Steve Naroff54055232008-10-27 17:20:55 +00004067 while (*argPtr++ && parenCount) {
4068 switch (*argPtr) {
Mike Stump1eb44332009-09-09 15:08:12 +00004069 case '^':
Steve Naroff54055232008-10-27 17:20:55 +00004070 // Replace the '^' with '*'.
4071 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4072 ReplaceText(DeclLoc, 1, "*", 1);
4073 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004074 case '(':
4075 parenCount++;
Steve Naroff54055232008-10-27 17:20:55 +00004076 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004077 case ')':
Steve Naroff54055232008-10-27 17:20:55 +00004078 parenCount--;
4079 break;
4080 }
4081 }
4082 return;
4083}
4084
4085bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004086 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004087 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004088 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004089 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004090 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004091 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004092 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004093 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004094 }
4095 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004096 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004097 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004098 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004099 return true;
4100 }
4101 return false;
4102}
4103
Ted Kremenek8189cde2009-02-07 01:47:29 +00004104void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4105 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004106 const char *argPtr = strchr(Name, '(');
4107 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004108
Steve Naroff54055232008-10-27 17:20:55 +00004109 LParen = argPtr; // output the start.
4110 argPtr++; // skip past the left paren.
4111 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004112
Steve Naroff54055232008-10-27 17:20:55 +00004113 while (*argPtr && parenCount) {
4114 switch (*argPtr) {
4115 case '(': parenCount++; break;
4116 case ')': parenCount--; break;
4117 default: break;
4118 }
4119 if (parenCount) argPtr++;
4120 }
4121 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4122 RParen = argPtr; // output the end
4123}
4124
4125void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4126 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4127 RewriteBlockPointerFunctionArgs(FD);
4128 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004129 }
Steve Naroff54055232008-10-27 17:20:55 +00004130 // Handle Variables and Typedefs.
4131 SourceLocation DeclLoc = ND->getLocation();
4132 QualType DeclT;
4133 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4134 DeclT = VD->getType();
4135 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4136 DeclT = TDD->getUnderlyingType();
4137 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4138 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004139 else
Steve Naroff54055232008-10-27 17:20:55 +00004140 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004141
Steve Naroff54055232008-10-27 17:20:55 +00004142 const char *startBuf = SM->getCharacterData(DeclLoc);
4143 const char *endBuf = startBuf;
4144 // scan backward (from the decl location) for the end of the previous decl.
4145 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4146 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004147
Steve Naroff54055232008-10-27 17:20:55 +00004148 // *startBuf != '^' if we are dealing with a pointer to function that
4149 // may take block argument types (which will be handled below).
4150 if (*startBuf == '^') {
4151 // Replace the '^' with '*', computing a negative offset.
4152 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4153 ReplaceText(DeclLoc, 1, "*", 1);
4154 }
4155 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4156 // Replace the '^' with '*' for arguments.
4157 DeclLoc = ND->getLocation();
4158 startBuf = SM->getCharacterData(DeclLoc);
4159 const char *argListBegin, *argListEnd;
4160 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4161 while (argListBegin < argListEnd) {
4162 if (*argListBegin == '^') {
4163 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4164 ReplaceText(CaretLoc, 1, "*", 1);
4165 }
4166 argListBegin++;
4167 }
4168 }
4169 return;
4170}
4171
Mike Stump1eb44332009-09-09 15:08:12 +00004172void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004173 // Add initializers for any closure decl refs.
4174 GetBlockDeclRefExprs(Exp->getBody());
4175 if (BlockDeclRefs.size()) {
4176 // Unique all "by copy" declarations.
4177 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4178 if (!BlockDeclRefs[i]->isByRef())
4179 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4180 // Unique all "by ref" declarations.
4181 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4182 if (BlockDeclRefs[i]->isByRef()) {
4183 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4184 }
4185 // Find any imported blocks...they will need special attention.
4186 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff47a24222008-12-11 20:51:38 +00004187 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004188 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004189 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4190 }
4191 }
4192}
4193
Steve Narofffa15fd92008-10-28 20:29:00 +00004194FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4195 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004196 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00004197 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004198 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor2224f842009-02-25 16:33:18 +00004199 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004200}
4201
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004202Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004203 Blocks.push_back(Exp);
4204
4205 CollectBlockDeclRefInfo(Exp);
4206 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004207
Steve Narofffa15fd92008-10-28 20:29:00 +00004208 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004209 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004210 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004211 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004212 // Convert colons to underscores.
4213 std::string::size_type loc = 0;
4214 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4215 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004216 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004217 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004218
Steve Narofffa15fd92008-10-28 20:29:00 +00004219 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004220
Steve Narofffa15fd92008-10-28 20:29:00 +00004221 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4222 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004223
Steve Narofffa15fd92008-10-28 20:29:00 +00004224 // Get a pointer to the function type so we can cast appropriately.
4225 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4226
4227 FunctionDecl *FD;
4228 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004229
Steve Narofffa15fd92008-10-28 20:29:00 +00004230 // Simulate a contructor call...
4231 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004232 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004233
Steve Narofffa15fd92008-10-28 20:29:00 +00004234 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004235
Steve Narofffdc03722008-10-29 21:23:59 +00004236 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004237 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004238 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4239 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004240 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4241 CastExpr::CK_Unknown, Arg,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004242 Context->VoidPtrTy, SourceLocation(),
4243 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004244 InitExprs.push_back(castExpr);
4245
Steve Narofffa15fd92008-10-28 20:29:00 +00004246 if (ImportedBlockDecls.size()) {
4247 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004248 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004249 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004250 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4251 CastExpr::CK_Unknown, Arg,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004252 Context->VoidPtrTy, SourceLocation(),
4253 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004254 InitExprs.push_back(castExpr);
4255
Steve Narofffa15fd92008-10-28 20:29:00 +00004256 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004257 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004258 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004259 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4260 CastExpr::CK_Unknown, Arg,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004261 Context->VoidPtrTy, SourceLocation(),
4262 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004263 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004264 }
4265 // Add initializers for any closure decl refs.
4266 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004267 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004268 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004269 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004270 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004271 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004272 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004273 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004274 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004275 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004276 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004277 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004278 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4279 CastExpr::CK_Unknown, Arg,
4280 Context->VoidPtrTy,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004281 SourceLocation(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004282 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004283 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004284 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004285 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004286 }
Mike Stump1eb44332009-09-09 15:08:12 +00004287 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004288 }
4289 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004290 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004291 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004292 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004293 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4294 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004295 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00004296 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004297 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004298 }
4299 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004300 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4301 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004302 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004303 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00004304 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004305 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004306 FType, SourceLocation(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004307 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004308 BlockDeclRefs.clear();
4309 BlockByRefDecls.clear();
4310 BlockByCopyDecls.clear();
4311 ImportedBlockDecls.clear();
4312 return NewRep;
4313}
4314
4315//===----------------------------------------------------------------------===//
4316// Function Body / Expression rewriting
4317//===----------------------------------------------------------------------===//
4318
Steve Naroffc77a6362008-12-04 16:24:46 +00004319// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4320// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4321// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4322// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4323// Since the rewriter isn't capable of rewriting rewritten code, it's important
4324// we get this right.
4325void RewriteObjC::CollectPropertySetters(Stmt *S) {
4326 // Perform a bottom up traversal of all children.
4327 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4328 CI != E; ++CI)
4329 if (*CI)
4330 CollectPropertySetters(*CI);
4331
4332 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4333 if (BinOp->isAssignmentOp()) {
4334 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4335 PropSetters[PRE] = BinOp;
4336 }
4337 }
4338}
4339
Steve Narofffa15fd92008-10-28 20:29:00 +00004340Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004341 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004342 isa<DoStmt>(S) || isa<ForStmt>(S))
4343 Stmts.push_back(S);
4344 else if (isa<ObjCForCollectionStmt>(S)) {
4345 Stmts.push_back(S);
4346 ObjCBcLabelNo.push_back(++BcLabelCount);
4347 }
Mike Stump1eb44332009-09-09 15:08:12 +00004348
Steve Narofffa15fd92008-10-28 20:29:00 +00004349 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004350
Steve Narofffa15fd92008-10-28 20:29:00 +00004351 // Perform a bottom up rewrite of all children.
4352 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4353 CI != E; ++CI)
4354 if (*CI) {
4355 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump1eb44332009-09-09 15:08:12 +00004356 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00004357 *CI = newStmt;
4358 }
Mike Stump1eb44332009-09-09 15:08:12 +00004359
Steve Narofffa15fd92008-10-28 20:29:00 +00004360 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4361 // Rewrite the block body in place.
4362 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00004363
Steve Narofffa15fd92008-10-28 20:29:00 +00004364 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004365 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4366 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004367
Steve Narofffa15fd92008-10-28 20:29:00 +00004368 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4369 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004370 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004371 return blockTranscribed;
4372 }
4373 // Handle specific things.
4374 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4375 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004376
Steve Narofffa15fd92008-10-28 20:29:00 +00004377 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4378 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4379
Steve Naroffc77a6362008-12-04 16:24:46 +00004380 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4381 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4382 if (BinOp) {
4383 // Because the rewriter doesn't allow us to rewrite rewritten code,
4384 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004385 DisableReplaceStmt = true;
4386 // Save the source range. Even if we disable the replacement, the
4387 // rewritten node will have been inserted into the tree. If the synthesized
4388 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00004389 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00004390 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4391 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004392 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004393 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004394 //
4395 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4396 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4397 // to see the original expression). Consider this example:
4398 //
4399 // Foo *obj1, *obj2;
4400 //
4401 // obj1.i = [obj2 rrrr];
4402 //
4403 // 'BinOp' for the previous expression looks like:
4404 //
4405 // (BinaryOperator 0x231ccf0 'int' '='
4406 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4407 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4408 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4409 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4410 //
4411 // 'newStmt' represents the rewritten message expression. For example:
4412 //
4413 // (CallExpr 0x231d300 'id':'struct objc_object *'
4414 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4415 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4416 // (CStyleCastExpr 0x231d220 'void *'
4417 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4418 //
4419 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4420 // can be used as the setter argument. ReplaceStmt() will still 'see'
4421 // the original RHS (since we haven't altered BinOp).
4422 //
Mike Stump1eb44332009-09-09 15:08:12 +00004423 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00004424 // node. As a result, we now leak the original AST nodes.
4425 //
Steve Naroffb619d952008-12-09 12:56:34 +00004426 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004427 } else {
4428 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004429 }
4430 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004431 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4432 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004433
Steve Narofffa15fd92008-10-28 20:29:00 +00004434 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4435 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004436
Steve Narofffa15fd92008-10-28 20:29:00 +00004437 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004438#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004439 // Before we rewrite it, put the original message expression in a comment.
4440 SourceLocation startLoc = MessExpr->getLocStart();
4441 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004442
Steve Narofffa15fd92008-10-28 20:29:00 +00004443 const char *startBuf = SM->getCharacterData(startLoc);
4444 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004445
Steve Narofffa15fd92008-10-28 20:29:00 +00004446 std::string messString;
4447 messString += "// ";
4448 messString.append(startBuf, endBuf-startBuf+1);
4449 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004450
4451 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004452 // InsertText(clang::SourceLocation, char const*, unsigned int).
4453 // InsertText(startLoc, messString.c_str(), messString.size());
4454 // Tried this, but it didn't work either...
4455 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004456#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004457 return RewriteMessageExpr(MessExpr);
4458 }
Mike Stump1eb44332009-09-09 15:08:12 +00004459
Steve Narofffa15fd92008-10-28 20:29:00 +00004460 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4461 return RewriteObjCTryStmt(StmtTry);
4462
4463 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4464 return RewriteObjCSynchronizedStmt(StmtTry);
4465
4466 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4467 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004468
Steve Narofffa15fd92008-10-28 20:29:00 +00004469 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4470 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004471
4472 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004473 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004474 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004475 OrigStmtRange.getEnd());
4476 if (BreakStmt *StmtBreakStmt =
4477 dyn_cast<BreakStmt>(S))
4478 return RewriteBreakStmt(StmtBreakStmt);
4479 if (ContinueStmt *StmtContinueStmt =
4480 dyn_cast<ContinueStmt>(S))
4481 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004482
4483 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004484 // and cast exprs.
4485 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4486 // FIXME: What we're doing here is modifying the type-specifier that
4487 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004488 // a separate type-specifier that we can rewrite.
Steve Narofffa15fd92008-10-28 20:29:00 +00004489 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004490
Steve Narofffa15fd92008-10-28 20:29:00 +00004491 // Blocks rewrite rules.
4492 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4493 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004494 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004495 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004496 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004497 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004498 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004499 CheckFunctionPointerDecl(ND->getType(), ND);
4500 }
4501 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004502 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004503 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004504 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004505 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4506 }
4507 }
4508 }
Mike Stump1eb44332009-09-09 15:08:12 +00004509
Steve Narofffa15fd92008-10-28 20:29:00 +00004510 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4511 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004512
4513 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004514 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4515 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004516 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4517 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004518 && "Statement stack mismatch");
4519 Stmts.pop_back();
4520 }
4521 // Handle blocks rewriting.
4522 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4523 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00004524 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004525 }
4526 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004527 if (CE->getCallee()->getType()->isBlockPointerType()) {
4528 Stmt *BlockCall = SynthesizeBlockCall(CE);
4529 ReplaceStmt(S, BlockCall);
4530 return BlockCall;
4531 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004532 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004533 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004534 RewriteCastExpr(CE);
4535 }
4536#if 0
4537 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004538 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004539 // Get the new text.
4540 std::string SStr;
4541 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00004542 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00004543 const std::string &Str = Buf.str();
4544
4545 printf("CAST = %s\n", &Str[0]);
4546 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4547 delete S;
4548 return Replacement;
4549 }
4550#endif
4551 // Return this stmt unmodified.
4552 return S;
4553}
4554
4555/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4556/// main file of the input.
4557void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4558 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00004559 if (FD->isOverloadedOperator())
4560 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004561
Steve Narofffa15fd92008-10-28 20:29:00 +00004562 // Since function prototypes don't have ParmDecl's, we check the function
4563 // prototype. This enables us to rewrite function declarations and
4564 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00004565 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004566
Sebastian Redld3a413d2009-04-26 20:35:05 +00004567 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00004568 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004569 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004570 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004571 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00004572 Body =
4573 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4574 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004575 CurrentBody = 0;
4576 if (PropParentMap) {
4577 delete PropParentMap;
4578 PropParentMap = 0;
4579 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004580 // This synthesizes and inserts the block "impl" struct, invoke function,
4581 // and any copy/dispose helper functions.
4582 InsertBlockLiteralsWithinFunction(FD);
4583 CurFunctionDef = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004584 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004585 return;
4586 }
4587 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00004588 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004589 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004590 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004591 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00004592 Body =
4593 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4594 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004595 CurrentBody = 0;
4596 if (PropParentMap) {
4597 delete PropParentMap;
4598 PropParentMap = 0;
4599 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004600 InsertBlockLiteralsWithinMethod(MD);
4601 CurMethodDef = 0;
4602 }
4603 }
4604 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4605 ClassImplementation.push_back(CI);
4606 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4607 CategoryImplementation.push_back(CI);
4608 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4609 RewriteForwardClassDecl(CD);
4610 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4611 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004612 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004613 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004614 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004615 CheckFunctionPointerDecl(VD->getType(), VD);
4616 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004617 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004618 RewriteCastExpr(CE);
4619 }
4620 }
4621 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004622 if (VD->getInit()) {
4623 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004624 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004625 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004626 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004627 CurrentBody = 0;
4628 if (PropParentMap) {
4629 delete PropParentMap;
4630 PropParentMap = 0;
4631 }
Mike Stump1eb44332009-09-09 15:08:12 +00004632 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004633 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004634 GlobalVarDecl = 0;
4635
4636 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004637 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004638 RewriteCastExpr(CE);
4639 }
4640 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004641 return;
4642 }
4643 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004644 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004645 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004646 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004647 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4648 return;
4649 }
4650 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4651 if (RD->isDefinition()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004652 for (RecordDecl::field_iterator i = RD->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004653 e = RD->field_end(); i != e; ++i) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004654 FieldDecl *FD = *i;
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004655 if (isTopLevelBlockPointerType(FD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004656 RewriteBlockPointerDecl(FD);
4657 }
4658 }
4659 return;
4660 }
4661 // Nothing yet.
4662}
4663
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00004664void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004665 // Get the top-level buffer that this corresponds to.
Mike Stump1eb44332009-09-09 15:08:12 +00004666
Steve Narofffa15fd92008-10-28 20:29:00 +00004667 // Rewrite tabs if we care.
4668 //RewriteTabs();
Mike Stump1eb44332009-09-09 15:08:12 +00004669
Steve Narofffa15fd92008-10-28 20:29:00 +00004670 if (Diags.hasErrorOccurred())
4671 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004672
Steve Narofffa15fd92008-10-28 20:29:00 +00004673 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00004674
Steve Naroff621edce2009-04-29 16:37:50 +00004675 // Here's a great place to add any extra declarations that may be needed.
4676 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00004677 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004678 E = ProtocolExprDecls.end(); I != E; ++I)
4679 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4680
Mike Stump1eb44332009-09-09 15:08:12 +00004681 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00004682 Preamble.c_str(), Preamble.size(), false);
Steve Naroff0aab7962008-11-14 14:10:01 +00004683 if (ClassImplementation.size() || CategoryImplementation.size())
4684 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00004685
Steve Narofffa15fd92008-10-28 20:29:00 +00004686 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4687 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00004688 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00004689 Rewrite.getRewriteBufferFor(MainFileID)) {
4690 //printf("Changed:\n");
4691 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4692 } else {
4693 fprintf(stderr, "No changes\n");
4694 }
Steve Narofface66252008-11-13 20:07:04 +00004695
Steve Naroff621edce2009-04-29 16:37:50 +00004696 if (ClassImplementation.size() || CategoryImplementation.size() ||
4697 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00004698 // Rewrite Objective-c meta data*
4699 std::string ResultStr;
4700 SynthesizeMetaDataIntoBuffer(ResultStr);
4701 // Emit metadata.
4702 *OutFile << ResultStr;
4703 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004704 OutFile->flush();
4705}
4706