blob: 93f36ee7f8316712c19095daeb0221f654284201 [file] [log] [blame]
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenek305c6132012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000018#include "clang/AST/ParentMap.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000019#include "clang/Basic/Diagnostic.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000020#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/SourceManager.h"
Benjamin Kramer9852f582012-12-01 16:35:25 +000022#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000023#include "clang/Lex/Lexer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000025#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/OwningPtr.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000029#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000031
32using namespace clang;
33using llvm::utostr;
34
35namespace {
36 class RewriteModernObjC : public ASTConsumer {
37 protected:
38
39 enum {
40 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
41 block, ... */
42 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
43 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
44 __block variable */
45 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
46 helpers */
47 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
48 support routines */
49 BLOCK_BYREF_CURRENT_MAX = 256
50 };
51
52 enum {
53 BLOCK_NEEDS_FREE = (1 << 24),
54 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
55 BLOCK_HAS_CXX_OBJ = (1 << 26),
56 BLOCK_IS_GC = (1 << 27),
57 BLOCK_IS_GLOBAL = (1 << 28),
58 BLOCK_HAS_DESCRIPTOR = (1 << 29)
59 };
60 static const int OBJC_ABI_VERSION = 7;
61
62 Rewriter Rewrite;
63 DiagnosticsEngine &Diags;
64 const LangOptions &LangOpts;
65 ASTContext *Context;
66 SourceManager *SM;
67 TranslationUnitDecl *TUDecl;
68 FileID MainFileID;
69 const char *MainFileStart, *MainFileEnd;
70 Stmt *CurrentBody;
71 ParentMap *PropParentMap; // created lazily.
72 std::string InFileName;
73 raw_ostream* OutFile;
74 std::string Preamble;
75
76 TypeDecl *ProtocolTypeDecl;
77 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000078 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000080 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000081 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
85
86 // ObjC foreach break/continue generation support.
87 int BcLabelCount;
88
89 unsigned TryFinallyContainsReturnDiag;
90 // Needed for super.
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
94
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
105 FunctionDecl *SuperContructorFunctionDecl;
106 FunctionDecl *CurFunctionDef;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000107
108 /* Misc. containers needed for meta-data rewrite. */
109 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
110 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
112 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000114 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000115 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000116 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
117 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
118
119 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
120 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
121
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000122 SmallVector<Stmt *, 32> Stmts;
123 SmallVector<int, 8> ObjCBcLabelNo;
124 // Remember all the @protocol(<expr>) expressions.
125 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
126
127 llvm::DenseSet<uint64_t> CopyDestroyCache;
128
129 // Block expressions.
130 SmallVector<BlockExpr *, 32> Blocks;
131 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000133
John McCallf4b88a42012-03-10 09:33:50 +0000134 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000135
136 // Block related declarations.
137 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
138 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
139 SmallVector<ValueDecl *, 8> BlockByRefDecls;
140 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
141 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
142 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
143 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
144
145 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000146 llvm::DenseMap<ObjCInterfaceDecl *,
147 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
148
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000149 // This maps an original source AST to it's rewritten form. This allows
150 // us to avoid rewriting the same node twice (which is very uncommon).
151 // This is needed to support some of the exotic property rewriting.
152 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
153
154 // Needed for header files being rewritten
155 bool IsHeader;
156 bool SilenceRewriteMacroWarning;
157 bool objc_impl_method;
158
159 bool DisableReplaceStmt;
160 class DisableReplaceStmtScope {
161 RewriteModernObjC &R;
162 bool SavedValue;
163
164 public:
165 DisableReplaceStmtScope(RewriteModernObjC &R)
166 : R(R), SavedValue(R.DisableReplaceStmt) {
167 R.DisableReplaceStmt = true;
168 }
169 ~DisableReplaceStmtScope() {
170 R.DisableReplaceStmt = SavedValue;
171 }
172 };
173 void InitializeCommon(ASTContext &context);
174
175 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000176 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000177 // Top Level Driver code.
178 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
179 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
180 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
181 if (!Class->isThisDeclarationADefinition()) {
182 RewriteForwardClassDecl(D);
183 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000184 } else {
185 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000186 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000187 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000188 }
189 }
190
191 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
192 if (!Proto->isThisDeclarationADefinition()) {
193 RewriteForwardProtocolDecl(D);
194 break;
195 }
196 }
197
198 HandleTopLevelSingleDecl(*I);
199 }
200 return true;
201 }
202 void HandleTopLevelSingleDecl(Decl *D);
203 void HandleDeclInMainFile(Decl *D);
204 RewriteModernObjC(std::string inFile, raw_ostream *OS,
205 DiagnosticsEngine &D, const LangOptions &LOpts,
206 bool silenceMacroWarn);
207
208 ~RewriteModernObjC() {}
209
210 virtual void HandleTranslationUnit(ASTContext &C);
211
212 void ReplaceStmt(Stmt *Old, Stmt *New) {
213 Stmt *ReplacingStmt = ReplacedNodes[Old];
214
215 if (ReplacingStmt)
216 return; // We can't rewrite the same node twice.
217
218 if (DisableReplaceStmt)
219 return;
220
221 // If replacement succeeded or warning disabled return with no warning.
222 if (!Rewrite.ReplaceStmt(Old, New)) {
223 ReplacedNodes[Old] = New;
224 return;
225 }
226 if (SilenceRewriteMacroWarning)
227 return;
228 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
229 << Old->getSourceRange();
230 }
231
232 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
233 if (DisableReplaceStmt)
234 return;
235
236 // Measure the old text.
237 int Size = Rewrite.getRangeSize(SrcRange);
238 if (Size == -1) {
239 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
240 << Old->getSourceRange();
241 return;
242 }
243 // Get the new text.
244 std::string SStr;
245 llvm::raw_string_ostream S(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +0000246 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000247 const std::string &Str = S.str();
248
249 // If replacement succeeded or warning disabled return with no warning.
250 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
251 ReplacedNodes[Old] = New;
252 return;
253 }
254 if (SilenceRewriteMacroWarning)
255 return;
256 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
257 << Old->getSourceRange();
258 }
259
260 void InsertText(SourceLocation Loc, StringRef Str,
261 bool InsertAfter = true) {
262 // If insertion succeeded or warning disabled return with no warning.
263 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
264 SilenceRewriteMacroWarning)
265 return;
266
267 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
268 }
269
270 void ReplaceText(SourceLocation Start, unsigned OrigLength,
271 StringRef Str) {
272 // If removal succeeded or warning disabled return with no warning.
273 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
274 SilenceRewriteMacroWarning)
275 return;
276
277 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
278 }
279
280 // Syntactic Rewriting.
281 void RewriteRecordBody(RecordDecl *RD);
282 void RewriteInclude();
Fariborz Jahanian96205962012-11-06 17:30:23 +0000283 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianf616ae22012-11-06 23:25:49 +0000284 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
285 std::string &LineString);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000286 void RewriteForwardClassDecl(DeclGroupRef D);
287 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
288 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
289 const std::string &typedefString);
290 void RewriteImplementations();
291 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
292 ObjCImplementationDecl *IMD,
293 ObjCCategoryImplDecl *CID);
294 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
295 void RewriteImplementationDecl(Decl *Dcl);
296 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
297 ObjCMethodDecl *MDecl, std::string &ResultStr);
298 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
299 const FunctionType *&FPRetType);
300 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
301 ValueDecl *VD, bool def=false);
302 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
303 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
304 void RewriteForwardProtocolDecl(DeclGroupRef D);
305 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
306 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
307 void RewriteProperty(ObjCPropertyDecl *prop);
308 void RewriteFunctionDecl(FunctionDecl *FD);
309 void RewriteBlockPointerType(std::string& Str, QualType Type);
310 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000311 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000312 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
313 void RewriteTypeOfDecl(VarDecl *VD);
314 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000315
316 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000317
318 // Expression Rewriting.
319 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
320 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
321 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
322 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
323 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
324 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
325 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000326 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000327 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000328 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000329 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000330 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000331 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian042b91d2012-05-23 23:47:20 +0000332 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000333 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
334 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
335 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
336 SourceLocation OrigEnd);
337 Stmt *RewriteBreakStmt(BreakStmt *S);
338 Stmt *RewriteContinueStmt(ContinueStmt *S);
339 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000340 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000341 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000342
343 // Block rewriting.
344 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
345
346 // Block specific rewrite rules.
347 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000348 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000349 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000350 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
351 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
352
353 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
354 std::string &Result);
355
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000356 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000357 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000358 bool &IsNamedDefinition);
359 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
360 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000361
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000362 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
363
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000364 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
365 std::string &Result);
366
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000367 virtual void Initialize(ASTContext &context);
368
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000369 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000370 // rewriting routines on the new ASTs.
371 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
372 Expr **args, unsigned nargs,
373 SourceLocation StartLoc=SourceLocation(),
374 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000375
376 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
377 QualType msgSendType,
378 QualType returnType,
379 SmallVectorImpl<QualType> &ArgTypes,
380 SmallVectorImpl<Expr*> &MsgExprs,
381 ObjCMethodDecl *Method);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000382
383 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
384 SourceLocation StartLoc=SourceLocation(),
385 SourceLocation EndLoc=SourceLocation());
386
387 void SynthCountByEnumWithState(std::string &buf);
388 void SynthMsgSendFunctionDecl();
389 void SynthMsgSendSuperFunctionDecl();
390 void SynthMsgSendStretFunctionDecl();
391 void SynthMsgSendFpretFunctionDecl();
392 void SynthMsgSendSuperStretFunctionDecl();
393 void SynthGetClassFunctionDecl();
394 void SynthGetMetaClassFunctionDecl();
395 void SynthGetSuperClassFunctionDecl();
396 void SynthSelGetUidFunctionDecl();
397 void SynthSuperContructorFunctionDecl();
398
399 // Rewriting metadata
400 template<typename MethodIterator>
401 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
402 MethodIterator MethodEnd,
403 bool IsInstanceMethod,
404 StringRef prefix,
405 StringRef ClassName,
406 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000407 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
408 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000409 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000410 const ObjCList<ObjCProtocolDecl> &Prots,
411 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000412 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000413 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000414 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000415
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000416 void RewriteMetaDataIntoBuffer(std::string &Result);
417 void WriteImageInfo(std::string &Result);
418 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000419 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000420 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000421
422 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000423 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000424 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000425 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000426
427
428 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
429 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
430 StringRef funcName, std::string Tag);
431 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
432 StringRef funcName, std::string Tag);
433 std::string SynthesizeBlockImpl(BlockExpr *CE,
434 std::string Tag, std::string Desc);
435 std::string SynthesizeBlockDescriptor(std::string DescTag,
436 std::string ImplTag,
437 int i, StringRef funcName,
438 unsigned hasCopy);
439 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
440 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
441 StringRef FunName);
442 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
443 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000444 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000445
446 // Misc. helper routines.
447 QualType getProtocolType();
448 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000449 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
450 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
451 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
452
453 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
454 void CollectBlockDeclRefInfo(BlockExpr *Exp);
455 void GetBlockDeclRefExprs(Stmt *S);
456 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000457 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000458 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
459
460 // We avoid calling Type::isBlockPointerType(), since it operates on the
461 // canonical type. We only care if the top-level type is a closure pointer.
462 bool isTopLevelBlockPointerType(QualType T) {
463 return isa<BlockPointerType>(T);
464 }
465
466 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
467 /// to a function pointer type and upon success, returns true; false
468 /// otherwise.
469 bool convertBlockPointerToFunctionPointer(QualType &T) {
470 if (isTopLevelBlockPointerType(T)) {
471 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
472 T = Context->getPointerType(BPT->getPointeeType());
473 return true;
474 }
475 return false;
476 }
477
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000478 bool convertObjCTypeToCStyleType(QualType &T);
479
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000480 bool needToScanForQualifiers(QualType T);
481 QualType getSuperStructType();
482 QualType getConstantStringStructType();
483 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
484 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
485
486 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000487 if (T->isObjCQualifiedIdType()) {
488 bool isConst = T.isConstQualified();
489 T = isConst ? Context->getObjCIdType().withConst()
490 : Context->getObjCIdType();
491 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000492 else if (T->isObjCQualifiedClassType())
493 T = Context->getObjCClassType();
494 else if (T->isObjCObjectPointerType() &&
495 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
496 if (const ObjCObjectPointerType * OBJPT =
497 T->getAsObjCInterfacePointerType()) {
498 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
499 T = QualType(IFaceT, 0);
500 T = Context->getPointerType(T);
501 }
502 }
503 }
504
505 // FIXME: This predicate seems like it would be useful to add to ASTContext.
506 bool isObjCType(QualType T) {
507 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
508 return false;
509
510 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
511
512 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
513 OCT == Context->getCanonicalType(Context->getObjCClassType()))
514 return true;
515
516 if (const PointerType *PT = OCT->getAs<PointerType>()) {
517 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
518 PT->getPointeeType()->isObjCQualifiedIdType())
519 return true;
520 }
521 return false;
522 }
523 bool PointerTypeTakesAnyBlockArguments(QualType QT);
524 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
525 void GetExtentOfArgList(const char *Name, const char *&LParen,
526 const char *&RParen);
527
528 void QuoteDoublequotes(std::string &From, std::string &To) {
529 for (unsigned i = 0; i < From.length(); i++) {
530 if (From[i] == '"')
531 To += "\\\"";
532 else
533 To += From[i];
534 }
535 }
536
537 QualType getSimpleFunctionType(QualType result,
538 const QualType *args,
539 unsigned numArgs,
540 bool variadic = false) {
541 if (result == Context->getObjCInstanceType())
542 result = Context->getObjCIdType();
543 FunctionProtoType::ExtProtoInfo fpi;
544 fpi.Variadic = variadic;
545 return Context->getFunctionType(result, args, numArgs, fpi);
546 }
547
548 // Helper function: create a CStyleCastExpr with trivial type source info.
549 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
550 CastKind Kind, Expr *E) {
551 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
552 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
553 SourceLocation(), SourceLocation());
554 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000555
556 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
557 IdentifierInfo* II = &Context->Idents.get("load");
558 Selector LoadSel = Context->Selectors.getSelector(0, &II);
559 return OD->getClassMethod(LoadSel) != 0;
560 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000561 };
562
563}
564
565void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
566 NamedDecl *D) {
567 if (const FunctionProtoType *fproto
568 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
569 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
570 E = fproto->arg_type_end(); I && (I != E); ++I)
571 if (isTopLevelBlockPointerType(*I)) {
572 // All the args are checked/rewritten. Don't call twice!
573 RewriteBlockPointerDecl(D);
574 break;
575 }
576 }
577}
578
579void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
580 const PointerType *PT = funcType->getAs<PointerType>();
581 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
582 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
583}
584
585static bool IsHeaderFile(const std::string &Filename) {
586 std::string::size_type DotPos = Filename.rfind('.');
587
588 if (DotPos == std::string::npos) {
589 // no file extension
590 return false;
591 }
592
593 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
594 // C header: .h
595 // C++ header: .hh or .H;
596 return Ext == "h" || Ext == "hh" || Ext == "H";
597}
598
599RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
600 DiagnosticsEngine &D, const LangOptions &LOpts,
601 bool silenceMacroWarn)
602 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
603 SilenceRewriteMacroWarning(silenceMacroWarn) {
604 IsHeader = IsHeaderFile(inFile);
605 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
606 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000607 // FIXME. This should be an error. But if block is not called, it is OK. And it
608 // may break including some headers.
609 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
610 "rewriting block literal declared in global scope is not implemented");
611
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000612 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
613 DiagnosticsEngine::Warning,
614 "rewriter doesn't support user-specified control flow semantics "
615 "for @try/@finally (code may not execute properly)");
616}
617
618ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
619 raw_ostream* OS,
620 DiagnosticsEngine &Diags,
621 const LangOptions &LOpts,
622 bool SilenceRewriteMacroWarning) {
623 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
624}
625
626void RewriteModernObjC::InitializeCommon(ASTContext &context) {
627 Context = &context;
628 SM = &Context->getSourceManager();
629 TUDecl = Context->getTranslationUnitDecl();
630 MsgSendFunctionDecl = 0;
631 MsgSendSuperFunctionDecl = 0;
632 MsgSendStretFunctionDecl = 0;
633 MsgSendSuperStretFunctionDecl = 0;
634 MsgSendFpretFunctionDecl = 0;
635 GetClassFunctionDecl = 0;
636 GetMetaClassFunctionDecl = 0;
637 GetSuperClassFunctionDecl = 0;
638 SelGetUidFunctionDecl = 0;
639 CFStringFunctionDecl = 0;
640 ConstantStringClassReference = 0;
641 NSStringRecord = 0;
642 CurMethodDef = 0;
643 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000644 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000645 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000646 SuperStructDecl = 0;
647 ProtocolTypeDecl = 0;
648 ConstantStringDecl = 0;
649 BcLabelCount = 0;
650 SuperContructorFunctionDecl = 0;
651 NumObjCStringLiterals = 0;
652 PropParentMap = 0;
653 CurrentBody = 0;
654 DisableReplaceStmt = false;
655 objc_impl_method = false;
656
657 // Get the ID and start/end of the main file.
658 MainFileID = SM->getMainFileID();
659 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
660 MainFileStart = MainBuf->getBufferStart();
661 MainFileEnd = MainBuf->getBufferEnd();
662
David Blaikie4e4d0842012-03-11 07:00:24 +0000663 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000664}
665
666//===----------------------------------------------------------------------===//
667// Top Level Driver Code
668//===----------------------------------------------------------------------===//
669
670void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
671 if (Diags.hasErrorOccurred())
672 return;
673
674 // Two cases: either the decl could be in the main file, or it could be in a
675 // #included file. If the former, rewrite it now. If the later, check to see
676 // if we rewrote the #include/#import.
677 SourceLocation Loc = D->getLocation();
678 Loc = SM->getExpansionLoc(Loc);
679
680 // If this is for a builtin, ignore it.
681 if (Loc.isInvalid()) return;
682
683 // Look for built-in declarations that we need to refer during the rewrite.
684 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
685 RewriteFunctionDecl(FD);
686 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
687 // declared in <Foundation/NSString.h>
688 if (FVD->getName() == "_NSConstantStringClassReference") {
689 ConstantStringClassReference = FVD;
690 return;
691 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000692 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
693 RewriteCategoryDecl(CD);
694 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
695 if (PD->isThisDeclarationADefinition())
696 RewriteProtocolDecl(PD);
697 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000698 // FIXME. This will not work in all situations and leaving it out
699 // is harmless.
700 // RewriteLinkageSpec(LSD);
701
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000702 // Recurse into linkage specifications
703 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
704 DIEnd = LSD->decls_end();
705 DI != DIEnd; ) {
706 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
707 if (!IFace->isThisDeclarationADefinition()) {
708 SmallVector<Decl *, 8> DG;
709 SourceLocation StartLoc = IFace->getLocStart();
710 do {
711 if (isa<ObjCInterfaceDecl>(*DI) &&
712 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
713 StartLoc == (*DI)->getLocStart())
714 DG.push_back(*DI);
715 else
716 break;
717
718 ++DI;
719 } while (DI != DIEnd);
720 RewriteForwardClassDecl(DG);
721 continue;
722 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000723 else {
724 // Keep track of all interface declarations seen.
725 ObjCInterfacesSeen.push_back(IFace);
726 ++DI;
727 continue;
728 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000729 }
730
731 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
732 if (!Proto->isThisDeclarationADefinition()) {
733 SmallVector<Decl *, 8> DG;
734 SourceLocation StartLoc = Proto->getLocStart();
735 do {
736 if (isa<ObjCProtocolDecl>(*DI) &&
737 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
738 StartLoc == (*DI)->getLocStart())
739 DG.push_back(*DI);
740 else
741 break;
742
743 ++DI;
744 } while (DI != DIEnd);
745 RewriteForwardProtocolDecl(DG);
746 continue;
747 }
748 }
749
750 HandleTopLevelSingleDecl(*DI);
751 ++DI;
752 }
753 }
754 // If we have a decl in the main file, see if we should rewrite it.
755 if (SM->isFromMainFile(Loc))
756 return HandleDeclInMainFile(D);
757}
758
759//===----------------------------------------------------------------------===//
760// Syntactic (non-AST) Rewriting Code
761//===----------------------------------------------------------------------===//
762
763void RewriteModernObjC::RewriteInclude() {
764 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
765 StringRef MainBuf = SM->getBufferData(MainFileID);
766 const char *MainBufStart = MainBuf.begin();
767 const char *MainBufEnd = MainBuf.end();
768 size_t ImportLen = strlen("import");
769
770 // Loop over the whole file, looking for includes.
771 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
772 if (*BufPtr == '#') {
773 if (++BufPtr == MainBufEnd)
774 return;
775 while (*BufPtr == ' ' || *BufPtr == '\t')
776 if (++BufPtr == MainBufEnd)
777 return;
778 if (!strncmp(BufPtr, "import", ImportLen)) {
779 // replace import with include
780 SourceLocation ImportLoc =
781 LocStart.getLocWithOffset(BufPtr-MainBufStart);
782 ReplaceText(ImportLoc, ImportLen, "include");
783 BufPtr += ImportLen;
784 }
785 }
786 }
787}
788
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000789static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
790 ObjCIvarDecl *IvarDecl, std::string &Result) {
791 Result += "OBJC_IVAR_$_";
792 Result += IDecl->getName();
793 Result += "$";
794 Result += IvarDecl->getName();
795}
796
797std::string
798RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
799 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
800
801 // Build name of symbol holding ivar offset.
802 std::string IvarOffsetName;
803 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
804
805
806 std::string S = "(*(";
807 QualType IvarT = D->getType();
808
809 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
810 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
811 RD = RD->getDefinition();
812 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
813 // decltype(((Foo_IMPL*)0)->bar) *
814 ObjCContainerDecl *CDecl =
815 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
816 // ivar in class extensions requires special treatment.
817 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
818 CDecl = CatDecl->getClassInterface();
819 std::string RecName = CDecl->getName();
820 RecName += "_IMPL";
821 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
822 SourceLocation(), SourceLocation(),
823 &Context->Idents.get(RecName.c_str()));
824 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
825 unsigned UnsignedIntSize =
826 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
827 Expr *Zero = IntegerLiteral::Create(*Context,
828 llvm::APInt(UnsignedIntSize, 0),
829 Context->UnsignedIntTy, SourceLocation());
830 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
831 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
832 Zero);
833 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
834 SourceLocation(),
835 &Context->Idents.get(D->getNameAsString()),
836 IvarT, 0,
837 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +0000838 ICIS_NoInit);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000839 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
840 FD->getType(), VK_LValue,
841 OK_Ordinary);
842 IvarT = Context->getDecltypeType(ME, ME->getType());
843 }
844 }
845 convertObjCTypeToCStyleType(IvarT);
846 QualType castT = Context->getPointerType(IvarT);
847 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
848 S += TypeString;
849 S += ")";
850
851 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
852 S += "((char *)self + ";
853 S += IvarOffsetName;
854 S += "))";
855 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000856 return S;
857}
858
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000859/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
860/// been found in the class implementation. In this case, it must be synthesized.
861static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
862 ObjCPropertyDecl *PD,
863 bool getter) {
864 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
865 : !IMP->getInstanceMethod(PD->getSetterName());
866
867}
868
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000869void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
870 ObjCImplementationDecl *IMD,
871 ObjCCategoryImplDecl *CID) {
872 static bool objcGetPropertyDefined = false;
873 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000874 SourceLocation startGetterSetterLoc;
875
876 if (PID->getLocStart().isValid()) {
877 SourceLocation startLoc = PID->getLocStart();
878 InsertText(startLoc, "// ");
879 const char *startBuf = SM->getCharacterData(startLoc);
880 assert((*startBuf == '@') && "bogus @synthesize location");
881 const char *semiBuf = strchr(startBuf, ';');
882 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
883 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
884 }
885 else
886 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000887
888 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
889 return; // FIXME: is this correct?
890
891 // Generate the 'getter' function.
892 ObjCPropertyDecl *PD = PID->getPropertyDecl();
893 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
894
895 if (!OID)
896 return;
897 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000898 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000899 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
900 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
901 ObjCPropertyDecl::OBJC_PR_copy));
902 std::string Getr;
903 if (GenGetProperty && !objcGetPropertyDefined) {
904 objcGetPropertyDefined = true;
905 // FIXME. Is this attribute correct in all cases?
906 Getr = "\nextern \"C\" __declspec(dllimport) "
907 "id objc_getProperty(id, SEL, long, bool);\n";
908 }
909 RewriteObjCMethodDecl(OID->getContainingInterface(),
910 PD->getGetterMethodDecl(), Getr);
911 Getr += "{ ";
912 // Synthesize an explicit cast to gain access to the ivar.
913 // See objc-act.c:objc_synthesize_new_getter() for details.
914 if (GenGetProperty) {
915 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
916 Getr += "typedef ";
917 const FunctionType *FPRetType = 0;
918 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
919 FPRetType);
920 Getr += " _TYPE";
921 if (FPRetType) {
922 Getr += ")"; // close the precedence "scope" for "*".
923
924 // Now, emit the argument types (if any).
925 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
926 Getr += "(";
927 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
928 if (i) Getr += ", ";
929 std::string ParamStr = FT->getArgType(i).getAsString(
930 Context->getPrintingPolicy());
931 Getr += ParamStr;
932 }
933 if (FT->isVariadic()) {
934 if (FT->getNumArgs()) Getr += ", ";
935 Getr += "...";
936 }
937 Getr += ")";
938 } else
939 Getr += "()";
940 }
941 Getr += ";\n";
942 Getr += "return (_TYPE)";
943 Getr += "objc_getProperty(self, _cmd, ";
944 RewriteIvarOffsetComputation(OID, Getr);
945 Getr += ", 1)";
946 }
947 else
948 Getr += "return " + getIvarAccessString(OID);
949 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000950 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000951 }
952
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000953 if (PD->isReadOnly() ||
954 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000955 return;
956
957 // Generate the 'setter' function.
958 std::string Setr;
959 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
960 ObjCPropertyDecl::OBJC_PR_copy);
961 if (GenSetProperty && !objcSetPropertyDefined) {
962 objcSetPropertyDefined = true;
963 // FIXME. Is this attribute correct in all cases?
964 Setr = "\nextern \"C\" __declspec(dllimport) "
965 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
966 }
967
968 RewriteObjCMethodDecl(OID->getContainingInterface(),
969 PD->getSetterMethodDecl(), Setr);
970 Setr += "{ ";
971 // Synthesize an explicit cast to initialize the ivar.
972 // See objc-act.c:objc_synthesize_new_setter() for details.
973 if (GenSetProperty) {
974 Setr += "objc_setProperty (self, _cmd, ";
975 RewriteIvarOffsetComputation(OID, Setr);
976 Setr += ", (id)";
977 Setr += PD->getName();
978 Setr += ", ";
979 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
980 Setr += "0, ";
981 else
982 Setr += "1, ";
983 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
984 Setr += "1)";
985 else
986 Setr += "0)";
987 }
988 else {
989 Setr += getIvarAccessString(OID) + " = ";
990 Setr += PD->getName();
991 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000992 Setr += "; }\n";
993 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000994}
995
996static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
997 std::string &typedefString) {
998 typedefString += "#ifndef _REWRITER_typedef_";
999 typedefString += ForwardDecl->getNameAsString();
1000 typedefString += "\n";
1001 typedefString += "#define _REWRITER_typedef_";
1002 typedefString += ForwardDecl->getNameAsString();
1003 typedefString += "\n";
1004 typedefString += "typedef struct objc_object ";
1005 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001006 // typedef struct { } _objc_exc_Classname;
1007 typedefString += ";\ntypedef struct {} _objc_exc_";
1008 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001009 typedefString += ";\n#endif\n";
1010}
1011
1012void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1013 const std::string &typedefString) {
1014 SourceLocation startLoc = ClassDecl->getLocStart();
1015 const char *startBuf = SM->getCharacterData(startLoc);
1016 const char *semiPtr = strchr(startBuf, ';');
1017 // Replace the @class with typedefs corresponding to the classes.
1018 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1019}
1020
1021void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1022 std::string typedefString;
1023 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1024 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1025 if (I == D.begin()) {
1026 // Translate to typedef's that forward reference structs with the same name
1027 // as the class. As a convenience, we include the original declaration
1028 // as a comment.
1029 typedefString += "// @class ";
1030 typedefString += ForwardDecl->getNameAsString();
1031 typedefString += ";\n";
1032 }
1033 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1034 }
1035 DeclGroupRef::iterator I = D.begin();
1036 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1037}
1038
1039void RewriteModernObjC::RewriteForwardClassDecl(
1040 const llvm::SmallVector<Decl*, 8> &D) {
1041 std::string typedefString;
1042 for (unsigned i = 0; i < D.size(); i++) {
1043 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1044 if (i == 0) {
1045 typedefString += "// @class ";
1046 typedefString += ForwardDecl->getNameAsString();
1047 typedefString += ";\n";
1048 }
1049 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1050 }
1051 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1052}
1053
1054void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1055 // When method is a synthesized one, such as a getter/setter there is
1056 // nothing to rewrite.
1057 if (Method->isImplicit())
1058 return;
1059 SourceLocation LocStart = Method->getLocStart();
1060 SourceLocation LocEnd = Method->getLocEnd();
1061
1062 if (SM->getExpansionLineNumber(LocEnd) >
1063 SM->getExpansionLineNumber(LocStart)) {
1064 InsertText(LocStart, "#if 0\n");
1065 ReplaceText(LocEnd, 1, ";\n#endif\n");
1066 } else {
1067 InsertText(LocStart, "// ");
1068 }
1069}
1070
1071void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1072 SourceLocation Loc = prop->getAtLoc();
1073
1074 ReplaceText(Loc, 0, "// ");
1075 // FIXME: handle properties that are declared across multiple lines.
1076}
1077
1078void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1079 SourceLocation LocStart = CatDecl->getLocStart();
1080
1081 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001082 if (CatDecl->getIvarRBraceLoc().isValid()) {
1083 ReplaceText(LocStart, 1, "/** ");
1084 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1085 }
1086 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001087 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001088 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001089
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001090 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1091 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001092 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001093
1094 for (ObjCCategoryDecl::instmeth_iterator
1095 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1096 I != E; ++I)
1097 RewriteMethodDeclaration(*I);
1098 for (ObjCCategoryDecl::classmeth_iterator
1099 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1100 I != E; ++I)
1101 RewriteMethodDeclaration(*I);
1102
1103 // Lastly, comment out the @end.
1104 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1105 strlen("@end"), "/* @end */");
1106}
1107
1108void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1109 SourceLocation LocStart = PDecl->getLocStart();
1110 assert(PDecl->isThisDeclarationADefinition());
1111
1112 // FIXME: handle protocol headers that are declared across multiple lines.
1113 ReplaceText(LocStart, 0, "// ");
1114
1115 for (ObjCProtocolDecl::instmeth_iterator
1116 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1117 I != E; ++I)
1118 RewriteMethodDeclaration(*I);
1119 for (ObjCProtocolDecl::classmeth_iterator
1120 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1121 I != E; ++I)
1122 RewriteMethodDeclaration(*I);
1123
1124 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1125 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001126 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001127
1128 // Lastly, comment out the @end.
1129 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1130 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1131
1132 // Must comment out @optional/@required
1133 const char *startBuf = SM->getCharacterData(LocStart);
1134 const char *endBuf = SM->getCharacterData(LocEnd);
1135 for (const char *p = startBuf; p < endBuf; p++) {
1136 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1137 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1138 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1139
1140 }
1141 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1142 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1143 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1144
1145 }
1146 }
1147}
1148
1149void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1150 SourceLocation LocStart = (*D.begin())->getLocStart();
1151 if (LocStart.isInvalid())
1152 llvm_unreachable("Invalid SourceLocation");
1153 // FIXME: handle forward protocol that are declared across multiple lines.
1154 ReplaceText(LocStart, 0, "// ");
1155}
1156
1157void
1158RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1159 SourceLocation LocStart = DG[0]->getLocStart();
1160 if (LocStart.isInvalid())
1161 llvm_unreachable("Invalid SourceLocation");
1162 // FIXME: handle forward protocol that are declared across multiple lines.
1163 ReplaceText(LocStart, 0, "// ");
1164}
1165
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001166void
1167RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1168 SourceLocation LocStart = LSD->getExternLoc();
1169 if (LocStart.isInvalid())
1170 llvm_unreachable("Invalid extern SourceLocation");
1171
1172 ReplaceText(LocStart, 0, "// ");
1173 if (!LSD->hasBraces())
1174 return;
1175 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1176 SourceLocation LocRBrace = LSD->getRBraceLoc();
1177 if (LocRBrace.isInvalid())
1178 llvm_unreachable("Invalid rbrace SourceLocation");
1179 ReplaceText(LocRBrace, 0, "// ");
1180}
1181
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001182void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1183 const FunctionType *&FPRetType) {
1184 if (T->isObjCQualifiedIdType())
1185 ResultStr += "id";
1186 else if (T->isFunctionPointerType() ||
1187 T->isBlockPointerType()) {
1188 // needs special handling, since pointer-to-functions have special
1189 // syntax (where a decaration models use).
1190 QualType retType = T;
1191 QualType PointeeTy;
1192 if (const PointerType* PT = retType->getAs<PointerType>())
1193 PointeeTy = PT->getPointeeType();
1194 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1195 PointeeTy = BPT->getPointeeType();
1196 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1197 ResultStr += FPRetType->getResultType().getAsString(
1198 Context->getPrintingPolicy());
1199 ResultStr += "(*";
1200 }
1201 } else
1202 ResultStr += T.getAsString(Context->getPrintingPolicy());
1203}
1204
1205void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1206 ObjCMethodDecl *OMD,
1207 std::string &ResultStr) {
1208 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1209 const FunctionType *FPRetType = 0;
1210 ResultStr += "\nstatic ";
1211 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1212 ResultStr += " ";
1213
1214 // Unique method name
1215 std::string NameStr;
1216
1217 if (OMD->isInstanceMethod())
1218 NameStr += "_I_";
1219 else
1220 NameStr += "_C_";
1221
1222 NameStr += IDecl->getNameAsString();
1223 NameStr += "_";
1224
1225 if (ObjCCategoryImplDecl *CID =
1226 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1227 NameStr += CID->getNameAsString();
1228 NameStr += "_";
1229 }
1230 // Append selector names, replacing ':' with '_'
1231 {
1232 std::string selString = OMD->getSelector().getAsString();
1233 int len = selString.size();
1234 for (int i = 0; i < len; i++)
1235 if (selString[i] == ':')
1236 selString[i] = '_';
1237 NameStr += selString;
1238 }
1239 // Remember this name for metadata emission
1240 MethodInternalNames[OMD] = NameStr;
1241 ResultStr += NameStr;
1242
1243 // Rewrite arguments
1244 ResultStr += "(";
1245
1246 // invisible arguments
1247 if (OMD->isInstanceMethod()) {
1248 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1249 selfTy = Context->getPointerType(selfTy);
1250 if (!LangOpts.MicrosoftExt) {
1251 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1252 ResultStr += "struct ";
1253 }
1254 // When rewriting for Microsoft, explicitly omit the structure name.
1255 ResultStr += IDecl->getNameAsString();
1256 ResultStr += " *";
1257 }
1258 else
1259 ResultStr += Context->getObjCClassType().getAsString(
1260 Context->getPrintingPolicy());
1261
1262 ResultStr += " self, ";
1263 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1264 ResultStr += " _cmd";
1265
1266 // Method arguments.
1267 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1268 E = OMD->param_end(); PI != E; ++PI) {
1269 ParmVarDecl *PDecl = *PI;
1270 ResultStr += ", ";
1271 if (PDecl->getType()->isObjCQualifiedIdType()) {
1272 ResultStr += "id ";
1273 ResultStr += PDecl->getNameAsString();
1274 } else {
1275 std::string Name = PDecl->getNameAsString();
1276 QualType QT = PDecl->getType();
1277 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001278 (void)convertBlockPointerToFunctionPointer(QT);
1279 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001280 ResultStr += Name;
1281 }
1282 }
1283 if (OMD->isVariadic())
1284 ResultStr += ", ...";
1285 ResultStr += ") ";
1286
1287 if (FPRetType) {
1288 ResultStr += ")"; // close the precedence "scope" for "*".
1289
1290 // Now, emit the argument types (if any).
1291 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1292 ResultStr += "(";
1293 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1294 if (i) ResultStr += ", ";
1295 std::string ParamStr = FT->getArgType(i).getAsString(
1296 Context->getPrintingPolicy());
1297 ResultStr += ParamStr;
1298 }
1299 if (FT->isVariadic()) {
1300 if (FT->getNumArgs()) ResultStr += ", ";
1301 ResultStr += "...";
1302 }
1303 ResultStr += ")";
1304 } else {
1305 ResultStr += "()";
1306 }
1307 }
1308}
1309void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1310 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1311 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1312
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001313 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001314 if (IMD->getIvarRBraceLoc().isValid()) {
1315 ReplaceText(IMD->getLocStart(), 1, "/** ");
1316 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001317 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001318 else {
1319 InsertText(IMD->getLocStart(), "// ");
1320 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001321 }
1322 else
1323 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001324
1325 for (ObjCCategoryImplDecl::instmeth_iterator
1326 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1327 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1328 I != E; ++I) {
1329 std::string ResultStr;
1330 ObjCMethodDecl *OMD = *I;
1331 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1332 SourceLocation LocStart = OMD->getLocStart();
1333 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1334
1335 const char *startBuf = SM->getCharacterData(LocStart);
1336 const char *endBuf = SM->getCharacterData(LocEnd);
1337 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1338 }
1339
1340 for (ObjCCategoryImplDecl::classmeth_iterator
1341 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1342 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1343 I != E; ++I) {
1344 std::string ResultStr;
1345 ObjCMethodDecl *OMD = *I;
1346 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1347 SourceLocation LocStart = OMD->getLocStart();
1348 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1349
1350 const char *startBuf = SM->getCharacterData(LocStart);
1351 const char *endBuf = SM->getCharacterData(LocEnd);
1352 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1353 }
1354 for (ObjCCategoryImplDecl::propimpl_iterator
1355 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1356 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1357 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001358 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001359 }
1360
1361 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1362}
1363
1364void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001365 // Do not synthesize more than once.
1366 if (ObjCSynthesizedStructs.count(ClassDecl))
1367 return;
1368 // Make sure super class's are written before current class is written.
1369 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1370 while (SuperClass) {
1371 RewriteInterfaceDecl(SuperClass);
1372 SuperClass = SuperClass->getSuperClass();
1373 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001374 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001375 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001376 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001377 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001378 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1379
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001380 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001381 // Mark this typedef as having been written into its c++ equivalent.
1382 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001383
1384 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001385 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001386 RewriteProperty(*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001387 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001388 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001389 I != E; ++I)
1390 RewriteMethodDeclaration(*I);
1391 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001392 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001393 I != E; ++I)
1394 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001395
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001396 // Lastly, comment out the @end.
1397 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1398 "/* @end */");
1399 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001400}
1401
1402Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1403 SourceRange OldRange = PseudoOp->getSourceRange();
1404
1405 // We just magically know some things about the structure of this
1406 // expression.
1407 ObjCMessageExpr *OldMsg =
1408 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1409 PseudoOp->getNumSemanticExprs() - 1));
1410
1411 // Because the rewriter doesn't allow us to rewrite rewritten code,
1412 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001413 Expr *Base;
1414 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001415 {
1416 DisableReplaceStmtScope S(*this);
1417
1418 // Rebuild the base expression if we have one.
1419 Base = 0;
1420 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1421 Base = OldMsg->getInstanceReceiver();
1422 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1423 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1424 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001425
1426 unsigned numArgs = OldMsg->getNumArgs();
1427 for (unsigned i = 0; i < numArgs; i++) {
1428 Expr *Arg = OldMsg->getArg(i);
1429 if (isa<OpaqueValueExpr>(Arg))
1430 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1431 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1432 Args.push_back(Arg);
1433 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001434 }
1435
1436 // TODO: avoid this copy.
1437 SmallVector<SourceLocation, 1> SelLocs;
1438 OldMsg->getSelectorLocs(SelLocs);
1439
1440 ObjCMessageExpr *NewMsg = 0;
1441 switch (OldMsg->getReceiverKind()) {
1442 case ObjCMessageExpr::Class:
1443 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1444 OldMsg->getValueKind(),
1445 OldMsg->getLeftLoc(),
1446 OldMsg->getClassReceiverTypeInfo(),
1447 OldMsg->getSelector(),
1448 SelLocs,
1449 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001450 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001451 OldMsg->getRightLoc(),
1452 OldMsg->isImplicit());
1453 break;
1454
1455 case ObjCMessageExpr::Instance:
1456 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1457 OldMsg->getValueKind(),
1458 OldMsg->getLeftLoc(),
1459 Base,
1460 OldMsg->getSelector(),
1461 SelLocs,
1462 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001463 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001464 OldMsg->getRightLoc(),
1465 OldMsg->isImplicit());
1466 break;
1467
1468 case ObjCMessageExpr::SuperClass:
1469 case ObjCMessageExpr::SuperInstance:
1470 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1471 OldMsg->getValueKind(),
1472 OldMsg->getLeftLoc(),
1473 OldMsg->getSuperLoc(),
1474 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1475 OldMsg->getSuperType(),
1476 OldMsg->getSelector(),
1477 SelLocs,
1478 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001479 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001480 OldMsg->getRightLoc(),
1481 OldMsg->isImplicit());
1482 break;
1483 }
1484
1485 Stmt *Replacement = SynthMessageExpr(NewMsg);
1486 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1487 return Replacement;
1488}
1489
1490Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1491 SourceRange OldRange = PseudoOp->getSourceRange();
1492
1493 // We just magically know some things about the structure of this
1494 // expression.
1495 ObjCMessageExpr *OldMsg =
1496 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1497
1498 // Because the rewriter doesn't allow us to rewrite rewritten code,
1499 // we need to suppress rewriting the sub-statements.
1500 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001501 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001502 {
1503 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001504 // Rebuild the base expression if we have one.
1505 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1506 Base = OldMsg->getInstanceReceiver();
1507 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1508 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1509 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001510 unsigned numArgs = OldMsg->getNumArgs();
1511 for (unsigned i = 0; i < numArgs; i++) {
1512 Expr *Arg = OldMsg->getArg(i);
1513 if (isa<OpaqueValueExpr>(Arg))
1514 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1515 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1516 Args.push_back(Arg);
1517 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001518 }
1519
1520 // Intentionally empty.
1521 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001522
1523 ObjCMessageExpr *NewMsg = 0;
1524 switch (OldMsg->getReceiverKind()) {
1525 case ObjCMessageExpr::Class:
1526 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1527 OldMsg->getValueKind(),
1528 OldMsg->getLeftLoc(),
1529 OldMsg->getClassReceiverTypeInfo(),
1530 OldMsg->getSelector(),
1531 SelLocs,
1532 OldMsg->getMethodDecl(),
1533 Args,
1534 OldMsg->getRightLoc(),
1535 OldMsg->isImplicit());
1536 break;
1537
1538 case ObjCMessageExpr::Instance:
1539 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1540 OldMsg->getValueKind(),
1541 OldMsg->getLeftLoc(),
1542 Base,
1543 OldMsg->getSelector(),
1544 SelLocs,
1545 OldMsg->getMethodDecl(),
1546 Args,
1547 OldMsg->getRightLoc(),
1548 OldMsg->isImplicit());
1549 break;
1550
1551 case ObjCMessageExpr::SuperClass:
1552 case ObjCMessageExpr::SuperInstance:
1553 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1554 OldMsg->getValueKind(),
1555 OldMsg->getLeftLoc(),
1556 OldMsg->getSuperLoc(),
1557 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1558 OldMsg->getSuperType(),
1559 OldMsg->getSelector(),
1560 SelLocs,
1561 OldMsg->getMethodDecl(),
1562 Args,
1563 OldMsg->getRightLoc(),
1564 OldMsg->isImplicit());
1565 break;
1566 }
1567
1568 Stmt *Replacement = SynthMessageExpr(NewMsg);
1569 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1570 return Replacement;
1571}
1572
1573/// SynthCountByEnumWithState - To print:
1574/// ((unsigned int (*)
1575/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1576/// (void *)objc_msgSend)((id)l_collection,
1577/// sel_registerName(
1578/// "countByEnumeratingWithState:objects:count:"),
1579/// &enumState,
1580/// (id *)__rw_items, (unsigned int)16)
1581///
1582void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1583 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1584 "id *, unsigned int))(void *)objc_msgSend)";
1585 buf += "\n\t\t";
1586 buf += "((id)l_collection,\n\t\t";
1587 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1588 buf += "\n\t\t";
1589 buf += "&enumState, "
1590 "(id *)__rw_items, (unsigned int)16)";
1591}
1592
1593/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1594/// statement to exit to its outer synthesized loop.
1595///
1596Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1597 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1598 return S;
1599 // replace break with goto __break_label
1600 std::string buf;
1601
1602 SourceLocation startLoc = S->getLocStart();
1603 buf = "goto __break_label_";
1604 buf += utostr(ObjCBcLabelNo.back());
1605 ReplaceText(startLoc, strlen("break"), buf);
1606
1607 return 0;
1608}
1609
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001610void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1611 SourceLocation Loc,
1612 std::string &LineString) {
1613 if (Loc.isFileID()) {
1614 LineString += "\n#line ";
1615 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1616 LineString += utostr(PLoc.getLine());
1617 LineString += " \"";
1618 LineString += Lexer::Stringify(PLoc.getFilename());
1619 LineString += "\"\n";
1620 }
1621}
1622
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001623/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1624/// statement to continue with its inner synthesized loop.
1625///
1626Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1627 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1628 return S;
1629 // replace continue with goto __continue_label
1630 std::string buf;
1631
1632 SourceLocation startLoc = S->getLocStart();
1633 buf = "goto __continue_label_";
1634 buf += utostr(ObjCBcLabelNo.back());
1635 ReplaceText(startLoc, strlen("continue"), buf);
1636
1637 return 0;
1638}
1639
1640/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1641/// It rewrites:
1642/// for ( type elem in collection) { stmts; }
1643
1644/// Into:
1645/// {
1646/// type elem;
1647/// struct __objcFastEnumerationState enumState = { 0 };
1648/// id __rw_items[16];
1649/// id l_collection = (id)collection;
1650/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1651/// objects:__rw_items count:16];
1652/// if (limit) {
1653/// unsigned long startMutations = *enumState.mutationsPtr;
1654/// do {
1655/// unsigned long counter = 0;
1656/// do {
1657/// if (startMutations != *enumState.mutationsPtr)
1658/// objc_enumerationMutation(l_collection);
1659/// elem = (type)enumState.itemsPtr[counter++];
1660/// stmts;
1661/// __continue_label: ;
1662/// } while (counter < limit);
1663/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1664/// objects:__rw_items count:16]);
1665/// elem = nil;
1666/// __break_label: ;
1667/// }
1668/// else
1669/// elem = nil;
1670/// }
1671///
1672Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1673 SourceLocation OrigEnd) {
1674 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1675 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1676 "ObjCForCollectionStmt Statement stack mismatch");
1677 assert(!ObjCBcLabelNo.empty() &&
1678 "ObjCForCollectionStmt - Label No stack empty");
1679
1680 SourceLocation startLoc = S->getLocStart();
1681 const char *startBuf = SM->getCharacterData(startLoc);
1682 StringRef elementName;
1683 std::string elementTypeAsString;
1684 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001685 // line directive first.
1686 SourceLocation ForEachLoc = S->getForLoc();
1687 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1688 buf += "{\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001689 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1690 // type elem;
1691 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1692 QualType ElementType = cast<ValueDecl>(D)->getType();
1693 if (ElementType->isObjCQualifiedIdType() ||
1694 ElementType->isObjCQualifiedInterfaceType())
1695 // Simply use 'id' for all qualified types.
1696 elementTypeAsString = "id";
1697 else
1698 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1699 buf += elementTypeAsString;
1700 buf += " ";
1701 elementName = D->getName();
1702 buf += elementName;
1703 buf += ";\n\t";
1704 }
1705 else {
1706 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1707 elementName = DR->getDecl()->getName();
1708 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1709 if (VD->getType()->isObjCQualifiedIdType() ||
1710 VD->getType()->isObjCQualifiedInterfaceType())
1711 // Simply use 'id' for all qualified types.
1712 elementTypeAsString = "id";
1713 else
1714 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1715 }
1716
1717 // struct __objcFastEnumerationState enumState = { 0 };
1718 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1719 // id __rw_items[16];
1720 buf += "id __rw_items[16];\n\t";
1721 // id l_collection = (id)
1722 buf += "id l_collection = (id)";
1723 // Find start location of 'collection' the hard way!
1724 const char *startCollectionBuf = startBuf;
1725 startCollectionBuf += 3; // skip 'for'
1726 startCollectionBuf = strchr(startCollectionBuf, '(');
1727 startCollectionBuf++; // skip '('
1728 // find 'in' and skip it.
1729 while (*startCollectionBuf != ' ' ||
1730 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1731 (*(startCollectionBuf+3) != ' ' &&
1732 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1733 startCollectionBuf++;
1734 startCollectionBuf += 3;
1735
1736 // Replace: "for (type element in" with string constructed thus far.
1737 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1738 // Replace ')' in for '(' type elem in collection ')' with ';'
1739 SourceLocation rightParenLoc = S->getRParenLoc();
1740 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1741 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1742 buf = ";\n\t";
1743
1744 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1745 // objects:__rw_items count:16];
1746 // which is synthesized into:
1747 // unsigned int limit =
1748 // ((unsigned int (*)
1749 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1750 // (void *)objc_msgSend)((id)l_collection,
1751 // sel_registerName(
1752 // "countByEnumeratingWithState:objects:count:"),
1753 // (struct __objcFastEnumerationState *)&state,
1754 // (id *)__rw_items, (unsigned int)16);
1755 buf += "unsigned long limit =\n\t\t";
1756 SynthCountByEnumWithState(buf);
1757 buf += ";\n\t";
1758 /// if (limit) {
1759 /// unsigned long startMutations = *enumState.mutationsPtr;
1760 /// do {
1761 /// unsigned long counter = 0;
1762 /// do {
1763 /// if (startMutations != *enumState.mutationsPtr)
1764 /// objc_enumerationMutation(l_collection);
1765 /// elem = (type)enumState.itemsPtr[counter++];
1766 buf += "if (limit) {\n\t";
1767 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1768 buf += "do {\n\t\t";
1769 buf += "unsigned long counter = 0;\n\t\t";
1770 buf += "do {\n\t\t\t";
1771 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1772 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1773 buf += elementName;
1774 buf += " = (";
1775 buf += elementTypeAsString;
1776 buf += ")enumState.itemsPtr[counter++];";
1777 // Replace ')' in for '(' type elem in collection ')' with all of these.
1778 ReplaceText(lparenLoc, 1, buf);
1779
1780 /// __continue_label: ;
1781 /// } while (counter < limit);
1782 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1783 /// objects:__rw_items count:16]);
1784 /// elem = nil;
1785 /// __break_label: ;
1786 /// }
1787 /// else
1788 /// elem = nil;
1789 /// }
1790 ///
1791 buf = ";\n\t";
1792 buf += "__continue_label_";
1793 buf += utostr(ObjCBcLabelNo.back());
1794 buf += ": ;";
1795 buf += "\n\t\t";
1796 buf += "} while (counter < limit);\n\t";
1797 buf += "} while (limit = ";
1798 SynthCountByEnumWithState(buf);
1799 buf += ");\n\t";
1800 buf += elementName;
1801 buf += " = ((";
1802 buf += elementTypeAsString;
1803 buf += ")0);\n\t";
1804 buf += "__break_label_";
1805 buf += utostr(ObjCBcLabelNo.back());
1806 buf += ": ;\n\t";
1807 buf += "}\n\t";
1808 buf += "else\n\t\t";
1809 buf += elementName;
1810 buf += " = ((";
1811 buf += elementTypeAsString;
1812 buf += ")0);\n\t";
1813 buf += "}\n";
1814
1815 // Insert all these *after* the statement body.
1816 // FIXME: If this should support Obj-C++, support CXXTryStmt
1817 if (isa<CompoundStmt>(S->getBody())) {
1818 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1819 InsertText(endBodyLoc, buf);
1820 } else {
1821 /* Need to treat single statements specially. For example:
1822 *
1823 * for (A *a in b) if (stuff()) break;
1824 * for (A *a in b) xxxyy;
1825 *
1826 * The following code simply scans ahead to the semi to find the actual end.
1827 */
1828 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1829 const char *semiBuf = strchr(stmtBuf, ';');
1830 assert(semiBuf && "Can't find ';'");
1831 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1832 InsertText(endBodyLoc, buf);
1833 }
1834 Stmts.pop_back();
1835 ObjCBcLabelNo.pop_back();
1836 return 0;
1837}
1838
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001839static void Write_RethrowObject(std::string &buf) {
1840 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1841 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1842 buf += "\tid rethrow;\n";
1843 buf += "\t} _fin_force_rethow(_rethrow);";
1844}
1845
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001846/// RewriteObjCSynchronizedStmt -
1847/// This routine rewrites @synchronized(expr) stmt;
1848/// into:
1849/// objc_sync_enter(expr);
1850/// @try stmt @finally { objc_sync_exit(expr); }
1851///
1852Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1853 // Get the start location and compute the semi location.
1854 SourceLocation startLoc = S->getLocStart();
1855 const char *startBuf = SM->getCharacterData(startLoc);
1856
1857 assert((*startBuf == '@') && "bogus @synchronized location");
1858
1859 std::string buf;
Fariborz Jahanian43f4f1e2012-11-07 00:43:05 +00001860 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1861 ConvertSourceLocationToLineDirective(SynchLoc, buf);
1862 buf += "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001863
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001864 const char *lparenBuf = startBuf;
1865 while (*lparenBuf != '(') lparenBuf++;
1866 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001867
1868 buf = "; objc_sync_enter(_sync_obj);\n";
1869 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1870 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1871 buf += "\n\tid sync_exit;";
1872 buf += "\n\t} _sync_exit(_sync_obj);\n";
1873
1874 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1875 // the sync expression is typically a message expression that's already
1876 // been rewritten! (which implies the SourceLocation's are invalid).
1877 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1878 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1879 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1880 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1881
1882 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1883 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1884 assert (*LBraceLocBuf == '{');
1885 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001886
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001887 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001888 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1889 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001890
1891 buf = "} catch (id e) {_rethrow = e;}\n";
1892 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001893 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001894 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001895
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001896 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001897
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001898 return 0;
1899}
1900
1901void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1902{
1903 // Perform a bottom up traversal of all children.
1904 for (Stmt::child_range CI = S->children(); CI; ++CI)
1905 if (*CI)
1906 WarnAboutReturnGotoStmts(*CI);
1907
1908 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1909 Diags.Report(Context->getFullLoc(S->getLocStart()),
1910 TryFinallyContainsReturnDiag);
1911 }
1912 return;
1913}
1914
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001915Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1916 SourceLocation startLoc = S->getAtLoc();
1917 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001918 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1919 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001920
1921 return 0;
1922}
1923
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001924Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001925 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001926 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001927 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001928 SourceLocation TryLocation = S->getAtTryLoc();
1929 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001930
1931 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001932 if (noCatch)
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001933 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001934 else {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001935 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001936 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001937 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001938 // Get the start location and compute the semi location.
1939 SourceLocation startLoc = S->getLocStart();
1940 const char *startBuf = SM->getCharacterData(startLoc);
1941
1942 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001943 if (finalStmt)
1944 ReplaceText(startLoc, 1, buf);
1945 else
1946 // @try -> try
1947 ReplaceText(startLoc, 1, "");
1948
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001949 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1950 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001951 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001952
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001953 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001954 bool AtRemoved = false;
1955 if (catchDecl) {
1956 QualType t = catchDecl->getType();
1957 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1958 // Should be a pointer to a class.
1959 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1960 if (IDecl) {
1961 std::string Result;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001962 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
1963
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001964 startBuf = SM->getCharacterData(startLoc);
1965 assert((*startBuf == '@') && "bogus @catch location");
1966 SourceLocation rParenLoc = Catch->getRParenLoc();
1967 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1968
1969 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001970 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001971 Result += " *_"; Result += catchDecl->getNameAsString();
1972 Result += ")";
1973 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1974 // Foo *e = (Foo *)_e;
1975 Result.clear();
1976 Result = "{ ";
1977 Result += IDecl->getNameAsString();
1978 Result += " *"; Result += catchDecl->getNameAsString();
1979 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1980 Result += "_"; Result += catchDecl->getNameAsString();
1981
1982 Result += "; ";
1983 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1984 ReplaceText(lBraceLoc, 1, Result);
1985 AtRemoved = true;
1986 }
1987 }
1988 }
1989 if (!AtRemoved)
1990 // @catch -> catch
1991 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001992
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001993 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001994 if (finalStmt) {
1995 buf.clear();
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001996 SourceLocation FinallyLoc = finalStmt->getLocStart();
1997
1998 if (noCatch) {
1999 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2000 buf += "catch (id e) {_rethrow = e;}\n";
2001 }
2002 else {
2003 buf += "}\n";
2004 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2005 buf += "catch (id e) {_rethrow = e;}\n";
2006 }
2007
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002008 SourceLocation startFinalLoc = finalStmt->getLocStart();
2009 ReplaceText(startFinalLoc, 8, buf);
2010 Stmt *body = finalStmt->getFinallyBody();
2011 SourceLocation startFinalBodyLoc = body->getLocStart();
2012 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00002013 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002014 ReplaceText(startFinalBodyLoc, 1, buf);
2015
2016 SourceLocation endFinalBodyLoc = body->getLocEnd();
2017 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00002018 // Now check for any return/continue/go statements within the @try.
2019 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002020 }
2021
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002022 return 0;
2023}
2024
2025// This can't be done with ReplaceStmt(S, ThrowExpr), since
2026// the throw expression is typically a message expression that's already
2027// been rewritten! (which implies the SourceLocation's are invalid).
2028Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2029 // Get the start location and compute the semi location.
2030 SourceLocation startLoc = S->getLocStart();
2031 const char *startBuf = SM->getCharacterData(startLoc);
2032
2033 assert((*startBuf == '@') && "bogus @throw location");
2034
2035 std::string buf;
2036 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2037 if (S->getThrowExpr())
2038 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00002039 else
2040 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002041
2042 // handle "@ throw" correctly.
2043 const char *wBuf = strchr(startBuf, 'w');
2044 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2045 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2046
2047 const char *semiBuf = strchr(startBuf, ';');
2048 assert((*semiBuf == ';') && "@throw: can't find ';'");
2049 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002050 if (S->getThrowExpr())
2051 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002052 return 0;
2053}
2054
2055Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2056 // Create a new string expression.
2057 QualType StrType = Context->getPointerType(Context->CharTy);
2058 std::string StrEncoding;
2059 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2060 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2061 StringLiteral::Ascii, false,
2062 StrType, SourceLocation());
2063 ReplaceStmt(Exp, Replacement);
2064
2065 // Replace this subexpr in the parent.
2066 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2067 return Replacement;
2068}
2069
2070Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2071 if (!SelGetUidFunctionDecl)
2072 SynthSelGetUidFunctionDecl();
2073 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2074 // Create a call to sel_registerName("selName").
2075 SmallVector<Expr*, 8> SelExprs;
2076 QualType argType = Context->getPointerType(Context->CharTy);
2077 SelExprs.push_back(StringLiteral::Create(*Context,
2078 Exp->getSelector().getAsString(),
2079 StringLiteral::Ascii, false,
2080 argType, SourceLocation()));
2081 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2082 &SelExprs[0], SelExprs.size());
2083 ReplaceStmt(Exp, SelExp);
2084 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2085 return SelExp;
2086}
2087
2088CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2089 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2090 SourceLocation EndLoc) {
2091 // Get the type, we will need to reference it in a couple spots.
2092 QualType msgSendType = FD->getType();
2093
2094 // Create a reference to the objc_msgSend() declaration.
2095 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002096 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002097
2098 // Now, we cast the reference to a pointer to the objc_msgSend type.
2099 QualType pToFunc = Context->getPointerType(msgSendType);
2100 ImplicitCastExpr *ICE =
2101 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2102 DRE, 0, VK_RValue);
2103
2104 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2105
2106 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002107 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002108 FT->getCallResultType(*Context),
2109 VK_RValue, EndLoc);
2110 return Exp;
2111}
2112
2113static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2114 const char *&startRef, const char *&endRef) {
2115 while (startBuf < endBuf) {
2116 if (*startBuf == '<')
2117 startRef = startBuf; // mark the start.
2118 if (*startBuf == '>') {
2119 if (startRef && *startRef == '<') {
2120 endRef = startBuf; // mark the end.
2121 return true;
2122 }
2123 return false;
2124 }
2125 startBuf++;
2126 }
2127 return false;
2128}
2129
2130static void scanToNextArgument(const char *&argRef) {
2131 int angle = 0;
2132 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2133 if (*argRef == '<')
2134 angle++;
2135 else if (*argRef == '>')
2136 angle--;
2137 argRef++;
2138 }
2139 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2140}
2141
2142bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2143 if (T->isObjCQualifiedIdType())
2144 return true;
2145 if (const PointerType *PT = T->getAs<PointerType>()) {
2146 if (PT->getPointeeType()->isObjCQualifiedIdType())
2147 return true;
2148 }
2149 if (T->isObjCObjectPointerType()) {
2150 T = T->getPointeeType();
2151 return T->isObjCQualifiedInterfaceType();
2152 }
2153 if (T->isArrayType()) {
2154 QualType ElemTy = Context->getBaseElementType(T);
2155 return needToScanForQualifiers(ElemTy);
2156 }
2157 return false;
2158}
2159
2160void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2161 QualType Type = E->getType();
2162 if (needToScanForQualifiers(Type)) {
2163 SourceLocation Loc, EndLoc;
2164
2165 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2166 Loc = ECE->getLParenLoc();
2167 EndLoc = ECE->getRParenLoc();
2168 } else {
2169 Loc = E->getLocStart();
2170 EndLoc = E->getLocEnd();
2171 }
2172 // This will defend against trying to rewrite synthesized expressions.
2173 if (Loc.isInvalid() || EndLoc.isInvalid())
2174 return;
2175
2176 const char *startBuf = SM->getCharacterData(Loc);
2177 const char *endBuf = SM->getCharacterData(EndLoc);
2178 const char *startRef = 0, *endRef = 0;
2179 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2180 // Get the locations of the startRef, endRef.
2181 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2182 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2183 // Comment out the protocol references.
2184 InsertText(LessLoc, "/*");
2185 InsertText(GreaterLoc, "*/");
2186 }
2187 }
2188}
2189
2190void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2191 SourceLocation Loc;
2192 QualType Type;
2193 const FunctionProtoType *proto = 0;
2194 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2195 Loc = VD->getLocation();
2196 Type = VD->getType();
2197 }
2198 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2199 Loc = FD->getLocation();
2200 // Check for ObjC 'id' and class types that have been adorned with protocol
2201 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2202 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2203 assert(funcType && "missing function type");
2204 proto = dyn_cast<FunctionProtoType>(funcType);
2205 if (!proto)
2206 return;
2207 Type = proto->getResultType();
2208 }
2209 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2210 Loc = FD->getLocation();
2211 Type = FD->getType();
2212 }
2213 else
2214 return;
2215
2216 if (needToScanForQualifiers(Type)) {
2217 // Since types are unique, we need to scan the buffer.
2218
2219 const char *endBuf = SM->getCharacterData(Loc);
2220 const char *startBuf = endBuf;
2221 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2222 startBuf--; // scan backward (from the decl location) for return type.
2223 const char *startRef = 0, *endRef = 0;
2224 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2225 // Get the locations of the startRef, endRef.
2226 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2227 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2228 // Comment out the protocol references.
2229 InsertText(LessLoc, "/*");
2230 InsertText(GreaterLoc, "*/");
2231 }
2232 }
2233 if (!proto)
2234 return; // most likely, was a variable
2235 // Now check arguments.
2236 const char *startBuf = SM->getCharacterData(Loc);
2237 const char *startFuncBuf = startBuf;
2238 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2239 if (needToScanForQualifiers(proto->getArgType(i))) {
2240 // Since types are unique, we need to scan the buffer.
2241
2242 const char *endBuf = startBuf;
2243 // scan forward (from the decl location) for argument types.
2244 scanToNextArgument(endBuf);
2245 const char *startRef = 0, *endRef = 0;
2246 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2247 // Get the locations of the startRef, endRef.
2248 SourceLocation LessLoc =
2249 Loc.getLocWithOffset(startRef-startFuncBuf);
2250 SourceLocation GreaterLoc =
2251 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2252 // Comment out the protocol references.
2253 InsertText(LessLoc, "/*");
2254 InsertText(GreaterLoc, "*/");
2255 }
2256 startBuf = ++endBuf;
2257 }
2258 else {
2259 // If the function name is derived from a macro expansion, then the
2260 // argument buffer will not follow the name. Need to speak with Chris.
2261 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2262 startBuf++; // scan forward (from the decl location) for argument types.
2263 startBuf++;
2264 }
2265 }
2266}
2267
2268void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2269 QualType QT = ND->getType();
2270 const Type* TypePtr = QT->getAs<Type>();
2271 if (!isa<TypeOfExprType>(TypePtr))
2272 return;
2273 while (isa<TypeOfExprType>(TypePtr)) {
2274 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2275 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2276 TypePtr = QT->getAs<Type>();
2277 }
2278 // FIXME. This will not work for multiple declarators; as in:
2279 // __typeof__(a) b,c,d;
2280 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2281 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2282 const char *startBuf = SM->getCharacterData(DeclLoc);
2283 if (ND->getInit()) {
2284 std::string Name(ND->getNameAsString());
2285 TypeAsString += " " + Name + " = ";
2286 Expr *E = ND->getInit();
2287 SourceLocation startLoc;
2288 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2289 startLoc = ECE->getLParenLoc();
2290 else
2291 startLoc = E->getLocStart();
2292 startLoc = SM->getExpansionLoc(startLoc);
2293 const char *endBuf = SM->getCharacterData(startLoc);
2294 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2295 }
2296 else {
2297 SourceLocation X = ND->getLocEnd();
2298 X = SM->getExpansionLoc(X);
2299 const char *endBuf = SM->getCharacterData(X);
2300 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2301 }
2302}
2303
2304// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2305void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2306 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2307 SmallVector<QualType, 16> ArgTys;
2308 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2309 QualType getFuncType =
2310 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2311 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2312 SourceLocation(),
2313 SourceLocation(),
2314 SelGetUidIdent, getFuncType, 0,
2315 SC_Extern,
2316 SC_None, false);
2317}
2318
2319void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2320 // declared in <objc/objc.h>
2321 if (FD->getIdentifier() &&
2322 FD->getName() == "sel_registerName") {
2323 SelGetUidFunctionDecl = FD;
2324 return;
2325 }
2326 RewriteObjCQualifiedInterfaceTypes(FD);
2327}
2328
2329void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2330 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2331 const char *argPtr = TypeString.c_str();
2332 if (!strchr(argPtr, '^')) {
2333 Str += TypeString;
2334 return;
2335 }
2336 while (*argPtr) {
2337 Str += (*argPtr == '^' ? '*' : *argPtr);
2338 argPtr++;
2339 }
2340}
2341
2342// FIXME. Consolidate this routine with RewriteBlockPointerType.
2343void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2344 ValueDecl *VD) {
2345 QualType Type = VD->getType();
2346 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2347 const char *argPtr = TypeString.c_str();
2348 int paren = 0;
2349 while (*argPtr) {
2350 switch (*argPtr) {
2351 case '(':
2352 Str += *argPtr;
2353 paren++;
2354 break;
2355 case ')':
2356 Str += *argPtr;
2357 paren--;
2358 break;
2359 case '^':
2360 Str += '*';
2361 if (paren == 1)
2362 Str += VD->getNameAsString();
2363 break;
2364 default:
2365 Str += *argPtr;
2366 break;
2367 }
2368 argPtr++;
2369 }
2370}
2371
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002372void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2373 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2374 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2375 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2376 if (!proto)
2377 return;
2378 QualType Type = proto->getResultType();
2379 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2380 FdStr += " ";
2381 FdStr += FD->getName();
2382 FdStr += "(";
2383 unsigned numArgs = proto->getNumArgs();
2384 for (unsigned i = 0; i < numArgs; i++) {
2385 QualType ArgType = proto->getArgType(i);
2386 RewriteBlockPointerType(FdStr, ArgType);
2387 if (i+1 < numArgs)
2388 FdStr += ", ";
2389 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002390 if (FD->isVariadic()) {
2391 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2392 }
2393 else
2394 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002395 InsertText(FunLocStart, FdStr);
2396}
2397
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002398// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002399void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2400 if (SuperContructorFunctionDecl)
2401 return;
2402 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2403 SmallVector<QualType, 16> ArgTys;
2404 QualType argT = Context->getObjCIdType();
2405 assert(!argT.isNull() && "Can't find 'id' type");
2406 ArgTys.push_back(argT);
2407 ArgTys.push_back(argT);
2408 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2409 &ArgTys[0], ArgTys.size());
2410 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2411 SourceLocation(),
2412 SourceLocation(),
2413 msgSendIdent, msgSendType, 0,
2414 SC_Extern,
2415 SC_None, false);
2416}
2417
2418// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2419void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2420 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2421 SmallVector<QualType, 16> ArgTys;
2422 QualType argT = Context->getObjCIdType();
2423 assert(!argT.isNull() && "Can't find 'id' type");
2424 ArgTys.push_back(argT);
2425 argT = Context->getObjCSelType();
2426 assert(!argT.isNull() && "Can't find 'SEL' type");
2427 ArgTys.push_back(argT);
2428 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2429 &ArgTys[0], ArgTys.size(),
2430 true /*isVariadic*/);
2431 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2432 SourceLocation(),
2433 SourceLocation(),
2434 msgSendIdent, msgSendType, 0,
2435 SC_Extern,
2436 SC_None, false);
2437}
2438
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002439// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002440void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2441 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002442 SmallVector<QualType, 2> ArgTys;
2443 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002444 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002445 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002446 true /*isVariadic*/);
2447 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2448 SourceLocation(),
2449 SourceLocation(),
2450 msgSendIdent, msgSendType, 0,
2451 SC_Extern,
2452 SC_None, false);
2453}
2454
2455// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2456void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2457 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2458 SmallVector<QualType, 16> ArgTys;
2459 QualType argT = Context->getObjCIdType();
2460 assert(!argT.isNull() && "Can't find 'id' type");
2461 ArgTys.push_back(argT);
2462 argT = Context->getObjCSelType();
2463 assert(!argT.isNull() && "Can't find 'SEL' type");
2464 ArgTys.push_back(argT);
2465 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2466 &ArgTys[0], ArgTys.size(),
2467 true /*isVariadic*/);
2468 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2469 SourceLocation(),
2470 SourceLocation(),
2471 msgSendIdent, msgSendType, 0,
2472 SC_Extern,
2473 SC_None, false);
2474}
2475
2476// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002477// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002478void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2479 IdentifierInfo *msgSendIdent =
2480 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002481 SmallVector<QualType, 2> ArgTys;
2482 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002483 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002484 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002485 true /*isVariadic*/);
2486 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2487 SourceLocation(),
2488 SourceLocation(),
2489 msgSendIdent, msgSendType, 0,
2490 SC_Extern,
2491 SC_None, false);
2492}
2493
2494// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2495void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2496 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2497 SmallVector<QualType, 16> ArgTys;
2498 QualType argT = Context->getObjCIdType();
2499 assert(!argT.isNull() && "Can't find 'id' type");
2500 ArgTys.push_back(argT);
2501 argT = Context->getObjCSelType();
2502 assert(!argT.isNull() && "Can't find 'SEL' type");
2503 ArgTys.push_back(argT);
2504 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2505 &ArgTys[0], ArgTys.size(),
2506 true /*isVariadic*/);
2507 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2508 SourceLocation(),
2509 SourceLocation(),
2510 msgSendIdent, msgSendType, 0,
2511 SC_Extern,
2512 SC_None, false);
2513}
2514
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002515// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002516void RewriteModernObjC::SynthGetClassFunctionDecl() {
2517 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2518 SmallVector<QualType, 16> ArgTys;
2519 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002520 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002521 &ArgTys[0], ArgTys.size());
2522 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2523 SourceLocation(),
2524 SourceLocation(),
2525 getClassIdent, getClassType, 0,
2526 SC_Extern,
2527 SC_None, false);
2528}
2529
2530// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2531void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2532 IdentifierInfo *getSuperClassIdent =
2533 &Context->Idents.get("class_getSuperclass");
2534 SmallVector<QualType, 16> ArgTys;
2535 ArgTys.push_back(Context->getObjCClassType());
2536 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2537 &ArgTys[0], ArgTys.size());
2538 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2539 SourceLocation(),
2540 SourceLocation(),
2541 getSuperClassIdent,
2542 getClassType, 0,
2543 SC_Extern,
2544 SC_None,
2545 false);
2546}
2547
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002548// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002549void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2550 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2551 SmallVector<QualType, 16> ArgTys;
2552 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002553 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002554 &ArgTys[0], ArgTys.size());
2555 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2556 SourceLocation(),
2557 SourceLocation(),
2558 getClassIdent, getClassType, 0,
2559 SC_Extern,
2560 SC_None, false);
2561}
2562
2563Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2564 QualType strType = getConstantStringStructType();
2565
2566 std::string S = "__NSConstantStringImpl_";
2567
2568 std::string tmpName = InFileName;
2569 unsigned i;
2570 for (i=0; i < tmpName.length(); i++) {
2571 char c = tmpName.at(i);
2572 // replace any non alphanumeric characters with '_'.
2573 if (!isalpha(c) && (c < '0' || c > '9'))
2574 tmpName[i] = '_';
2575 }
2576 S += tmpName;
2577 S += "_";
2578 S += utostr(NumObjCStringLiterals++);
2579
2580 Preamble += "static __NSConstantStringImpl " + S;
2581 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2582 Preamble += "0x000007c8,"; // utf8_str
2583 // The pretty printer for StringLiteral handles escape characters properly.
2584 std::string prettyBufS;
2585 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002586 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002587 Preamble += prettyBuf.str();
2588 Preamble += ",";
2589 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2590
2591 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2592 SourceLocation(), &Context->Idents.get(S),
2593 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002594 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002595 SourceLocation());
2596 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2597 Context->getPointerType(DRE->getType()),
2598 VK_RValue, OK_Ordinary,
2599 SourceLocation());
2600 // cast to NSConstantString *
2601 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2602 CK_CPointerToObjCPointerCast, Unop);
2603 ReplaceStmt(Exp, cast);
2604 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2605 return cast;
2606}
2607
Fariborz Jahanian55947042012-03-27 20:17:30 +00002608Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2609 unsigned IntSize =
2610 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2611
2612 Expr *FlagExp = IntegerLiteral::Create(*Context,
2613 llvm::APInt(IntSize, Exp->getValue()),
2614 Context->IntTy, Exp->getLocation());
2615 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2616 CK_BitCast, FlagExp);
2617 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2618 cast);
2619 ReplaceStmt(Exp, PE);
2620 return PE;
2621}
2622
Patrick Beardeb382ec2012-04-19 00:25:12 +00002623Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002624 // synthesize declaration of helper functions needed in this routine.
2625 if (!SelGetUidFunctionDecl)
2626 SynthSelGetUidFunctionDecl();
2627 // use objc_msgSend() for all.
2628 if (!MsgSendFunctionDecl)
2629 SynthMsgSendFunctionDecl();
2630 if (!GetClassFunctionDecl)
2631 SynthGetClassFunctionDecl();
2632
2633 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2634 SourceLocation StartLoc = Exp->getLocStart();
2635 SourceLocation EndLoc = Exp->getLocEnd();
2636
2637 // Synthesize a call to objc_msgSend().
2638 SmallVector<Expr*, 4> MsgExprs;
2639 SmallVector<Expr*, 4> ClsExprs;
2640 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002641
Patrick Beardeb382ec2012-04-19 00:25:12 +00002642 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2643 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2644 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002645
Patrick Beardeb382ec2012-04-19 00:25:12 +00002646 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002647 ClsExprs.push_back(StringLiteral::Create(*Context,
2648 clsName->getName(),
2649 StringLiteral::Ascii, false,
2650 argType, SourceLocation()));
2651 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2652 &ClsExprs[0],
2653 ClsExprs.size(),
2654 StartLoc, EndLoc);
2655 MsgExprs.push_back(Cls);
2656
Patrick Beardeb382ec2012-04-19 00:25:12 +00002657 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002658 // it will be the 2nd argument.
2659 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002660 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002661 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002662 StringLiteral::Ascii, false,
2663 argType, SourceLocation()));
2664 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2665 &SelExprs[0], SelExprs.size(),
2666 StartLoc, EndLoc);
2667 MsgExprs.push_back(SelExp);
2668
Patrick Beardeb382ec2012-04-19 00:25:12 +00002669 // User provided sub-expression is the 3rd, and last, argument.
2670 Expr *subExpr = Exp->getSubExpr();
2671 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002672 QualType type = ICE->getType();
2673 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2674 CastKind CK = CK_BitCast;
2675 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2676 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002677 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002678 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002679 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002680
2681 SmallVector<QualType, 4> ArgTypes;
2682 ArgTypes.push_back(Context->getObjCIdType());
2683 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002684 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2685 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002686 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002687
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002688 QualType returnType = Exp->getType();
2689 // Get the type, we will need to reference it in a couple spots.
2690 QualType msgSendType = MsgSendFlavor->getType();
2691
2692 // Create a reference to the objc_msgSend() declaration.
2693 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2694 VK_LValue, SourceLocation());
2695
2696 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002697 Context->getPointerType(Context->VoidTy),
2698 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002699
2700 // Now do the "normal" pointer to function cast.
2701 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002702 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2703 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002704 castType = Context->getPointerType(castType);
2705 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2706 cast);
2707
2708 // Don't forget the parens to enforce the proper binding.
2709 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2710
2711 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002712 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002713 FT->getResultType(), VK_RValue,
2714 EndLoc);
2715 ReplaceStmt(Exp, CE);
2716 return CE;
2717}
2718
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002719Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2720 // synthesize declaration of helper functions needed in this routine.
2721 if (!SelGetUidFunctionDecl)
2722 SynthSelGetUidFunctionDecl();
2723 // use objc_msgSend() for all.
2724 if (!MsgSendFunctionDecl)
2725 SynthMsgSendFunctionDecl();
2726 if (!GetClassFunctionDecl)
2727 SynthGetClassFunctionDecl();
2728
2729 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2730 SourceLocation StartLoc = Exp->getLocStart();
2731 SourceLocation EndLoc = Exp->getLocEnd();
2732
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002733 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002734 QualType IntQT = Context->IntTy;
2735 QualType NSArrayFType =
2736 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002737 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002738 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2739 DeclRefExpr *NSArrayDRE =
2740 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2741 SourceLocation());
2742
2743 SmallVector<Expr*, 16> InitExprs;
2744 unsigned NumElements = Exp->getNumElements();
2745 unsigned UnsignedIntSize =
2746 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2747 Expr *count = IntegerLiteral::Create(*Context,
2748 llvm::APInt(UnsignedIntSize, NumElements),
2749 Context->UnsignedIntTy, SourceLocation());
2750 InitExprs.push_back(count);
2751 for (unsigned i = 0; i < NumElements; i++)
2752 InitExprs.push_back(Exp->getElement(i));
2753 Expr *NSArrayCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002754 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002755 NSArrayFType, VK_LValue, SourceLocation());
2756
2757 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2758 SourceLocation(),
2759 &Context->Idents.get("arr"),
2760 Context->getPointerType(Context->VoidPtrTy), 0,
2761 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002762 ICIS_NoInit);
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002763 MemberExpr *ArrayLiteralME =
2764 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2765 SourceLocation(),
2766 ARRFD->getType(), VK_LValue,
2767 OK_Ordinary);
2768 QualType ConstIdT = Context->getObjCIdType().withConst();
2769 CStyleCastExpr * ArrayLiteralObjects =
2770 NoTypeInfoCStyleCastExpr(Context,
2771 Context->getPointerType(ConstIdT),
2772 CK_BitCast,
2773 ArrayLiteralME);
2774
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002775 // Synthesize a call to objc_msgSend().
2776 SmallVector<Expr*, 32> MsgExprs;
2777 SmallVector<Expr*, 4> ClsExprs;
2778 QualType argType = Context->getPointerType(Context->CharTy);
2779 QualType expType = Exp->getType();
2780
2781 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2782 ObjCInterfaceDecl *Class =
2783 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2784
2785 IdentifierInfo *clsName = Class->getIdentifier();
2786 ClsExprs.push_back(StringLiteral::Create(*Context,
2787 clsName->getName(),
2788 StringLiteral::Ascii, false,
2789 argType, SourceLocation()));
2790 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2791 &ClsExprs[0],
2792 ClsExprs.size(),
2793 StartLoc, EndLoc);
2794 MsgExprs.push_back(Cls);
2795
2796 // Create a call to sel_registerName("arrayWithObjects:count:").
2797 // it will be the 2nd argument.
2798 SmallVector<Expr*, 4> SelExprs;
2799 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2800 SelExprs.push_back(StringLiteral::Create(*Context,
2801 ArrayMethod->getSelector().getAsString(),
2802 StringLiteral::Ascii, false,
2803 argType, SourceLocation()));
2804 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2805 &SelExprs[0], SelExprs.size(),
2806 StartLoc, EndLoc);
2807 MsgExprs.push_back(SelExp);
2808
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002809 // (const id [])objects
2810 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002811
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002812 // (NSUInteger)cnt
2813 Expr *cnt = IntegerLiteral::Create(*Context,
2814 llvm::APInt(UnsignedIntSize, NumElements),
2815 Context->UnsignedIntTy, SourceLocation());
2816 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002817
2818
2819 SmallVector<QualType, 4> ArgTypes;
2820 ArgTypes.push_back(Context->getObjCIdType());
2821 ArgTypes.push_back(Context->getObjCSelType());
2822 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2823 E = ArrayMethod->param_end(); PI != E; ++PI)
2824 ArgTypes.push_back((*PI)->getType());
2825
2826 QualType returnType = Exp->getType();
2827 // Get the type, we will need to reference it in a couple spots.
2828 QualType msgSendType = MsgSendFlavor->getType();
2829
2830 // Create a reference to the objc_msgSend() declaration.
2831 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2832 VK_LValue, SourceLocation());
2833
2834 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2835 Context->getPointerType(Context->VoidTy),
2836 CK_BitCast, DRE);
2837
2838 // Now do the "normal" pointer to function cast.
2839 QualType castType =
2840 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2841 ArrayMethod->isVariadic());
2842 castType = Context->getPointerType(castType);
2843 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2844 cast);
2845
2846 // Don't forget the parens to enforce the proper binding.
2847 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2848
2849 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002850 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002851 FT->getResultType(), VK_RValue,
2852 EndLoc);
2853 ReplaceStmt(Exp, CE);
2854 return CE;
2855}
2856
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002857Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2858 // synthesize declaration of helper functions needed in this routine.
2859 if (!SelGetUidFunctionDecl)
2860 SynthSelGetUidFunctionDecl();
2861 // use objc_msgSend() for all.
2862 if (!MsgSendFunctionDecl)
2863 SynthMsgSendFunctionDecl();
2864 if (!GetClassFunctionDecl)
2865 SynthGetClassFunctionDecl();
2866
2867 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2868 SourceLocation StartLoc = Exp->getLocStart();
2869 SourceLocation EndLoc = Exp->getLocEnd();
2870
2871 // Build the expression: __NSContainer_literal(int, ...).arr
2872 QualType IntQT = Context->IntTy;
2873 QualType NSDictFType =
2874 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2875 std::string NSDictFName("__NSContainer_literal");
2876 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2877 DeclRefExpr *NSDictDRE =
2878 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2879 SourceLocation());
2880
2881 SmallVector<Expr*, 16> KeyExprs;
2882 SmallVector<Expr*, 16> ValueExprs;
2883
2884 unsigned NumElements = Exp->getNumElements();
2885 unsigned UnsignedIntSize =
2886 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2887 Expr *count = IntegerLiteral::Create(*Context,
2888 llvm::APInt(UnsignedIntSize, NumElements),
2889 Context->UnsignedIntTy, SourceLocation());
2890 KeyExprs.push_back(count);
2891 ValueExprs.push_back(count);
2892 for (unsigned i = 0; i < NumElements; i++) {
2893 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2894 KeyExprs.push_back(Element.Key);
2895 ValueExprs.push_back(Element.Value);
2896 }
2897
2898 // (const id [])objects
2899 Expr *NSValueCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002900 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002901 NSDictFType, VK_LValue, SourceLocation());
2902
2903 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2904 SourceLocation(),
2905 &Context->Idents.get("arr"),
2906 Context->getPointerType(Context->VoidPtrTy), 0,
2907 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002908 ICIS_NoInit);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002909 MemberExpr *DictLiteralValueME =
2910 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2911 SourceLocation(),
2912 ARRFD->getType(), VK_LValue,
2913 OK_Ordinary);
2914 QualType ConstIdT = Context->getObjCIdType().withConst();
2915 CStyleCastExpr * DictValueObjects =
2916 NoTypeInfoCStyleCastExpr(Context,
2917 Context->getPointerType(ConstIdT),
2918 CK_BitCast,
2919 DictLiteralValueME);
2920 // (const id <NSCopying> [])keys
2921 Expr *NSKeyCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002922 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002923 NSDictFType, VK_LValue, SourceLocation());
2924
2925 MemberExpr *DictLiteralKeyME =
2926 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2927 SourceLocation(),
2928 ARRFD->getType(), VK_LValue,
2929 OK_Ordinary);
2930
2931 CStyleCastExpr * DictKeyObjects =
2932 NoTypeInfoCStyleCastExpr(Context,
2933 Context->getPointerType(ConstIdT),
2934 CK_BitCast,
2935 DictLiteralKeyME);
2936
2937
2938
2939 // Synthesize a call to objc_msgSend().
2940 SmallVector<Expr*, 32> MsgExprs;
2941 SmallVector<Expr*, 4> ClsExprs;
2942 QualType argType = Context->getPointerType(Context->CharTy);
2943 QualType expType = Exp->getType();
2944
2945 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2946 ObjCInterfaceDecl *Class =
2947 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2948
2949 IdentifierInfo *clsName = Class->getIdentifier();
2950 ClsExprs.push_back(StringLiteral::Create(*Context,
2951 clsName->getName(),
2952 StringLiteral::Ascii, false,
2953 argType, SourceLocation()));
2954 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2955 &ClsExprs[0],
2956 ClsExprs.size(),
2957 StartLoc, EndLoc);
2958 MsgExprs.push_back(Cls);
2959
2960 // Create a call to sel_registerName("arrayWithObjects:count:").
2961 // it will be the 2nd argument.
2962 SmallVector<Expr*, 4> SelExprs;
2963 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2964 SelExprs.push_back(StringLiteral::Create(*Context,
2965 DictMethod->getSelector().getAsString(),
2966 StringLiteral::Ascii, false,
2967 argType, SourceLocation()));
2968 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2969 &SelExprs[0], SelExprs.size(),
2970 StartLoc, EndLoc);
2971 MsgExprs.push_back(SelExp);
2972
2973 // (const id [])objects
2974 MsgExprs.push_back(DictValueObjects);
2975
2976 // (const id <NSCopying> [])keys
2977 MsgExprs.push_back(DictKeyObjects);
2978
2979 // (NSUInteger)cnt
2980 Expr *cnt = IntegerLiteral::Create(*Context,
2981 llvm::APInt(UnsignedIntSize, NumElements),
2982 Context->UnsignedIntTy, SourceLocation());
2983 MsgExprs.push_back(cnt);
2984
2985
2986 SmallVector<QualType, 8> ArgTypes;
2987 ArgTypes.push_back(Context->getObjCIdType());
2988 ArgTypes.push_back(Context->getObjCSelType());
2989 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2990 E = DictMethod->param_end(); PI != E; ++PI) {
2991 QualType T = (*PI)->getType();
2992 if (const PointerType* PT = T->getAs<PointerType>()) {
2993 QualType PointeeTy = PT->getPointeeType();
2994 convertToUnqualifiedObjCType(PointeeTy);
2995 T = Context->getPointerType(PointeeTy);
2996 }
2997 ArgTypes.push_back(T);
2998 }
2999
3000 QualType returnType = Exp->getType();
3001 // Get the type, we will need to reference it in a couple spots.
3002 QualType msgSendType = MsgSendFlavor->getType();
3003
3004 // Create a reference to the objc_msgSend() declaration.
3005 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3006 VK_LValue, SourceLocation());
3007
3008 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3009 Context->getPointerType(Context->VoidTy),
3010 CK_BitCast, DRE);
3011
3012 // Now do the "normal" pointer to function cast.
3013 QualType castType =
3014 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3015 DictMethod->isVariadic());
3016 castType = Context->getPointerType(castType);
3017 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3018 cast);
3019
3020 // Don't forget the parens to enforce the proper binding.
3021 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3022
3023 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003024 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003025 FT->getResultType(), VK_RValue,
3026 EndLoc);
3027 ReplaceStmt(Exp, CE);
3028 return CE;
3029}
3030
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003031// struct __rw_objc_super {
3032// struct objc_object *object; struct objc_object *superClass;
3033// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003034QualType RewriteModernObjC::getSuperStructType() {
3035 if (!SuperStructDecl) {
3036 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3037 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003038 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003039 QualType FieldTypes[2];
3040
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003041 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003042 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003043 // struct objc_object *superClass;
3044 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003045
3046 // Create fields
3047 for (unsigned i = 0; i < 2; ++i) {
3048 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3049 SourceLocation(),
3050 SourceLocation(), 0,
3051 FieldTypes[i], 0,
3052 /*BitWidth=*/0,
3053 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003054 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003055 }
3056
3057 SuperStructDecl->completeDefinition();
3058 }
3059 return Context->getTagDeclType(SuperStructDecl);
3060}
3061
3062QualType RewriteModernObjC::getConstantStringStructType() {
3063 if (!ConstantStringDecl) {
3064 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3065 SourceLocation(), SourceLocation(),
3066 &Context->Idents.get("__NSConstantStringImpl"));
3067 QualType FieldTypes[4];
3068
3069 // struct objc_object *receiver;
3070 FieldTypes[0] = Context->getObjCIdType();
3071 // int flags;
3072 FieldTypes[1] = Context->IntTy;
3073 // char *str;
3074 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3075 // long length;
3076 FieldTypes[3] = Context->LongTy;
3077
3078 // Create fields
3079 for (unsigned i = 0; i < 4; ++i) {
3080 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3081 ConstantStringDecl,
3082 SourceLocation(),
3083 SourceLocation(), 0,
3084 FieldTypes[i], 0,
3085 /*BitWidth=*/0,
3086 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003087 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003088 }
3089
3090 ConstantStringDecl->completeDefinition();
3091 }
3092 return Context->getTagDeclType(ConstantStringDecl);
3093}
3094
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003095/// getFunctionSourceLocation - returns start location of a function
3096/// definition. Complication arises when function has declared as
3097/// extern "C" or extern "C" {...}
3098static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3099 FunctionDecl *FD) {
3100 if (FD->isExternC() && !FD->isMain()) {
3101 const DeclContext *DC = FD->getDeclContext();
3102 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3103 // if it is extern "C" {...}, return function decl's own location.
3104 if (!LSD->getRBraceLoc().isValid())
3105 return LSD->getExternLoc();
3106 }
3107 if (FD->getStorageClassAsWritten() != SC_None)
3108 R.RewriteBlockLiteralFunctionDecl(FD);
3109 return FD->getTypeSpecStartLoc();
3110}
3111
Fariborz Jahanian96205962012-11-06 17:30:23 +00003112void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3113
3114 SourceLocation Location = D->getLocation();
3115
3116 if (Location.isFileID()) {
Fariborz Jahanian3b45ca92012-11-07 18:15:53 +00003117 std::string LineString("\n#line ");
Fariborz Jahanian96205962012-11-06 17:30:23 +00003118 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3119 LineString += utostr(PLoc.getLine());
3120 LineString += " \"";
NAKAMURA Takumiba529a92012-11-06 22:45:31 +00003121 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanian96205962012-11-06 17:30:23 +00003122 if (isa<ObjCMethodDecl>(D))
3123 LineString += "\"";
3124 else LineString += "\"\n";
3125
3126 Location = D->getLocStart();
3127 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3128 if (FD->isExternC() && !FD->isMain()) {
3129 const DeclContext *DC = FD->getDeclContext();
3130 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3131 // if it is extern "C" {...}, return function decl's own location.
3132 if (!LSD->getRBraceLoc().isValid())
3133 Location = LSD->getExternLoc();
3134 }
3135 }
3136 InsertText(Location, LineString);
3137 }
3138}
3139
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003140/// SynthMsgSendStretCallExpr - This routine translates message expression
3141/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3142/// nil check on receiver must be performed before calling objc_msgSend_stret.
3143/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3144/// msgSendType - function type of objc_msgSend_stret(...)
3145/// returnType - Result type of the method being synthesized.
3146/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3147/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3148/// starting with receiver.
3149/// Method - Method being rewritten.
3150Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3151 QualType msgSendType,
3152 QualType returnType,
3153 SmallVectorImpl<QualType> &ArgTypes,
3154 SmallVectorImpl<Expr*> &MsgExprs,
3155 ObjCMethodDecl *Method) {
3156 // Now do the "normal" pointer to function cast.
3157 QualType castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3158 Method ? Method->isVariadic() : false);
3159 castType = Context->getPointerType(castType);
3160
3161 // build type for containing the objc_msgSend_stret object.
3162 static unsigned stretCount=0;
3163 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003164 std::string str =
3165 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3166 str += "struct "; str += name;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003167 str += " {\n\t";
3168 str += name;
3169 str += "(id receiver, SEL sel";
3170 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003171 std::string ArgName = "arg"; ArgName += utostr(i);
3172 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3173 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003174 }
3175 // could be vararg.
3176 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003177 std::string ArgName = "arg"; ArgName += utostr(i);
3178 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3179 Context->getPrintingPolicy());
3180 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003181 }
3182
3183 str += ") {\n";
3184 str += "\t if (receiver == 0)\n";
3185 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3186 str += "\t else\n";
3187 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3188 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3189 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3190 str += ", arg"; str += utostr(i);
3191 }
3192 // could be vararg.
3193 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3194 str += ", arg"; str += utostr(i);
3195 }
3196
3197 str += ");\n";
3198 str += "\t}\n";
3199 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3200 str += " s;\n";
3201 str += "};\n\n";
Fariborz Jahaniana6e5a6e2012-08-21 18:56:50 +00003202 SourceLocation FunLocStart;
3203 if (CurFunctionDef)
3204 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3205 else {
3206 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3207 FunLocStart = CurMethodDef->getLocStart();
3208 }
3209
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003210 InsertText(FunLocStart, str);
3211 ++stretCount;
3212
3213 // AST for __Stretn(receiver, args).s;
3214 IdentifierInfo *ID = &Context->Idents.get(name);
3215 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
3216 SourceLocation(), ID, castType, 0, SC_Extern,
3217 SC_None, false, false);
3218 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3219 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003220 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003221 castType, VK_LValue, SourceLocation());
3222
3223 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3224 SourceLocation(),
3225 &Context->Idents.get("s"),
3226 returnType, 0,
3227 /*BitWidth=*/0, /*Mutable=*/true,
3228 ICIS_NoInit);
3229 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3230 FieldD->getType(), VK_LValue,
3231 OK_Ordinary);
3232
3233 return ME;
3234}
3235
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003236Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3237 SourceLocation StartLoc,
3238 SourceLocation EndLoc) {
3239 if (!SelGetUidFunctionDecl)
3240 SynthSelGetUidFunctionDecl();
3241 if (!MsgSendFunctionDecl)
3242 SynthMsgSendFunctionDecl();
3243 if (!MsgSendSuperFunctionDecl)
3244 SynthMsgSendSuperFunctionDecl();
3245 if (!MsgSendStretFunctionDecl)
3246 SynthMsgSendStretFunctionDecl();
3247 if (!MsgSendSuperStretFunctionDecl)
3248 SynthMsgSendSuperStretFunctionDecl();
3249 if (!MsgSendFpretFunctionDecl)
3250 SynthMsgSendFpretFunctionDecl();
3251 if (!GetClassFunctionDecl)
3252 SynthGetClassFunctionDecl();
3253 if (!GetSuperClassFunctionDecl)
3254 SynthGetSuperClassFunctionDecl();
3255 if (!GetMetaClassFunctionDecl)
3256 SynthGetMetaClassFunctionDecl();
3257
3258 // default to objc_msgSend().
3259 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3260 // May need to use objc_msgSend_stret() as well.
3261 FunctionDecl *MsgSendStretFlavor = 0;
3262 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3263 QualType resultType = mDecl->getResultType();
3264 if (resultType->isRecordType())
3265 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3266 else if (resultType->isRealFloatingType())
3267 MsgSendFlavor = MsgSendFpretFunctionDecl;
3268 }
3269
3270 // Synthesize a call to objc_msgSend().
3271 SmallVector<Expr*, 8> MsgExprs;
3272 switch (Exp->getReceiverKind()) {
3273 case ObjCMessageExpr::SuperClass: {
3274 MsgSendFlavor = MsgSendSuperFunctionDecl;
3275 if (MsgSendStretFlavor)
3276 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3277 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3278
3279 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3280
3281 SmallVector<Expr*, 4> InitExprs;
3282
3283 // set the receiver to self, the first argument to all methods.
3284 InitExprs.push_back(
3285 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3286 CK_BitCast,
3287 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003288 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003289 Context->getObjCIdType(),
3290 VK_RValue,
3291 SourceLocation()))
3292 ); // set the 'receiver'.
3293
3294 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3295 SmallVector<Expr*, 8> ClsExprs;
3296 QualType argType = Context->getPointerType(Context->CharTy);
3297 ClsExprs.push_back(StringLiteral::Create(*Context,
3298 ClassDecl->getIdentifier()->getName(),
3299 StringLiteral::Ascii, false,
3300 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003301 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003302 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3303 &ClsExprs[0],
3304 ClsExprs.size(),
3305 StartLoc,
3306 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003307 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003308 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003309 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3310 &ClsExprs[0], ClsExprs.size(),
3311 StartLoc, EndLoc);
3312
3313 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3314 // To turn off a warning, type-cast to 'id'
3315 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3316 NoTypeInfoCStyleCastExpr(Context,
3317 Context->getObjCIdType(),
3318 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003319 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003320 QualType superType = getSuperStructType();
3321 Expr *SuperRep;
3322
3323 if (LangOpts.MicrosoftExt) {
3324 SynthSuperContructorFunctionDecl();
3325 // Simulate a contructor call...
3326 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003327 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003328 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003329 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003330 superType, VK_LValue,
3331 SourceLocation());
3332 // The code for super is a little tricky to prevent collision with
3333 // the structure definition in the header. The rewriter has it's own
3334 // internal definition (__rw_objc_super) that is uses. This is why
3335 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003336 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003337 //
3338 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3339 Context->getPointerType(SuperRep->getType()),
3340 VK_RValue, OK_Ordinary,
3341 SourceLocation());
3342 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3343 Context->getPointerType(superType),
3344 CK_BitCast, SuperRep);
3345 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003346 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003347 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003348 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003349 SourceLocation());
3350 TypeSourceInfo *superTInfo
3351 = Context->getTrivialTypeSourceInfo(superType);
3352 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3353 superType, VK_LValue,
3354 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003355 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003356 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3357 Context->getPointerType(SuperRep->getType()),
3358 VK_RValue, OK_Ordinary,
3359 SourceLocation());
3360 }
3361 MsgExprs.push_back(SuperRep);
3362 break;
3363 }
3364
3365 case ObjCMessageExpr::Class: {
3366 SmallVector<Expr*, 8> ClsExprs;
3367 QualType argType = Context->getPointerType(Context->CharTy);
3368 ObjCInterfaceDecl *Class
3369 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3370 IdentifierInfo *clsName = Class->getIdentifier();
3371 ClsExprs.push_back(StringLiteral::Create(*Context,
3372 clsName->getName(),
3373 StringLiteral::Ascii, false,
3374 argType, SourceLocation()));
3375 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3376 &ClsExprs[0],
3377 ClsExprs.size(),
3378 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003379 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3380 Context->getObjCIdType(),
3381 CK_BitCast, Cls);
3382 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003383 break;
3384 }
3385
3386 case ObjCMessageExpr::SuperInstance:{
3387 MsgSendFlavor = MsgSendSuperFunctionDecl;
3388 if (MsgSendStretFlavor)
3389 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3390 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3391 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3392 SmallVector<Expr*, 4> InitExprs;
3393
3394 InitExprs.push_back(
3395 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3396 CK_BitCast,
3397 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003398 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003399 Context->getObjCIdType(),
3400 VK_RValue, SourceLocation()))
3401 ); // set the 'receiver'.
3402
3403 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3404 SmallVector<Expr*, 8> ClsExprs;
3405 QualType argType = Context->getPointerType(Context->CharTy);
3406 ClsExprs.push_back(StringLiteral::Create(*Context,
3407 ClassDecl->getIdentifier()->getName(),
3408 StringLiteral::Ascii, false, argType,
3409 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003410 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003411 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3412 &ClsExprs[0],
3413 ClsExprs.size(),
3414 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003415 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003416 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003417 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3418 &ClsExprs[0], ClsExprs.size(),
3419 StartLoc, EndLoc);
3420
3421 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3422 // To turn off a warning, type-cast to 'id'
3423 InitExprs.push_back(
3424 // set 'super class', using class_getSuperclass().
3425 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3426 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003427 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003428 QualType superType = getSuperStructType();
3429 Expr *SuperRep;
3430
3431 if (LangOpts.MicrosoftExt) {
3432 SynthSuperContructorFunctionDecl();
3433 // Simulate a contructor call...
3434 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003435 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003436 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003437 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003438 superType, VK_LValue, SourceLocation());
3439 // The code for super is a little tricky to prevent collision with
3440 // the structure definition in the header. The rewriter has it's own
3441 // internal definition (__rw_objc_super) that is uses. This is why
3442 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003443 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003444 //
3445 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3446 Context->getPointerType(SuperRep->getType()),
3447 VK_RValue, OK_Ordinary,
3448 SourceLocation());
3449 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3450 Context->getPointerType(superType),
3451 CK_BitCast, SuperRep);
3452 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003453 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003454 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003455 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003456 SourceLocation());
3457 TypeSourceInfo *superTInfo
3458 = Context->getTrivialTypeSourceInfo(superType);
3459 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3460 superType, VK_RValue, ILE,
3461 false);
3462 }
3463 MsgExprs.push_back(SuperRep);
3464 break;
3465 }
3466
3467 case ObjCMessageExpr::Instance: {
3468 // Remove all type-casts because it may contain objc-style types; e.g.
3469 // Foo<Proto> *.
3470 Expr *recExpr = Exp->getInstanceReceiver();
3471 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3472 recExpr = CE->getSubExpr();
3473 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3474 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3475 ? CK_BlockPointerToObjCPointerCast
3476 : CK_CPointerToObjCPointerCast;
3477
3478 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3479 CK, recExpr);
3480 MsgExprs.push_back(recExpr);
3481 break;
3482 }
3483 }
3484
3485 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3486 SmallVector<Expr*, 8> SelExprs;
3487 QualType argType = Context->getPointerType(Context->CharTy);
3488 SelExprs.push_back(StringLiteral::Create(*Context,
3489 Exp->getSelector().getAsString(),
3490 StringLiteral::Ascii, false,
3491 argType, SourceLocation()));
3492 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3493 &SelExprs[0], SelExprs.size(),
3494 StartLoc,
3495 EndLoc);
3496 MsgExprs.push_back(SelExp);
3497
3498 // Now push any user supplied arguments.
3499 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3500 Expr *userExpr = Exp->getArg(i);
3501 // Make all implicit casts explicit...ICE comes in handy:-)
3502 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3503 // Reuse the ICE type, it is exactly what the doctor ordered.
3504 QualType type = ICE->getType();
3505 if (needToScanForQualifiers(type))
3506 type = Context->getObjCIdType();
3507 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3508 (void)convertBlockPointerToFunctionPointer(type);
3509 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3510 CastKind CK;
3511 if (SubExpr->getType()->isIntegralType(*Context) &&
3512 type->isBooleanType()) {
3513 CK = CK_IntegralToBoolean;
3514 } else if (type->isObjCObjectPointerType()) {
3515 if (SubExpr->getType()->isBlockPointerType()) {
3516 CK = CK_BlockPointerToObjCPointerCast;
3517 } else if (SubExpr->getType()->isPointerType()) {
3518 CK = CK_CPointerToObjCPointerCast;
3519 } else {
3520 CK = CK_BitCast;
3521 }
3522 } else {
3523 CK = CK_BitCast;
3524 }
3525
3526 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3527 }
3528 // Make id<P...> cast into an 'id' cast.
3529 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3530 if (CE->getType()->isObjCQualifiedIdType()) {
3531 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3532 userExpr = CE->getSubExpr();
3533 CastKind CK;
3534 if (userExpr->getType()->isIntegralType(*Context)) {
3535 CK = CK_IntegralToPointer;
3536 } else if (userExpr->getType()->isBlockPointerType()) {
3537 CK = CK_BlockPointerToObjCPointerCast;
3538 } else if (userExpr->getType()->isPointerType()) {
3539 CK = CK_CPointerToObjCPointerCast;
3540 } else {
3541 CK = CK_BitCast;
3542 }
3543 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3544 CK, userExpr);
3545 }
3546 }
3547 MsgExprs.push_back(userExpr);
3548 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3549 // out the argument in the original expression (since we aren't deleting
3550 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3551 //Exp->setArg(i, 0);
3552 }
3553 // Generate the funky cast.
3554 CastExpr *cast;
3555 SmallVector<QualType, 8> ArgTypes;
3556 QualType returnType;
3557
3558 // Push 'id' and 'SEL', the 2 implicit arguments.
3559 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3560 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3561 else
3562 ArgTypes.push_back(Context->getObjCIdType());
3563 ArgTypes.push_back(Context->getObjCSelType());
3564 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3565 // Push any user argument types.
3566 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3567 E = OMD->param_end(); PI != E; ++PI) {
3568 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3569 ? Context->getObjCIdType()
3570 : (*PI)->getType();
3571 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3572 (void)convertBlockPointerToFunctionPointer(t);
3573 ArgTypes.push_back(t);
3574 }
3575 returnType = Exp->getType();
3576 convertToUnqualifiedObjCType(returnType);
3577 (void)convertBlockPointerToFunctionPointer(returnType);
3578 } else {
3579 returnType = Context->getObjCIdType();
3580 }
3581 // Get the type, we will need to reference it in a couple spots.
3582 QualType msgSendType = MsgSendFlavor->getType();
3583
3584 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003585 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003586 VK_LValue, SourceLocation());
3587
3588 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3589 // If we don't do this cast, we get the following bizarre warning/note:
3590 // xx.m:13: warning: function called through a non-compatible type
3591 // xx.m:13: note: if this code is reached, the program will abort
3592 cast = NoTypeInfoCStyleCastExpr(Context,
3593 Context->getPointerType(Context->VoidTy),
3594 CK_BitCast, DRE);
3595
3596 // Now do the "normal" pointer to function cast.
3597 QualType castType =
3598 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3599 // If we don't have a method decl, force a variadic cast.
3600 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3601 castType = Context->getPointerType(castType);
3602 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3603 cast);
3604
3605 // Don't forget the parens to enforce the proper binding.
3606 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3607
3608 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003609 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3610 FT->getResultType(), VK_RValue, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003611 Stmt *ReplacingStmt = CE;
3612 if (MsgSendStretFlavor) {
3613 // We have the method which returns a struct/union. Must also generate
3614 // call to objc_msgSend_stret and hang both varieties on a conditional
3615 // expression which dictate which one to envoke depending on size of
3616 // method's return type.
3617
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003618 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3619 msgSendType, returnType,
3620 ArgTypes, MsgExprs,
3621 Exp->getMethodDecl());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003622
3623 // Build sizeof(returnType)
3624 UnaryExprOrTypeTraitExpr *sizeofExpr =
3625 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3626 Context->getTrivialTypeSourceInfo(returnType),
3627 Context->getSizeType(), SourceLocation(),
3628 SourceLocation());
3629 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3630 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3631 // For X86 it is more complicated and some kind of target specific routine
3632 // is needed to decide what to do.
3633 unsigned IntSize =
3634 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3635 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3636 llvm::APInt(IntSize, 8),
3637 Context->IntTy,
3638 SourceLocation());
3639 BinaryOperator *lessThanExpr =
3640 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00003641 VK_RValue, OK_Ordinary, SourceLocation(),
3642 false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003643 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3644 ConditionalOperator *CondExpr =
3645 new (Context) ConditionalOperator(lessThanExpr,
3646 SourceLocation(), CE,
3647 SourceLocation(), STCE,
3648 returnType, VK_RValue, OK_Ordinary);
3649 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3650 CondExpr);
3651 }
3652 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3653 return ReplacingStmt;
3654}
3655
3656Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3657 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3658 Exp->getLocEnd());
3659
3660 // Now do the actual rewrite.
3661 ReplaceStmt(Exp, ReplacingStmt);
3662
3663 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3664 return ReplacingStmt;
3665}
3666
3667// typedef struct objc_object Protocol;
3668QualType RewriteModernObjC::getProtocolType() {
3669 if (!ProtocolTypeDecl) {
3670 TypeSourceInfo *TInfo
3671 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3672 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3673 SourceLocation(), SourceLocation(),
3674 &Context->Idents.get("Protocol"),
3675 TInfo);
3676 }
3677 return Context->getTypeDeclType(ProtocolTypeDecl);
3678}
3679
3680/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3681/// a synthesized/forward data reference (to the protocol's metadata).
3682/// The forward references (and metadata) are generated in
3683/// RewriteModernObjC::HandleTranslationUnit().
3684Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003685 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3686 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003687 IdentifierInfo *ID = &Context->Idents.get(Name);
3688 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3689 SourceLocation(), ID, getProtocolType(), 0,
3690 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003691 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3692 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003693 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3694 Context->getPointerType(DRE->getType()),
3695 VK_RValue, OK_Ordinary, SourceLocation());
3696 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3697 CK_BitCast,
3698 DerefExpr);
3699 ReplaceStmt(Exp, castExpr);
3700 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3701 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3702 return castExpr;
3703
3704}
3705
3706bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3707 const char *endBuf) {
3708 while (startBuf < endBuf) {
3709 if (*startBuf == '#') {
3710 // Skip whitespace.
3711 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3712 ;
3713 if (!strncmp(startBuf, "if", strlen("if")) ||
3714 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3715 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3716 !strncmp(startBuf, "define", strlen("define")) ||
3717 !strncmp(startBuf, "undef", strlen("undef")) ||
3718 !strncmp(startBuf, "else", strlen("else")) ||
3719 !strncmp(startBuf, "elif", strlen("elif")) ||
3720 !strncmp(startBuf, "endif", strlen("endif")) ||
3721 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3722 !strncmp(startBuf, "include", strlen("include")) ||
3723 !strncmp(startBuf, "import", strlen("import")) ||
3724 !strncmp(startBuf, "include_next", strlen("include_next")))
3725 return true;
3726 }
3727 startBuf++;
3728 }
3729 return false;
3730}
3731
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003732/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3733/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003734bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003735 TagDecl *Tag,
3736 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003737 if (!IDecl)
3738 return false;
3739 SourceLocation TagLocation;
3740 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3741 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003742 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003743 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003744 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003745 TagLocation = RD->getLocation();
3746 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003747 IDecl->getLocation(), TagLocation);
3748 }
3749 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3750 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3751 return false;
3752 IsNamedDefinition = true;
3753 TagLocation = ED->getLocation();
3754 return Context->getSourceManager().isBeforeInTranslationUnit(
3755 IDecl->getLocation(), TagLocation);
3756
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003757 }
3758 return false;
3759}
3760
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003761/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003762/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003763bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3764 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003765 if (isa<TypedefType>(Type)) {
3766 Result += "\t";
3767 return false;
3768 }
3769
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003770 if (Type->isArrayType()) {
3771 QualType ElemTy = Context->getBaseElementType(Type);
3772 return RewriteObjCFieldDeclType(ElemTy, Result);
3773 }
3774 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003775 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3776 if (RD->isCompleteDefinition()) {
3777 if (RD->isStruct())
3778 Result += "\n\tstruct ";
3779 else if (RD->isUnion())
3780 Result += "\n\tunion ";
3781 else
3782 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003783
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003784 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003785 if (GlobalDefinedTags.count(RD)) {
3786 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003787 Result += " ";
3788 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003789 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003790 Result += " {\n";
3791 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003792 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003793 FieldDecl *FD = *i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003794 RewriteObjCFieldDecl(FD, Result);
3795 }
3796 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003797 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003798 }
3799 }
3800 else if (Type->isEnumeralType()) {
3801 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3802 if (ED->isCompleteDefinition()) {
3803 Result += "\n\tenum ";
3804 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003805 if (GlobalDefinedTags.count(ED)) {
3806 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003807 Result += " ";
3808 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003809 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003810
3811 Result += " {\n";
3812 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3813 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3814 Result += "\t"; Result += EC->getName(); Result += " = ";
3815 llvm::APSInt Val = EC->getInitVal();
3816 Result += Val.toString(10);
3817 Result += ",\n";
3818 }
3819 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003820 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003821 }
3822 }
3823
3824 Result += "\t";
3825 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003826 return false;
3827}
3828
3829
3830/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3831/// It handles elaborated types, as well as enum types in the process.
3832void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3833 std::string &Result) {
3834 QualType Type = fieldDecl->getType();
3835 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003836
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003837 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3838 if (!EleboratedType)
3839 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003840 Result += Name;
3841 if (fieldDecl->isBitField()) {
3842 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3843 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003844 else if (EleboratedType && Type->isArrayType()) {
3845 CanQualType CType = Context->getCanonicalType(Type);
3846 while (isa<ArrayType>(CType)) {
3847 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3848 Result += "[";
3849 llvm::APInt Dim = CAT->getSize();
3850 Result += utostr(Dim.getZExtValue());
3851 Result += "]";
3852 }
3853 CType = CType->getAs<ArrayType>()->getElementType();
3854 }
3855 }
3856
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003857 Result += ";\n";
3858}
3859
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003860/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3861/// named aggregate types into the input buffer.
3862void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3863 std::string &Result) {
3864 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003865 if (isa<TypedefType>(Type))
3866 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003867 if (Type->isArrayType())
3868 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003869 ObjCContainerDecl *IDecl =
3870 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003871
3872 TagDecl *TD = 0;
3873 if (Type->isRecordType()) {
3874 TD = Type->getAs<RecordType>()->getDecl();
3875 }
3876 else if (Type->isEnumeralType()) {
3877 TD = Type->getAs<EnumType>()->getDecl();
3878 }
3879
3880 if (TD) {
3881 if (GlobalDefinedTags.count(TD))
3882 return;
3883
3884 bool IsNamedDefinition = false;
3885 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3886 RewriteObjCFieldDeclType(Type, Result);
3887 Result += ";";
3888 }
3889 if (IsNamedDefinition)
3890 GlobalDefinedTags.insert(TD);
3891 }
3892
3893}
3894
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003895/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3896/// an objective-c class with ivars.
3897void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3898 std::string &Result) {
3899 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3900 assert(CDecl->getName() != "" &&
3901 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003902 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003903 SmallVector<ObjCIvarDecl *, 8> IVars;
3904 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003905 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003906 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003907
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003908 SourceLocation LocStart = CDecl->getLocStart();
3909 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003910
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003911 const char *startBuf = SM->getCharacterData(LocStart);
3912 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003913
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003914 // If no ivars and no root or if its root, directly or indirectly,
3915 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003916 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003917 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3918 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3919 ReplaceText(LocStart, endBuf-startBuf, Result);
3920 return;
3921 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003922
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003923 // Insert named struct/union definitions inside class to
3924 // outer scope. This follows semantics of locally defined
3925 // struct/unions in objective-c classes.
3926 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3927 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3928
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003929 Result += "\nstruct ";
3930 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003931 Result += "_IMPL {\n";
3932
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003933 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003934 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3935 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3936 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003937 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003938
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003939 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3940 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003941
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003942 Result += "};\n";
3943 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3944 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003945 // Mark this struct as having been generated.
3946 if (!ObjCSynthesizedStructs.insert(CDecl))
3947 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003948}
3949
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003950/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3951/// have been referenced in an ivar access expression.
3952void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3953 std::string &Result) {
3954 // write out ivar offset symbols which have been referenced in an ivar
3955 // access expression.
3956 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3957 if (Ivars.empty())
3958 return;
3959 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3960 e = Ivars.end(); i != e; i++) {
3961 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003962 Result += "\n";
3963 if (LangOpts.MicrosoftExt)
3964 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003965 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003966 if (LangOpts.MicrosoftExt &&
3967 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003968 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3969 Result += "__declspec(dllimport) ";
3970
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003971 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003972 WriteInternalIvarName(CDecl, IvarDecl, Result);
3973 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003974 }
3975}
3976
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003977//===----------------------------------------------------------------------===//
3978// Meta Data Emission
3979//===----------------------------------------------------------------------===//
3980
3981
3982/// RewriteImplementations - This routine rewrites all method implementations
3983/// and emits meta-data.
3984
3985void RewriteModernObjC::RewriteImplementations() {
3986 int ClsDefCount = ClassImplementation.size();
3987 int CatDefCount = CategoryImplementation.size();
3988
3989 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003990 for (int i = 0; i < ClsDefCount; i++) {
3991 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3992 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3993 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003994 assert(false &&
3995 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003996 RewriteImplementationDecl(OIMP);
3997 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003998
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003999 for (int i = 0; i < CatDefCount; i++) {
4000 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4001 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4002 if (CDecl->isImplicitInterfaceDecl())
4003 assert(false &&
4004 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004005 RewriteImplementationDecl(CIMP);
4006 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004007}
4008
4009void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4010 const std::string &Name,
4011 ValueDecl *VD, bool def) {
4012 assert(BlockByRefDeclNo.count(VD) &&
4013 "RewriteByRefString: ByRef decl missing");
4014 if (def)
4015 ResultStr += "struct ";
4016 ResultStr += "__Block_byref_" + Name +
4017 "_" + utostr(BlockByRefDeclNo[VD]) ;
4018}
4019
4020static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4021 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4022 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4023 return false;
4024}
4025
4026std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4027 StringRef funcName,
4028 std::string Tag) {
4029 const FunctionType *AFT = CE->getFunctionType();
4030 QualType RT = AFT->getResultType();
4031 std::string StructRef = "struct " + Tag;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00004032 SourceLocation BlockLoc = CE->getExprLoc();
4033 std::string S;
4034 ConvertSourceLocationToLineDirective(BlockLoc, S);
4035
4036 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4037 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004038
4039 BlockDecl *BD = CE->getBlockDecl();
4040
4041 if (isa<FunctionNoProtoType>(AFT)) {
4042 // No user-supplied arguments. Still need to pass in a pointer to the
4043 // block (to reference imported block decl refs).
4044 S += "(" + StructRef + " *__cself)";
4045 } else if (BD->param_empty()) {
4046 S += "(" + StructRef + " *__cself)";
4047 } else {
4048 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4049 assert(FT && "SynthesizeBlockFunc: No function proto");
4050 S += '(';
4051 // first add the implicit argument.
4052 S += StructRef + " *__cself, ";
4053 std::string ParamStr;
4054 for (BlockDecl::param_iterator AI = BD->param_begin(),
4055 E = BD->param_end(); AI != E; ++AI) {
4056 if (AI != BD->param_begin()) S += ", ";
4057 ParamStr = (*AI)->getNameAsString();
4058 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00004059 (void)convertBlockPointerToFunctionPointer(QT);
4060 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004061 S += ParamStr;
4062 }
4063 if (FT->isVariadic()) {
4064 if (!BD->param_empty()) S += ", ";
4065 S += "...";
4066 }
4067 S += ')';
4068 }
4069 S += " {\n";
4070
4071 // Create local declarations to avoid rewriting all closure decl ref exprs.
4072 // First, emit a declaration for all "by ref" decls.
4073 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4074 E = BlockByRefDecls.end(); I != E; ++I) {
4075 S += " ";
4076 std::string Name = (*I)->getNameAsString();
4077 std::string TypeString;
4078 RewriteByRefString(TypeString, Name, (*I));
4079 TypeString += " *";
4080 Name = TypeString + Name;
4081 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4082 }
4083 // Next, emit a declaration for all "by copy" declarations.
4084 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4085 E = BlockByCopyDecls.end(); I != E; ++I) {
4086 S += " ";
4087 // Handle nested closure invocation. For example:
4088 //
4089 // void (^myImportedClosure)(void);
4090 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4091 //
4092 // void (^anotherClosure)(void);
4093 // anotherClosure = ^(void) {
4094 // myImportedClosure(); // import and invoke the closure
4095 // };
4096 //
4097 if (isTopLevelBlockPointerType((*I)->getType())) {
4098 RewriteBlockPointerTypeVariable(S, (*I));
4099 S += " = (";
4100 RewriteBlockPointerType(S, (*I)->getType());
4101 S += ")";
4102 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4103 }
4104 else {
4105 std::string Name = (*I)->getNameAsString();
4106 QualType QT = (*I)->getType();
4107 if (HasLocalVariableExternalStorage(*I))
4108 QT = Context->getPointerType(QT);
4109 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4110 S += Name + " = __cself->" +
4111 (*I)->getNameAsString() + "; // bound by copy\n";
4112 }
4113 }
4114 std::string RewrittenStr = RewrittenBlockExprs[CE];
4115 const char *cstr = RewrittenStr.c_str();
4116 while (*cstr++ != '{') ;
4117 S += cstr;
4118 S += "\n";
4119 return S;
4120}
4121
4122std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4123 StringRef funcName,
4124 std::string Tag) {
4125 std::string StructRef = "struct " + Tag;
4126 std::string S = "static void __";
4127
4128 S += funcName;
4129 S += "_block_copy_" + utostr(i);
4130 S += "(" + StructRef;
4131 S += "*dst, " + StructRef;
4132 S += "*src) {";
4133 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4134 E = ImportedBlockDecls.end(); I != E; ++I) {
4135 ValueDecl *VD = (*I);
4136 S += "_Block_object_assign((void*)&dst->";
4137 S += (*I)->getNameAsString();
4138 S += ", (void*)src->";
4139 S += (*I)->getNameAsString();
4140 if (BlockByRefDeclsPtrSet.count((*I)))
4141 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4142 else if (VD->getType()->isBlockPointerType())
4143 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4144 else
4145 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4146 }
4147 S += "}\n";
4148
4149 S += "\nstatic void __";
4150 S += funcName;
4151 S += "_block_dispose_" + utostr(i);
4152 S += "(" + StructRef;
4153 S += "*src) {";
4154 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4155 E = ImportedBlockDecls.end(); I != E; ++I) {
4156 ValueDecl *VD = (*I);
4157 S += "_Block_object_dispose((void*)src->";
4158 S += (*I)->getNameAsString();
4159 if (BlockByRefDeclsPtrSet.count((*I)))
4160 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4161 else if (VD->getType()->isBlockPointerType())
4162 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4163 else
4164 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4165 }
4166 S += "}\n";
4167 return S;
4168}
4169
4170std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4171 std::string Desc) {
4172 std::string S = "\nstruct " + Tag;
4173 std::string Constructor = " " + Tag;
4174
4175 S += " {\n struct __block_impl impl;\n";
4176 S += " struct " + Desc;
4177 S += "* Desc;\n";
4178
4179 Constructor += "(void *fp, "; // Invoke function pointer.
4180 Constructor += "struct " + Desc; // Descriptor pointer.
4181 Constructor += " *desc";
4182
4183 if (BlockDeclRefs.size()) {
4184 // Output all "by copy" declarations.
4185 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4186 E = BlockByCopyDecls.end(); I != E; ++I) {
4187 S += " ";
4188 std::string FieldName = (*I)->getNameAsString();
4189 std::string ArgName = "_" + FieldName;
4190 // Handle nested closure invocation. For example:
4191 //
4192 // void (^myImportedBlock)(void);
4193 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4194 //
4195 // void (^anotherBlock)(void);
4196 // anotherBlock = ^(void) {
4197 // myImportedBlock(); // import and invoke the closure
4198 // };
4199 //
4200 if (isTopLevelBlockPointerType((*I)->getType())) {
4201 S += "struct __block_impl *";
4202 Constructor += ", void *" + ArgName;
4203 } else {
4204 QualType QT = (*I)->getType();
4205 if (HasLocalVariableExternalStorage(*I))
4206 QT = Context->getPointerType(QT);
4207 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4208 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4209 Constructor += ", " + ArgName;
4210 }
4211 S += FieldName + ";\n";
4212 }
4213 // Output all "by ref" declarations.
4214 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4215 E = BlockByRefDecls.end(); I != E; ++I) {
4216 S += " ";
4217 std::string FieldName = (*I)->getNameAsString();
4218 std::string ArgName = "_" + FieldName;
4219 {
4220 std::string TypeString;
4221 RewriteByRefString(TypeString, FieldName, (*I));
4222 TypeString += " *";
4223 FieldName = TypeString + FieldName;
4224 ArgName = TypeString + ArgName;
4225 Constructor += ", " + ArgName;
4226 }
4227 S += FieldName + "; // by ref\n";
4228 }
4229 // Finish writing the constructor.
4230 Constructor += ", int flags=0)";
4231 // Initialize all "by copy" arguments.
4232 bool firsTime = true;
4233 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4234 E = BlockByCopyDecls.end(); I != E; ++I) {
4235 std::string Name = (*I)->getNameAsString();
4236 if (firsTime) {
4237 Constructor += " : ";
4238 firsTime = false;
4239 }
4240 else
4241 Constructor += ", ";
4242 if (isTopLevelBlockPointerType((*I)->getType()))
4243 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4244 else
4245 Constructor += Name + "(_" + Name + ")";
4246 }
4247 // Initialize all "by ref" arguments.
4248 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4249 E = BlockByRefDecls.end(); I != E; ++I) {
4250 std::string Name = (*I)->getNameAsString();
4251 if (firsTime) {
4252 Constructor += " : ";
4253 firsTime = false;
4254 }
4255 else
4256 Constructor += ", ";
4257 Constructor += Name + "(_" + Name + "->__forwarding)";
4258 }
4259
4260 Constructor += " {\n";
4261 if (GlobalVarDecl)
4262 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4263 else
4264 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4265 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4266
4267 Constructor += " Desc = desc;\n";
4268 } else {
4269 // Finish writing the constructor.
4270 Constructor += ", int flags=0) {\n";
4271 if (GlobalVarDecl)
4272 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4273 else
4274 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4275 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4276 Constructor += " Desc = desc;\n";
4277 }
4278 Constructor += " ";
4279 Constructor += "}\n";
4280 S += Constructor;
4281 S += "};\n";
4282 return S;
4283}
4284
4285std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4286 std::string ImplTag, int i,
4287 StringRef FunName,
4288 unsigned hasCopy) {
4289 std::string S = "\nstatic struct " + DescTag;
4290
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004291 S += " {\n size_t reserved;\n";
4292 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004293 if (hasCopy) {
4294 S += " void (*copy)(struct ";
4295 S += ImplTag; S += "*, struct ";
4296 S += ImplTag; S += "*);\n";
4297
4298 S += " void (*dispose)(struct ";
4299 S += ImplTag; S += "*);\n";
4300 }
4301 S += "} ";
4302
4303 S += DescTag + "_DATA = { 0, sizeof(struct ";
4304 S += ImplTag + ")";
4305 if (hasCopy) {
4306 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4307 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4308 }
4309 S += "};\n";
4310 return S;
4311}
4312
4313void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4314 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004315 bool RewriteSC = (GlobalVarDecl &&
4316 !Blocks.empty() &&
4317 GlobalVarDecl->getStorageClass() == SC_Static &&
4318 GlobalVarDecl->getType().getCVRQualifiers());
4319 if (RewriteSC) {
4320 std::string SC(" void __");
4321 SC += GlobalVarDecl->getNameAsString();
4322 SC += "() {}";
4323 InsertText(FunLocStart, SC);
4324 }
4325
4326 // Insert closures that were part of the function.
4327 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4328 CollectBlockDeclRefInfo(Blocks[i]);
4329 // Need to copy-in the inner copied-in variables not actually used in this
4330 // block.
4331 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004332 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004333 ValueDecl *VD = Exp->getDecl();
4334 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004335 if (!VD->hasAttr<BlocksAttr>()) {
4336 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4337 BlockByCopyDeclsPtrSet.insert(VD);
4338 BlockByCopyDecls.push_back(VD);
4339 }
4340 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004341 }
John McCallf4b88a42012-03-10 09:33:50 +00004342
4343 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004344 BlockByRefDeclsPtrSet.insert(VD);
4345 BlockByRefDecls.push_back(VD);
4346 }
John McCallf4b88a42012-03-10 09:33:50 +00004347
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004348 // imported objects in the inner blocks not used in the outer
4349 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004350 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004351 VD->getType()->isBlockPointerType())
4352 ImportedBlockDecls.insert(VD);
4353 }
4354
4355 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4356 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4357
4358 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4359
4360 InsertText(FunLocStart, CI);
4361
4362 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4363
4364 InsertText(FunLocStart, CF);
4365
4366 if (ImportedBlockDecls.size()) {
4367 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4368 InsertText(FunLocStart, HF);
4369 }
4370 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4371 ImportedBlockDecls.size() > 0);
4372 InsertText(FunLocStart, BD);
4373
4374 BlockDeclRefs.clear();
4375 BlockByRefDecls.clear();
4376 BlockByRefDeclsPtrSet.clear();
4377 BlockByCopyDecls.clear();
4378 BlockByCopyDeclsPtrSet.clear();
4379 ImportedBlockDecls.clear();
4380 }
4381 if (RewriteSC) {
4382 // Must insert any 'const/volatile/static here. Since it has been
4383 // removed as result of rewriting of block literals.
4384 std::string SC;
4385 if (GlobalVarDecl->getStorageClass() == SC_Static)
4386 SC = "static ";
4387 if (GlobalVarDecl->getType().isConstQualified())
4388 SC += "const ";
4389 if (GlobalVarDecl->getType().isVolatileQualified())
4390 SC += "volatile ";
4391 if (GlobalVarDecl->getType().isRestrictQualified())
4392 SC += "restrict ";
4393 InsertText(FunLocStart, SC);
4394 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004395 if (GlobalConstructionExp) {
4396 // extra fancy dance for global literal expression.
4397
4398 // Always the latest block expression on the block stack.
4399 std::string Tag = "__";
4400 Tag += FunName;
4401 Tag += "_block_impl_";
4402 Tag += utostr(Blocks.size()-1);
4403 std::string globalBuf = "static ";
4404 globalBuf += Tag; globalBuf += " ";
4405 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004406
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004407 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004408 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004409 PrintingPolicy(LangOpts));
4410 globalBuf += constructorExprBuf.str();
4411 globalBuf += ";\n";
4412 InsertText(FunLocStart, globalBuf);
4413 GlobalConstructionExp = 0;
4414 }
4415
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004416 Blocks.clear();
4417 InnerDeclRefsCount.clear();
4418 InnerDeclRefs.clear();
4419 RewrittenBlockExprs.clear();
4420}
4421
4422void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004423 SourceLocation FunLocStart =
4424 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4425 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004426 StringRef FuncName = FD->getName();
4427
4428 SynthesizeBlockLiterals(FunLocStart, FuncName);
4429}
4430
4431static void BuildUniqueMethodName(std::string &Name,
4432 ObjCMethodDecl *MD) {
4433 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4434 Name = IFace->getName();
4435 Name += "__" + MD->getSelector().getAsString();
4436 // Convert colons to underscores.
4437 std::string::size_type loc = 0;
4438 while ((loc = Name.find(":", loc)) != std::string::npos)
4439 Name.replace(loc, 1, "_");
4440}
4441
4442void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4443 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4444 //SourceLocation FunLocStart = MD->getLocStart();
4445 SourceLocation FunLocStart = MD->getLocStart();
4446 std::string FuncName;
4447 BuildUniqueMethodName(FuncName, MD);
4448 SynthesizeBlockLiterals(FunLocStart, FuncName);
4449}
4450
4451void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4452 for (Stmt::child_range CI = S->children(); CI; ++CI)
4453 if (*CI) {
4454 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4455 GetBlockDeclRefExprs(CBE->getBody());
4456 else
4457 GetBlockDeclRefExprs(*CI);
4458 }
4459 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004460 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4461 if (DRE->refersToEnclosingLocal()) {
4462 // FIXME: Handle enums.
4463 if (!isa<FunctionDecl>(DRE->getDecl()))
4464 BlockDeclRefs.push_back(DRE);
4465 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4466 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004467 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004468 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004469
4470 return;
4471}
4472
4473void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004474 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004475 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4476 for (Stmt::child_range CI = S->children(); CI; ++CI)
4477 if (*CI) {
4478 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4479 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4480 GetInnerBlockDeclRefExprs(CBE->getBody(),
4481 InnerBlockDeclRefs,
4482 InnerContexts);
4483 }
4484 else
4485 GetInnerBlockDeclRefExprs(*CI,
4486 InnerBlockDeclRefs,
4487 InnerContexts);
4488
4489 }
4490 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004491 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4492 if (DRE->refersToEnclosingLocal()) {
4493 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4494 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4495 InnerBlockDeclRefs.push_back(DRE);
4496 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4497 if (Var->isFunctionOrMethodVarDecl())
4498 ImportedLocalExternalDecls.insert(Var);
4499 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004500 }
4501
4502 return;
4503}
4504
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004505/// convertObjCTypeToCStyleType - This routine converts such objc types
4506/// as qualified objects, and blocks to their closest c/c++ types that
4507/// it can. It returns true if input type was modified.
4508bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4509 QualType oldT = T;
4510 convertBlockPointerToFunctionPointer(T);
4511 if (T->isFunctionPointerType()) {
4512 QualType PointeeTy;
4513 if (const PointerType* PT = T->getAs<PointerType>()) {
4514 PointeeTy = PT->getPointeeType();
4515 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4516 T = convertFunctionTypeOfBlocks(FT);
4517 T = Context->getPointerType(T);
4518 }
4519 }
4520 }
4521
4522 convertToUnqualifiedObjCType(T);
4523 return T != oldT;
4524}
4525
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004526/// convertFunctionTypeOfBlocks - This routine converts a function type
4527/// whose result type may be a block pointer or whose argument type(s)
4528/// might be block pointers to an equivalent function type replacing
4529/// all block pointers to function pointers.
4530QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4531 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4532 // FTP will be null for closures that don't take arguments.
4533 // Generate a funky cast.
4534 SmallVector<QualType, 8> ArgTypes;
4535 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004536 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004537
4538 if (FTP) {
4539 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4540 E = FTP->arg_type_end(); I && (I != E); ++I) {
4541 QualType t = *I;
4542 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004543 if (convertObjCTypeToCStyleType(t))
4544 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004545 ArgTypes.push_back(t);
4546 }
4547 }
4548 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004549 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004550 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4551 else FuncType = QualType(FT, 0);
4552 return FuncType;
4553}
4554
4555Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4556 // Navigate to relevant type information.
4557 const BlockPointerType *CPT = 0;
4558
4559 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4560 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004561 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4562 CPT = MExpr->getType()->getAs<BlockPointerType>();
4563 }
4564 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4565 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4566 }
4567 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4568 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4569 else if (const ConditionalOperator *CEXPR =
4570 dyn_cast<ConditionalOperator>(BlockExp)) {
4571 Expr *LHSExp = CEXPR->getLHS();
4572 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4573 Expr *RHSExp = CEXPR->getRHS();
4574 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4575 Expr *CONDExp = CEXPR->getCond();
4576 ConditionalOperator *CondExpr =
4577 new (Context) ConditionalOperator(CONDExp,
4578 SourceLocation(), cast<Expr>(LHSStmt),
4579 SourceLocation(), cast<Expr>(RHSStmt),
4580 Exp->getType(), VK_RValue, OK_Ordinary);
4581 return CondExpr;
4582 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4583 CPT = IRE->getType()->getAs<BlockPointerType>();
4584 } else if (const PseudoObjectExpr *POE
4585 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4586 CPT = POE->getType()->castAs<BlockPointerType>();
4587 } else {
4588 assert(1 && "RewriteBlockClass: Bad type");
4589 }
4590 assert(CPT && "RewriteBlockClass: Bad type");
4591 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4592 assert(FT && "RewriteBlockClass: Bad type");
4593 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4594 // FTP will be null for closures that don't take arguments.
4595
4596 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4597 SourceLocation(), SourceLocation(),
4598 &Context->Idents.get("__block_impl"));
4599 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4600
4601 // Generate a funky cast.
4602 SmallVector<QualType, 8> ArgTypes;
4603
4604 // Push the block argument type.
4605 ArgTypes.push_back(PtrBlock);
4606 if (FTP) {
4607 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4608 E = FTP->arg_type_end(); I && (I != E); ++I) {
4609 QualType t = *I;
4610 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4611 if (!convertBlockPointerToFunctionPointer(t))
4612 convertToUnqualifiedObjCType(t);
4613 ArgTypes.push_back(t);
4614 }
4615 }
4616 // Now do the pointer to function cast.
4617 QualType PtrToFuncCastType
4618 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4619
4620 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4621
4622 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4623 CK_BitCast,
4624 const_cast<Expr*>(BlockExp));
4625 // Don't forget the parens to enforce the proper binding.
4626 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4627 BlkCast);
4628 //PE->dump();
4629
4630 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4631 SourceLocation(),
4632 &Context->Idents.get("FuncPtr"),
4633 Context->VoidPtrTy, 0,
4634 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004635 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004636 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4637 FD->getType(), VK_LValue,
4638 OK_Ordinary);
4639
4640
4641 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4642 CK_BitCast, ME);
4643 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4644
4645 SmallVector<Expr*, 8> BlkExprs;
4646 // Add the implicit argument.
4647 BlkExprs.push_back(BlkCast);
4648 // Add the user arguments.
4649 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4650 E = Exp->arg_end(); I != E; ++I) {
4651 BlkExprs.push_back(*I);
4652 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004653 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004654 Exp->getType(), VK_RValue,
4655 SourceLocation());
4656 return CE;
4657}
4658
4659// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004660// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004661// For example:
4662//
4663// int main() {
4664// __block Foo *f;
4665// __block int i;
4666//
4667// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004668// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004669// i = 77;
4670// };
4671//}
John McCallf4b88a42012-03-10 09:33:50 +00004672Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004673 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4674 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004675 ValueDecl *VD = DeclRefExp->getDecl();
4676 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004677
4678 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4679 SourceLocation(),
4680 &Context->Idents.get("__forwarding"),
4681 Context->VoidPtrTy, 0,
4682 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004683 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004684 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4685 FD, SourceLocation(),
4686 FD->getType(), VK_LValue,
4687 OK_Ordinary);
4688
4689 StringRef Name = VD->getName();
4690 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4691 &Context->Idents.get(Name),
4692 Context->VoidPtrTy, 0,
4693 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004694 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004695 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4696 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4697
4698
4699
4700 // Need parens to enforce precedence.
4701 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4702 DeclRefExp->getExprLoc(),
4703 ME);
4704 ReplaceStmt(DeclRefExp, PE);
4705 return PE;
4706}
4707
4708// Rewrites the imported local variable V with external storage
4709// (static, extern, etc.) as *V
4710//
4711Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4712 ValueDecl *VD = DRE->getDecl();
4713 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4714 if (!ImportedLocalExternalDecls.count(Var))
4715 return DRE;
4716 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4717 VK_LValue, OK_Ordinary,
4718 DRE->getLocation());
4719 // Need parens to enforce precedence.
4720 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4721 Exp);
4722 ReplaceStmt(DRE, PE);
4723 return PE;
4724}
4725
4726void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4727 SourceLocation LocStart = CE->getLParenLoc();
4728 SourceLocation LocEnd = CE->getRParenLoc();
4729
4730 // Need to avoid trying to rewrite synthesized casts.
4731 if (LocStart.isInvalid())
4732 return;
4733 // Need to avoid trying to rewrite casts contained in macros.
4734 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4735 return;
4736
4737 const char *startBuf = SM->getCharacterData(LocStart);
4738 const char *endBuf = SM->getCharacterData(LocEnd);
4739 QualType QT = CE->getType();
4740 const Type* TypePtr = QT->getAs<Type>();
4741 if (isa<TypeOfExprType>(TypePtr)) {
4742 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4743 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4744 std::string TypeAsString = "(";
4745 RewriteBlockPointerType(TypeAsString, QT);
4746 TypeAsString += ")";
4747 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4748 return;
4749 }
4750 // advance the location to startArgList.
4751 const char *argPtr = startBuf;
4752
4753 while (*argPtr++ && (argPtr < endBuf)) {
4754 switch (*argPtr) {
4755 case '^':
4756 // Replace the '^' with '*'.
4757 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4758 ReplaceText(LocStart, 1, "*");
4759 break;
4760 }
4761 }
4762 return;
4763}
4764
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004765void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4766 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004767 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4768 CastKind != CK_AnyPointerToBlockPointerCast)
4769 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004770
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004771 QualType QT = IC->getType();
4772 (void)convertBlockPointerToFunctionPointer(QT);
4773 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4774 std::string Str = "(";
4775 Str += TypeString;
4776 Str += ")";
4777 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4778
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004779 return;
4780}
4781
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004782void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4783 SourceLocation DeclLoc = FD->getLocation();
4784 unsigned parenCount = 0;
4785
4786 // We have 1 or more arguments that have closure pointers.
4787 const char *startBuf = SM->getCharacterData(DeclLoc);
4788 const char *startArgList = strchr(startBuf, '(');
4789
4790 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4791
4792 parenCount++;
4793 // advance the location to startArgList.
4794 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4795 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4796
4797 const char *argPtr = startArgList;
4798
4799 while (*argPtr++ && parenCount) {
4800 switch (*argPtr) {
4801 case '^':
4802 // Replace the '^' with '*'.
4803 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4804 ReplaceText(DeclLoc, 1, "*");
4805 break;
4806 case '(':
4807 parenCount++;
4808 break;
4809 case ')':
4810 parenCount--;
4811 break;
4812 }
4813 }
4814 return;
4815}
4816
4817bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4818 const FunctionProtoType *FTP;
4819 const PointerType *PT = QT->getAs<PointerType>();
4820 if (PT) {
4821 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4822 } else {
4823 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4824 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4825 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4826 }
4827 if (FTP) {
4828 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4829 E = FTP->arg_type_end(); I != E; ++I)
4830 if (isTopLevelBlockPointerType(*I))
4831 return true;
4832 }
4833 return false;
4834}
4835
4836bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4837 const FunctionProtoType *FTP;
4838 const PointerType *PT = QT->getAs<PointerType>();
4839 if (PT) {
4840 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4841 } else {
4842 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4843 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4844 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4845 }
4846 if (FTP) {
4847 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4848 E = FTP->arg_type_end(); I != E; ++I) {
4849 if ((*I)->isObjCQualifiedIdType())
4850 return true;
4851 if ((*I)->isObjCObjectPointerType() &&
4852 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4853 return true;
4854 }
4855
4856 }
4857 return false;
4858}
4859
4860void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4861 const char *&RParen) {
4862 const char *argPtr = strchr(Name, '(');
4863 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4864
4865 LParen = argPtr; // output the start.
4866 argPtr++; // skip past the left paren.
4867 unsigned parenCount = 1;
4868
4869 while (*argPtr && parenCount) {
4870 switch (*argPtr) {
4871 case '(': parenCount++; break;
4872 case ')': parenCount--; break;
4873 default: break;
4874 }
4875 if (parenCount) argPtr++;
4876 }
4877 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4878 RParen = argPtr; // output the end
4879}
4880
4881void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4882 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4883 RewriteBlockPointerFunctionArgs(FD);
4884 return;
4885 }
4886 // Handle Variables and Typedefs.
4887 SourceLocation DeclLoc = ND->getLocation();
4888 QualType DeclT;
4889 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4890 DeclT = VD->getType();
4891 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4892 DeclT = TDD->getUnderlyingType();
4893 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4894 DeclT = FD->getType();
4895 else
4896 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4897
4898 const char *startBuf = SM->getCharacterData(DeclLoc);
4899 const char *endBuf = startBuf;
4900 // scan backward (from the decl location) for the end of the previous decl.
4901 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4902 startBuf--;
4903 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4904 std::string buf;
4905 unsigned OrigLength=0;
4906 // *startBuf != '^' if we are dealing with a pointer to function that
4907 // may take block argument types (which will be handled below).
4908 if (*startBuf == '^') {
4909 // Replace the '^' with '*', computing a negative offset.
4910 buf = '*';
4911 startBuf++;
4912 OrigLength++;
4913 }
4914 while (*startBuf != ')') {
4915 buf += *startBuf;
4916 startBuf++;
4917 OrigLength++;
4918 }
4919 buf += ')';
4920 OrigLength++;
4921
4922 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4923 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4924 // Replace the '^' with '*' for arguments.
4925 // Replace id<P> with id/*<>*/
4926 DeclLoc = ND->getLocation();
4927 startBuf = SM->getCharacterData(DeclLoc);
4928 const char *argListBegin, *argListEnd;
4929 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4930 while (argListBegin < argListEnd) {
4931 if (*argListBegin == '^')
4932 buf += '*';
4933 else if (*argListBegin == '<') {
4934 buf += "/*";
4935 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004936 OrigLength++;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004937 while (*argListBegin != '>') {
4938 buf += *argListBegin++;
4939 OrigLength++;
4940 }
4941 buf += *argListBegin;
4942 buf += "*/";
4943 }
4944 else
4945 buf += *argListBegin;
4946 argListBegin++;
4947 OrigLength++;
4948 }
4949 buf += ')';
4950 OrigLength++;
4951 }
4952 ReplaceText(Start, OrigLength, buf);
4953
4954 return;
4955}
4956
4957
4958/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4959/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4960/// struct Block_byref_id_object *src) {
4961/// _Block_object_assign (&_dest->object, _src->object,
4962/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4963/// [|BLOCK_FIELD_IS_WEAK]) // object
4964/// _Block_object_assign(&_dest->object, _src->object,
4965/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4966/// [|BLOCK_FIELD_IS_WEAK]) // block
4967/// }
4968/// And:
4969/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4970/// _Block_object_dispose(_src->object,
4971/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4972/// [|BLOCK_FIELD_IS_WEAK]) // object
4973/// _Block_object_dispose(_src->object,
4974/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4975/// [|BLOCK_FIELD_IS_WEAK]) // block
4976/// }
4977
4978std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4979 int flag) {
4980 std::string S;
4981 if (CopyDestroyCache.count(flag))
4982 return S;
4983 CopyDestroyCache.insert(flag);
4984 S = "static void __Block_byref_id_object_copy_";
4985 S += utostr(flag);
4986 S += "(void *dst, void *src) {\n";
4987
4988 // offset into the object pointer is computed as:
4989 // void * + void* + int + int + void* + void *
4990 unsigned IntSize =
4991 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4992 unsigned VoidPtrSize =
4993 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4994
4995 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4996 S += " _Block_object_assign((char*)dst + ";
4997 S += utostr(offset);
4998 S += ", *(void * *) ((char*)src + ";
4999 S += utostr(offset);
5000 S += "), ";
5001 S += utostr(flag);
5002 S += ");\n}\n";
5003
5004 S += "static void __Block_byref_id_object_dispose_";
5005 S += utostr(flag);
5006 S += "(void *src) {\n";
5007 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5008 S += utostr(offset);
5009 S += "), ";
5010 S += utostr(flag);
5011 S += ");\n}\n";
5012 return S;
5013}
5014
5015/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5016/// the declaration into:
5017/// struct __Block_byref_ND {
5018/// void *__isa; // NULL for everything except __weak pointers
5019/// struct __Block_byref_ND *__forwarding;
5020/// int32_t __flags;
5021/// int32_t __size;
5022/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5023/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5024/// typex ND;
5025/// };
5026///
5027/// It then replaces declaration of ND variable with:
5028/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5029/// __size=sizeof(struct __Block_byref_ND),
5030/// ND=initializer-if-any};
5031///
5032///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005033void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5034 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005035 int flag = 0;
5036 int isa = 0;
5037 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5038 if (DeclLoc.isInvalid())
5039 // If type location is missing, it is because of missing type (a warning).
5040 // Use variable's location which is good for this case.
5041 DeclLoc = ND->getLocation();
5042 const char *startBuf = SM->getCharacterData(DeclLoc);
5043 SourceLocation X = ND->getLocEnd();
5044 X = SM->getExpansionLoc(X);
5045 const char *endBuf = SM->getCharacterData(X);
5046 std::string Name(ND->getNameAsString());
5047 std::string ByrefType;
5048 RewriteByRefString(ByrefType, Name, ND, true);
5049 ByrefType += " {\n";
5050 ByrefType += " void *__isa;\n";
5051 RewriteByRefString(ByrefType, Name, ND);
5052 ByrefType += " *__forwarding;\n";
5053 ByrefType += " int __flags;\n";
5054 ByrefType += " int __size;\n";
5055 // Add void *__Block_byref_id_object_copy;
5056 // void *__Block_byref_id_object_dispose; if needed.
5057 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00005058 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005059 if (HasCopyAndDispose) {
5060 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5061 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5062 }
5063
5064 QualType T = Ty;
5065 (void)convertBlockPointerToFunctionPointer(T);
5066 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5067
5068 ByrefType += " " + Name + ";\n";
5069 ByrefType += "};\n";
5070 // Insert this type in global scope. It is needed by helper function.
5071 SourceLocation FunLocStart;
5072 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00005073 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005074 else {
5075 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5076 FunLocStart = CurMethodDef->getLocStart();
5077 }
5078 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005079
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005080 if (Ty.isObjCGCWeak()) {
5081 flag |= BLOCK_FIELD_IS_WEAK;
5082 isa = 1;
5083 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005084 if (HasCopyAndDispose) {
5085 flag = BLOCK_BYREF_CALLER;
5086 QualType Ty = ND->getType();
5087 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5088 if (Ty->isBlockPointerType())
5089 flag |= BLOCK_FIELD_IS_BLOCK;
5090 else
5091 flag |= BLOCK_FIELD_IS_OBJECT;
5092 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5093 if (!HF.empty())
5094 InsertText(FunLocStart, HF);
5095 }
5096
5097 // struct __Block_byref_ND ND =
5098 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5099 // initializer-if-any};
5100 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00005101 // FIXME. rewriter does not support __block c++ objects which
5102 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00005103 if (hasInit)
5104 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5105 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5106 if (CXXDecl && CXXDecl->isDefaultConstructor())
5107 hasInit = false;
5108 }
5109
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005110 unsigned flags = 0;
5111 if (HasCopyAndDispose)
5112 flags |= BLOCK_HAS_COPY_DISPOSE;
5113 Name = ND->getNameAsString();
5114 ByrefType.clear();
5115 RewriteByRefString(ByrefType, Name, ND);
5116 std::string ForwardingCastType("(");
5117 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005118 ByrefType += " " + Name + " = {(void*)";
5119 ByrefType += utostr(isa);
5120 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5121 ByrefType += utostr(flags);
5122 ByrefType += ", ";
5123 ByrefType += "sizeof(";
5124 RewriteByRefString(ByrefType, Name, ND);
5125 ByrefType += ")";
5126 if (HasCopyAndDispose) {
5127 ByrefType += ", __Block_byref_id_object_copy_";
5128 ByrefType += utostr(flag);
5129 ByrefType += ", __Block_byref_id_object_dispose_";
5130 ByrefType += utostr(flag);
5131 }
5132
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005133 if (!firstDecl) {
5134 // In multiple __block declarations, and for all but 1st declaration,
5135 // find location of the separating comma. This would be start location
5136 // where new text is to be inserted.
5137 DeclLoc = ND->getLocation();
5138 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5139 const char *commaBuf = startDeclBuf;
5140 while (*commaBuf != ',')
5141 commaBuf--;
5142 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5143 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5144 startBuf = commaBuf;
5145 }
5146
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005147 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005148 ByrefType += "};\n";
5149 unsigned nameSize = Name.size();
5150 // for block or function pointer declaration. Name is aleady
5151 // part of the declaration.
5152 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5153 nameSize = 1;
5154 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5155 }
5156 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005157 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005158 SourceLocation startLoc;
5159 Expr *E = ND->getInit();
5160 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5161 startLoc = ECE->getLParenLoc();
5162 else
5163 startLoc = E->getLocStart();
5164 startLoc = SM->getExpansionLoc(startLoc);
5165 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005166 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005167
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005168 const char separator = lastDecl ? ';' : ',';
5169 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5170 const char *separatorBuf = strchr(startInitializerBuf, separator);
5171 assert((*separatorBuf == separator) &&
5172 "RewriteByRefVar: can't find ';' or ','");
5173 SourceLocation separatorLoc =
5174 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5175
5176 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005177 }
5178 return;
5179}
5180
5181void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5182 // Add initializers for any closure decl refs.
5183 GetBlockDeclRefExprs(Exp->getBody());
5184 if (BlockDeclRefs.size()) {
5185 // Unique all "by copy" declarations.
5186 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005187 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005188 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5189 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5190 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5191 }
5192 }
5193 // Unique all "by ref" declarations.
5194 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005195 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005196 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5197 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5198 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5199 }
5200 }
5201 // Find any imported blocks...they will need special attention.
5202 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005203 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005204 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5205 BlockDeclRefs[i]->getType()->isBlockPointerType())
5206 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5207 }
5208}
5209
5210FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5211 IdentifierInfo *ID = &Context->Idents.get(name);
5212 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5213 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5214 SourceLocation(), ID, FType, 0, SC_Extern,
5215 SC_None, false, false);
5216}
5217
5218Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005219 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005220
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005221 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005222
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005223 Blocks.push_back(Exp);
5224
5225 CollectBlockDeclRefInfo(Exp);
5226
5227 // Add inner imported variables now used in current block.
5228 int countOfInnerDecls = 0;
5229 if (!InnerBlockDeclRefs.empty()) {
5230 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005231 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005232 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005233 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005234 // We need to save the copied-in variables in nested
5235 // blocks because it is needed at the end for some of the API generations.
5236 // See SynthesizeBlockLiterals routine.
5237 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5238 BlockDeclRefs.push_back(Exp);
5239 BlockByCopyDeclsPtrSet.insert(VD);
5240 BlockByCopyDecls.push_back(VD);
5241 }
John McCallf4b88a42012-03-10 09:33:50 +00005242 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005243 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5244 BlockDeclRefs.push_back(Exp);
5245 BlockByRefDeclsPtrSet.insert(VD);
5246 BlockByRefDecls.push_back(VD);
5247 }
5248 }
5249 // Find any imported blocks...they will need special attention.
5250 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005251 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005252 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5253 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5254 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5255 }
5256 InnerDeclRefsCount.push_back(countOfInnerDecls);
5257
5258 std::string FuncName;
5259
5260 if (CurFunctionDef)
5261 FuncName = CurFunctionDef->getNameAsString();
5262 else if (CurMethodDef)
5263 BuildUniqueMethodName(FuncName, CurMethodDef);
5264 else if (GlobalVarDecl)
5265 FuncName = std::string(GlobalVarDecl->getNameAsString());
5266
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005267 bool GlobalBlockExpr =
5268 block->getDeclContext()->getRedeclContext()->isFileContext();
5269
5270 if (GlobalBlockExpr && !GlobalVarDecl) {
5271 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5272 GlobalBlockExpr = false;
5273 }
5274
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005275 std::string BlockNumber = utostr(Blocks.size()-1);
5276
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005277 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5278
5279 // Get a pointer to the function type so we can cast appropriately.
5280 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5281 QualType FType = Context->getPointerType(BFT);
5282
5283 FunctionDecl *FD;
5284 Expr *NewRep;
5285
5286 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005287 std::string Tag;
5288
5289 if (GlobalBlockExpr)
5290 Tag = "__global_";
5291 else
5292 Tag = "__";
5293 Tag += FuncName + "_block_impl_" + BlockNumber;
5294
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005295 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005296 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005297 SourceLocation());
5298
5299 SmallVector<Expr*, 4> InitExprs;
5300
5301 // Initialize the block function.
5302 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005303 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5304 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005305 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5306 CK_BitCast, Arg);
5307 InitExprs.push_back(castExpr);
5308
5309 // Initialize the block descriptor.
5310 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5311
5312 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5313 SourceLocation(), SourceLocation(),
5314 &Context->Idents.get(DescData.c_str()),
5315 Context->VoidPtrTy, 0,
5316 SC_Static, SC_None);
5317 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005318 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005319 Context->VoidPtrTy,
5320 VK_LValue,
5321 SourceLocation()),
5322 UO_AddrOf,
5323 Context->getPointerType(Context->VoidPtrTy),
5324 VK_RValue, OK_Ordinary,
5325 SourceLocation());
5326 InitExprs.push_back(DescRefExpr);
5327
5328 // Add initializers for any closure decl refs.
5329 if (BlockDeclRefs.size()) {
5330 Expr *Exp;
5331 // Output all "by copy" declarations.
5332 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5333 E = BlockByCopyDecls.end(); I != E; ++I) {
5334 if (isObjCType((*I)->getType())) {
5335 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5336 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005337 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5338 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005339 if (HasLocalVariableExternalStorage(*I)) {
5340 QualType QT = (*I)->getType();
5341 QT = Context->getPointerType(QT);
5342 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5343 OK_Ordinary, SourceLocation());
5344 }
5345 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5346 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005347 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5348 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005349 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5350 CK_BitCast, Arg);
5351 } else {
5352 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005353 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5354 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005355 if (HasLocalVariableExternalStorage(*I)) {
5356 QualType QT = (*I)->getType();
5357 QT = Context->getPointerType(QT);
5358 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5359 OK_Ordinary, SourceLocation());
5360 }
5361
5362 }
5363 InitExprs.push_back(Exp);
5364 }
5365 // Output all "by ref" declarations.
5366 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5367 E = BlockByRefDecls.end(); I != E; ++I) {
5368 ValueDecl *ND = (*I);
5369 std::string Name(ND->getNameAsString());
5370 std::string RecName;
5371 RewriteByRefString(RecName, Name, ND, true);
5372 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5373 + sizeof("struct"));
5374 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5375 SourceLocation(), SourceLocation(),
5376 II);
5377 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5378 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5379
5380 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005381 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005382 SourceLocation());
5383 bool isNestedCapturedVar = false;
5384 if (block)
5385 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5386 ce = block->capture_end(); ci != ce; ++ci) {
5387 const VarDecl *variable = ci->getVariable();
5388 if (variable == ND && ci->isNested()) {
5389 assert (ci->isByRef() &&
5390 "SynthBlockInitExpr - captured block variable is not byref");
5391 isNestedCapturedVar = true;
5392 break;
5393 }
5394 }
5395 // captured nested byref variable has its address passed. Do not take
5396 // its address again.
5397 if (!isNestedCapturedVar)
5398 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5399 Context->getPointerType(Exp->getType()),
5400 VK_RValue, OK_Ordinary, SourceLocation());
5401 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5402 InitExprs.push_back(Exp);
5403 }
5404 }
5405 if (ImportedBlockDecls.size()) {
5406 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5407 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5408 unsigned IntSize =
5409 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5410 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5411 Context->IntTy, SourceLocation());
5412 InitExprs.push_back(FlagExp);
5413 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005414 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005415 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005416
5417 if (GlobalBlockExpr) {
5418 assert (GlobalConstructionExp == 0 &&
5419 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5420 GlobalConstructionExp = NewRep;
5421 NewRep = DRE;
5422 }
5423
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005424 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5425 Context->getPointerType(NewRep->getType()),
5426 VK_RValue, OK_Ordinary, SourceLocation());
5427 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5428 NewRep);
5429 BlockDeclRefs.clear();
5430 BlockByRefDecls.clear();
5431 BlockByRefDeclsPtrSet.clear();
5432 BlockByCopyDecls.clear();
5433 BlockByCopyDeclsPtrSet.clear();
5434 ImportedBlockDecls.clear();
5435 return NewRep;
5436}
5437
5438bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5439 if (const ObjCForCollectionStmt * CS =
5440 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5441 return CS->getElement() == DS;
5442 return false;
5443}
5444
5445//===----------------------------------------------------------------------===//
5446// Function Body / Expression rewriting
5447//===----------------------------------------------------------------------===//
5448
5449Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5450 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5451 isa<DoStmt>(S) || isa<ForStmt>(S))
5452 Stmts.push_back(S);
5453 else if (isa<ObjCForCollectionStmt>(S)) {
5454 Stmts.push_back(S);
5455 ObjCBcLabelNo.push_back(++BcLabelCount);
5456 }
5457
5458 // Pseudo-object operations and ivar references need special
5459 // treatment because we're going to recursively rewrite them.
5460 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5461 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5462 return RewritePropertyOrImplicitSetter(PseudoOp);
5463 } else {
5464 return RewritePropertyOrImplicitGetter(PseudoOp);
5465 }
5466 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5467 return RewriteObjCIvarRefExpr(IvarRefExpr);
5468 }
5469
5470 SourceRange OrigStmtRange = S->getSourceRange();
5471
5472 // Perform a bottom up rewrite of all children.
5473 for (Stmt::child_range CI = S->children(); CI; ++CI)
5474 if (*CI) {
5475 Stmt *childStmt = (*CI);
5476 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5477 if (newStmt) {
5478 *CI = newStmt;
5479 }
5480 }
5481
5482 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005483 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005484 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5485 InnerContexts.insert(BE->getBlockDecl());
5486 ImportedLocalExternalDecls.clear();
5487 GetInnerBlockDeclRefExprs(BE->getBody(),
5488 InnerBlockDeclRefs, InnerContexts);
5489 // Rewrite the block body in place.
5490 Stmt *SaveCurrentBody = CurrentBody;
5491 CurrentBody = BE->getBody();
5492 PropParentMap = 0;
5493 // block literal on rhs of a property-dot-sytax assignment
5494 // must be replaced by its synthesize ast so getRewrittenText
5495 // works as expected. In this case, what actually ends up on RHS
5496 // is the blockTranscribed which is the helper function for the
5497 // block literal; as in: self.c = ^() {[ace ARR];};
5498 bool saveDisableReplaceStmt = DisableReplaceStmt;
5499 DisableReplaceStmt = false;
5500 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5501 DisableReplaceStmt = saveDisableReplaceStmt;
5502 CurrentBody = SaveCurrentBody;
5503 PropParentMap = 0;
5504 ImportedLocalExternalDecls.clear();
5505 // Now we snarf the rewritten text and stash it away for later use.
5506 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5507 RewrittenBlockExprs[BE] = Str;
5508
5509 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5510
5511 //blockTranscribed->dump();
5512 ReplaceStmt(S, blockTranscribed);
5513 return blockTranscribed;
5514 }
5515 // Handle specific things.
5516 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5517 return RewriteAtEncode(AtEncode);
5518
5519 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5520 return RewriteAtSelector(AtSelector);
5521
5522 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5523 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005524
5525 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5526 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005527
Patrick Beardeb382ec2012-04-19 00:25:12 +00005528 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5529 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005530
5531 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5532 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005533
5534 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5535 dyn_cast<ObjCDictionaryLiteral>(S))
5536 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005537
5538 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5539#if 0
5540 // Before we rewrite it, put the original message expression in a comment.
5541 SourceLocation startLoc = MessExpr->getLocStart();
5542 SourceLocation endLoc = MessExpr->getLocEnd();
5543
5544 const char *startBuf = SM->getCharacterData(startLoc);
5545 const char *endBuf = SM->getCharacterData(endLoc);
5546
5547 std::string messString;
5548 messString += "// ";
5549 messString.append(startBuf, endBuf-startBuf+1);
5550 messString += "\n";
5551
5552 // FIXME: Missing definition of
5553 // InsertText(clang::SourceLocation, char const*, unsigned int).
5554 // InsertText(startLoc, messString.c_str(), messString.size());
5555 // Tried this, but it didn't work either...
5556 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5557#endif
5558 return RewriteMessageExpr(MessExpr);
5559 }
5560
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005561 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5562 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5563 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5564 }
5565
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005566 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5567 return RewriteObjCTryStmt(StmtTry);
5568
5569 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5570 return RewriteObjCSynchronizedStmt(StmtTry);
5571
5572 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5573 return RewriteObjCThrowStmt(StmtThrow);
5574
5575 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5576 return RewriteObjCProtocolExpr(ProtocolExp);
5577
5578 if (ObjCForCollectionStmt *StmtForCollection =
5579 dyn_cast<ObjCForCollectionStmt>(S))
5580 return RewriteObjCForCollectionStmt(StmtForCollection,
5581 OrigStmtRange.getEnd());
5582 if (BreakStmt *StmtBreakStmt =
5583 dyn_cast<BreakStmt>(S))
5584 return RewriteBreakStmt(StmtBreakStmt);
5585 if (ContinueStmt *StmtContinueStmt =
5586 dyn_cast<ContinueStmt>(S))
5587 return RewriteContinueStmt(StmtContinueStmt);
5588
5589 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5590 // and cast exprs.
5591 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5592 // FIXME: What we're doing here is modifying the type-specifier that
5593 // precedes the first Decl. In the future the DeclGroup should have
5594 // a separate type-specifier that we can rewrite.
5595 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5596 // the context of an ObjCForCollectionStmt. For example:
5597 // NSArray *someArray;
5598 // for (id <FooProtocol> index in someArray) ;
5599 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5600 // and it depends on the original text locations/positions.
5601 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5602 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5603
5604 // Blocks rewrite rules.
5605 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5606 DI != DE; ++DI) {
5607 Decl *SD = *DI;
5608 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5609 if (isTopLevelBlockPointerType(ND->getType()))
5610 RewriteBlockPointerDecl(ND);
5611 else if (ND->getType()->isFunctionPointerType())
5612 CheckFunctionPointerDecl(ND->getType(), ND);
5613 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5614 if (VD->hasAttr<BlocksAttr>()) {
5615 static unsigned uniqueByrefDeclCount = 0;
5616 assert(!BlockByRefDeclNo.count(ND) &&
5617 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5618 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005619 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005620 }
5621 else
5622 RewriteTypeOfDecl(VD);
5623 }
5624 }
5625 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5626 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5627 RewriteBlockPointerDecl(TD);
5628 else if (TD->getUnderlyingType()->isFunctionPointerType())
5629 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5630 }
5631 }
5632 }
5633
5634 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5635 RewriteObjCQualifiedInterfaceTypes(CE);
5636
5637 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5638 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5639 assert(!Stmts.empty() && "Statement stack is empty");
5640 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5641 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5642 && "Statement stack mismatch");
5643 Stmts.pop_back();
5644 }
5645 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005646 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5647 ValueDecl *VD = DRE->getDecl();
5648 if (VD->hasAttr<BlocksAttr>())
5649 return RewriteBlockDeclRefExpr(DRE);
5650 if (HasLocalVariableExternalStorage(VD))
5651 return RewriteLocalVariableExternalStorage(DRE);
5652 }
5653
5654 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5655 if (CE->getCallee()->getType()->isBlockPointerType()) {
5656 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5657 ReplaceStmt(S, BlockCall);
5658 return BlockCall;
5659 }
5660 }
5661 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5662 RewriteCastExpr(CE);
5663 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005664 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5665 RewriteImplicitCastObjCExpr(ICE);
5666 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005667#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005668
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005669 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5670 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5671 ICE->getSubExpr(),
5672 SourceLocation());
5673 // Get the new text.
5674 std::string SStr;
5675 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00005676 Replacement->printPretty(Buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005677 const std::string &Str = Buf.str();
5678
5679 printf("CAST = %s\n", &Str[0]);
5680 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5681 delete S;
5682 return Replacement;
5683 }
5684#endif
5685 // Return this stmt unmodified.
5686 return S;
5687}
5688
5689void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5690 for (RecordDecl::field_iterator i = RD->field_begin(),
5691 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00005692 FieldDecl *FD = *i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005693 if (isTopLevelBlockPointerType(FD->getType()))
5694 RewriteBlockPointerDecl(FD);
5695 if (FD->getType()->isObjCQualifiedIdType() ||
5696 FD->getType()->isObjCQualifiedInterfaceType())
5697 RewriteObjCQualifiedInterfaceTypes(FD);
5698 }
5699}
5700
5701/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5702/// main file of the input.
5703void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5704 switch (D->getKind()) {
5705 case Decl::Function: {
5706 FunctionDecl *FD = cast<FunctionDecl>(D);
5707 if (FD->isOverloadedOperator())
5708 return;
5709
5710 // Since function prototypes don't have ParmDecl's, we check the function
5711 // prototype. This enables us to rewrite function declarations and
5712 // definitions using the same code.
5713 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5714
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005715 if (!FD->isThisDeclarationADefinition())
5716 break;
5717
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005718 // FIXME: If this should support Obj-C++, support CXXTryStmt
5719 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5720 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005721 CurrentBody = Body;
5722 Body =
5723 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5724 FD->setBody(Body);
5725 CurrentBody = 0;
5726 if (PropParentMap) {
5727 delete PropParentMap;
5728 PropParentMap = 0;
5729 }
5730 // This synthesizes and inserts the block "impl" struct, invoke function,
5731 // and any copy/dispose helper functions.
5732 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005733 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005734 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005735 }
5736 break;
5737 }
5738 case Decl::ObjCMethod: {
5739 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5740 if (CompoundStmt *Body = MD->getCompoundBody()) {
5741 CurMethodDef = MD;
5742 CurrentBody = Body;
5743 Body =
5744 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5745 MD->setBody(Body);
5746 CurrentBody = 0;
5747 if (PropParentMap) {
5748 delete PropParentMap;
5749 PropParentMap = 0;
5750 }
5751 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005752 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005753 CurMethodDef = 0;
5754 }
5755 break;
5756 }
5757 case Decl::ObjCImplementation: {
5758 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5759 ClassImplementation.push_back(CI);
5760 break;
5761 }
5762 case Decl::ObjCCategoryImpl: {
5763 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5764 CategoryImplementation.push_back(CI);
5765 break;
5766 }
5767 case Decl::Var: {
5768 VarDecl *VD = cast<VarDecl>(D);
5769 RewriteObjCQualifiedInterfaceTypes(VD);
5770 if (isTopLevelBlockPointerType(VD->getType()))
5771 RewriteBlockPointerDecl(VD);
5772 else if (VD->getType()->isFunctionPointerType()) {
5773 CheckFunctionPointerDecl(VD->getType(), VD);
5774 if (VD->getInit()) {
5775 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5776 RewriteCastExpr(CE);
5777 }
5778 }
5779 } else if (VD->getType()->isRecordType()) {
5780 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5781 if (RD->isCompleteDefinition())
5782 RewriteRecordBody(RD);
5783 }
5784 if (VD->getInit()) {
5785 GlobalVarDecl = VD;
5786 CurrentBody = VD->getInit();
5787 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5788 CurrentBody = 0;
5789 if (PropParentMap) {
5790 delete PropParentMap;
5791 PropParentMap = 0;
5792 }
5793 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5794 GlobalVarDecl = 0;
5795
5796 // This is needed for blocks.
5797 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5798 RewriteCastExpr(CE);
5799 }
5800 }
5801 break;
5802 }
5803 case Decl::TypeAlias:
5804 case Decl::Typedef: {
5805 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5806 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5807 RewriteBlockPointerDecl(TD);
5808 else if (TD->getUnderlyingType()->isFunctionPointerType())
5809 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5810 }
5811 break;
5812 }
5813 case Decl::CXXRecord:
5814 case Decl::Record: {
5815 RecordDecl *RD = cast<RecordDecl>(D);
5816 if (RD->isCompleteDefinition())
5817 RewriteRecordBody(RD);
5818 break;
5819 }
5820 default:
5821 break;
5822 }
5823 // Nothing yet.
5824}
5825
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005826/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5827/// protocol reference symbols in the for of:
5828/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5829static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5830 ObjCProtocolDecl *PDecl,
5831 std::string &Result) {
5832 // Also output .objc_protorefs$B section and its meta-data.
5833 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00005834 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005835 Result += "struct _protocol_t *";
5836 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5837 Result += PDecl->getNameAsString();
5838 Result += " = &";
5839 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5840 Result += ";\n";
5841}
5842
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005843void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5844 if (Diags.hasErrorOccurred())
5845 return;
5846
5847 RewriteInclude();
5848
5849 // Here's a great place to add any extra declarations that may be needed.
5850 // Write out meta data for each @protocol(<expr>).
5851 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005852 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005853 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005854 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5855 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005856
5857 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00005858
5859 if (ClassImplementation.size() || CategoryImplementation.size())
5860 RewriteImplementations();
5861
Fariborz Jahanian57317782012-02-21 23:58:41 +00005862 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5863 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5864 // Write struct declaration for the class matching its ivar declarations.
5865 // Note that for modern abi, this is postponed until the end of TU
5866 // because class extensions and the implementation might declare their own
5867 // private ivars.
5868 RewriteInterfaceDecl(CDecl);
5869 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005870
5871 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5872 // we are done.
5873 if (const RewriteBuffer *RewriteBuf =
5874 Rewrite.getRewriteBufferFor(MainFileID)) {
5875 //printf("Changed:\n");
5876 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5877 } else {
5878 llvm::errs() << "No changes\n";
5879 }
5880
5881 if (ClassImplementation.size() || CategoryImplementation.size() ||
5882 ProtocolExprDecls.size()) {
5883 // Rewrite Objective-c meta data*
5884 std::string ResultStr;
5885 RewriteMetaDataIntoBuffer(ResultStr);
5886 // Emit metadata.
5887 *OutFile << ResultStr;
5888 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005889 // Emit ImageInfo;
5890 {
5891 std::string ResultStr;
5892 WriteImageInfo(ResultStr);
5893 *OutFile << ResultStr;
5894 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005895 OutFile->flush();
5896}
5897
5898void RewriteModernObjC::Initialize(ASTContext &context) {
5899 InitializeCommon(context);
5900
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005901 Preamble += "#ifndef __OBJC2__\n";
5902 Preamble += "#define __OBJC2__\n";
5903 Preamble += "#endif\n";
5904
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005905 // declaring objc_selector outside the parameter list removes a silly
5906 // scope related warning...
5907 if (IsHeader)
5908 Preamble = "#pragma once\n";
5909 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005910 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5911 Preamble += "\n\tstruct objc_object *superClass; ";
5912 // Add a constructor for creating temporary objects.
5913 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5914 Preamble += ": object(o), superClass(s) {} ";
5915 Preamble += "\n};\n";
5916
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005917 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005918 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005919 // These are currently generated.
5920 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005921 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005922 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005923 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5924 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005925 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005926 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005927 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5928 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005929 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005930
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005931 // These need be generated for performance. Currently they are not,
5932 // using API calls instead.
5933 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5934 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5935 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5936
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005937 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005938 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5939 Preamble += "typedef struct objc_object Protocol;\n";
5940 Preamble += "#define _REWRITER_typedef_Protocol\n";
5941 Preamble += "#endif\n";
5942 if (LangOpts.MicrosoftExt) {
5943 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5944 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005945 }
5946 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005947 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005948
5949 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5950 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5951 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5952 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5953 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5954
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005955 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005956 Preamble += "(const char *);\n";
5957 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5958 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005959 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005960 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005961 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005962 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00005963 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5964 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005965 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5966 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5967 Preamble += "struct __objcFastEnumerationState {\n\t";
5968 Preamble += "unsigned long state;\n\t";
5969 Preamble += "void **itemsPtr;\n\t";
5970 Preamble += "unsigned long *mutationsPtr;\n\t";
5971 Preamble += "unsigned long extra[5];\n};\n";
5972 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5973 Preamble += "#define __FASTENUMERATIONSTATE\n";
5974 Preamble += "#endif\n";
5975 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5976 Preamble += "struct __NSConstantStringImpl {\n";
5977 Preamble += " int *isa;\n";
5978 Preamble += " int flags;\n";
5979 Preamble += " char *str;\n";
5980 Preamble += " long length;\n";
5981 Preamble += "};\n";
5982 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5983 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5984 Preamble += "#else\n";
5985 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5986 Preamble += "#endif\n";
5987 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5988 Preamble += "#endif\n";
5989 // Blocks preamble.
5990 Preamble += "#ifndef BLOCK_IMPL\n";
5991 Preamble += "#define BLOCK_IMPL\n";
5992 Preamble += "struct __block_impl {\n";
5993 Preamble += " void *isa;\n";
5994 Preamble += " int Flags;\n";
5995 Preamble += " int Reserved;\n";
5996 Preamble += " void *FuncPtr;\n";
5997 Preamble += "};\n";
5998 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5999 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6000 Preamble += "extern \"C\" __declspec(dllexport) "
6001 "void _Block_object_assign(void *, const void *, const int);\n";
6002 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6003 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6004 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6005 Preamble += "#else\n";
6006 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6007 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6008 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6009 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6010 Preamble += "#endif\n";
6011 Preamble += "#endif\n";
6012 if (LangOpts.MicrosoftExt) {
6013 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6014 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6015 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6016 Preamble += "#define __attribute__(X)\n";
6017 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006018 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006019 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006020 Preamble += "#endif\n";
6021 Preamble += "#ifndef __block\n";
6022 Preamble += "#define __block\n";
6023 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006024 }
6025 else {
6026 Preamble += "#define __block\n";
6027 Preamble += "#define __weak\n";
6028 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00006029
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006030 // Declarations required for modern objective-c array and dictionary literals.
6031 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006032 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006033 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006034 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006035 Preamble += "\tva_list marker;\n";
6036 Preamble += "\tva_start(marker, count);\n";
6037 Preamble += "\tarr = new void *[count];\n";
6038 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6039 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6040 Preamble += "\tva_end( marker );\n";
6041 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00006042 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006043 Preamble += "\tdelete[] arr;\n";
6044 Preamble += " }\n";
6045 Preamble += "};\n";
6046
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00006047 // Declaration required for implementation of @autoreleasepool statement.
6048 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6049 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6050 Preamble += "struct __AtAutoreleasePool {\n";
6051 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6052 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6053 Preamble += " void * atautoreleasepoolobj;\n";
6054 Preamble += "};\n";
6055
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006056 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6057 // as this avoids warning in any 64bit/32bit compilation model.
6058 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6059}
6060
6061/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6062/// ivar offset.
6063void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6064 std::string &Result) {
6065 if (ivar->isBitField()) {
6066 // FIXME: The hack below doesn't work for bitfields. For now, we simply
6067 // place all bitfields at offset 0.
6068 Result += "0";
6069 } else {
6070 Result += "__OFFSETOFIVAR__(struct ";
6071 Result += ivar->getContainingInterface()->getNameAsString();
6072 if (LangOpts.MicrosoftExt)
6073 Result += "_IMPL";
6074 Result += ", ";
6075 Result += ivar->getNameAsString();
6076 Result += ")";
6077 }
6078}
6079
6080/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6081/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006082/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006083/// char *attributes;
6084/// }
6085
6086/// struct _prop_list_t {
6087/// uint32_t entsize; // sizeof(struct _prop_t)
6088/// uint32_t count_of_properties;
6089/// struct _prop_t prop_list[count_of_properties];
6090/// }
6091
6092/// struct _protocol_t;
6093
6094/// struct _protocol_list_t {
6095/// long protocol_count; // Note, this is 32/64 bit
6096/// struct _protocol_t * protocol_list[protocol_count];
6097/// }
6098
6099/// struct _objc_method {
6100/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006101/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006102/// char *_imp;
6103/// }
6104
6105/// struct _method_list_t {
6106/// uint32_t entsize; // sizeof(struct _objc_method)
6107/// uint32_t method_count;
6108/// struct _objc_method method_list[method_count];
6109/// }
6110
6111/// struct _protocol_t {
6112/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006113/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006114/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006115/// const struct method_list_t *instance_methods;
6116/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006117/// const struct method_list_t *optionalInstanceMethods;
6118/// const struct method_list_t *optionalClassMethods;
6119/// const struct _prop_list_t * properties;
6120/// const uint32_t size; // sizeof(struct _protocol_t)
6121/// const uint32_t flags; // = 0
6122/// const char ** extendedMethodTypes;
6123/// }
6124
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006125/// struct _ivar_t {
6126/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00006127/// const char *name;
6128/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006129/// uint32_t alignment;
6130/// uint32_t size;
6131/// }
6132
6133/// struct _ivar_list_t {
6134/// uint32 entsize; // sizeof(struct _ivar_t)
6135/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00006136/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006137/// }
6138
6139/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006140/// uint32_t flags;
6141/// uint32_t instanceStart;
6142/// uint32_t instanceSize;
6143/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006144/// const uint8_t *ivarLayout;
6145/// const char *name;
6146/// const struct _method_list_t *baseMethods;
6147/// const struct _protocol_list_t *baseProtocols;
6148/// const struct _ivar_list_t *ivars;
6149/// const uint8_t *weakIvarLayout;
6150/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006151/// }
6152
6153/// struct _class_t {
6154/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006155/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006156/// void *cache;
6157/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006158/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006159/// }
6160
6161/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006162/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006163/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006164/// const struct _method_list_t *instance_methods;
6165/// const struct _method_list_t *class_methods;
6166/// const struct _protocol_list_t *protocols;
6167/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006168/// }
6169
6170/// MessageRefTy - LLVM for:
6171/// struct _message_ref_t {
6172/// IMP messenger;
6173/// SEL name;
6174/// };
6175
6176/// SuperMessageRefTy - LLVM for:
6177/// struct _super_message_ref_t {
6178/// SUPER_IMP messenger;
6179/// SEL name;
6180/// };
6181
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006182static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006183 static bool meta_data_declared = false;
6184 if (meta_data_declared)
6185 return;
6186
6187 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006188 Result += "\tconst char *name;\n";
6189 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006190 Result += "};\n";
6191
6192 Result += "\nstruct _protocol_t;\n";
6193
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006194 Result += "\nstruct _objc_method {\n";
6195 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006196 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006197 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006198 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006199
6200 Result += "\nstruct _protocol_t {\n";
6201 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006202 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006203 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006204 Result += "\tconst struct method_list_t *instance_methods;\n";
6205 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006206 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6207 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6208 Result += "\tconst struct _prop_list_t * properties;\n";
6209 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6210 Result += "\tconst unsigned int flags; // = 0\n";
6211 Result += "\tconst char ** extendedMethodTypes;\n";
6212 Result += "};\n";
6213
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006214 Result += "\nstruct _ivar_t {\n";
6215 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006216 Result += "\tconst char *name;\n";
6217 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006218 Result += "\tunsigned int alignment;\n";
6219 Result += "\tunsigned int size;\n";
6220 Result += "};\n";
6221
6222 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006223 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006224 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006225 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006226 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6227 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006228 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006229 Result += "\tconst unsigned char *ivarLayout;\n";
6230 Result += "\tconst char *name;\n";
6231 Result += "\tconst struct _method_list_t *baseMethods;\n";
6232 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6233 Result += "\tconst struct _ivar_list_t *ivars;\n";
6234 Result += "\tconst unsigned char *weakIvarLayout;\n";
6235 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006236 Result += "};\n";
6237
6238 Result += "\nstruct _class_t {\n";
6239 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006240 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006241 Result += "\tvoid *cache;\n";
6242 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006243 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006244 Result += "};\n";
6245
6246 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006247 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006248 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006249 Result += "\tconst struct _method_list_t *instance_methods;\n";
6250 Result += "\tconst struct _method_list_t *class_methods;\n";
6251 Result += "\tconst struct _protocol_list_t *protocols;\n";
6252 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006253 Result += "};\n";
6254
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006255 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006256 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006257 meta_data_declared = true;
6258}
6259
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006260static void Write_protocol_list_t_TypeDecl(std::string &Result,
6261 long super_protocol_count) {
6262 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6263 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6264 Result += "\tstruct _protocol_t *super_protocols[";
6265 Result += utostr(super_protocol_count); Result += "];\n";
6266 Result += "}";
6267}
6268
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006269static void Write_method_list_t_TypeDecl(std::string &Result,
6270 unsigned int method_count) {
6271 Result += "struct /*_method_list_t*/"; Result += " {\n";
6272 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6273 Result += "\tunsigned int method_count;\n";
6274 Result += "\tstruct _objc_method method_list[";
6275 Result += utostr(method_count); Result += "];\n";
6276 Result += "}";
6277}
6278
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006279static void Write__prop_list_t_TypeDecl(std::string &Result,
6280 unsigned int property_count) {
6281 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6282 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6283 Result += "\tunsigned int count_of_properties;\n";
6284 Result += "\tstruct _prop_t prop_list[";
6285 Result += utostr(property_count); Result += "];\n";
6286 Result += "}";
6287}
6288
Fariborz Jahanianae932952012-02-10 20:47:10 +00006289static void Write__ivar_list_t_TypeDecl(std::string &Result,
6290 unsigned int ivar_count) {
6291 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6292 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6293 Result += "\tunsigned int count;\n";
6294 Result += "\tstruct _ivar_t ivar_list[";
6295 Result += utostr(ivar_count); Result += "];\n";
6296 Result += "}";
6297}
6298
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006299static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6300 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6301 StringRef VarName,
6302 StringRef ProtocolName) {
6303 if (SuperProtocols.size() > 0) {
6304 Result += "\nstatic ";
6305 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6306 Result += " "; Result += VarName;
6307 Result += ProtocolName;
6308 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6309 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6310 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6311 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6312 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6313 Result += SuperPD->getNameAsString();
6314 if (i == e-1)
6315 Result += "\n};\n";
6316 else
6317 Result += ",\n";
6318 }
6319 }
6320}
6321
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006322static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6323 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006324 ArrayRef<ObjCMethodDecl *> Methods,
6325 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006326 StringRef TopLevelDeclName,
6327 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006328 if (Methods.size() > 0) {
6329 Result += "\nstatic ";
6330 Write_method_list_t_TypeDecl(Result, Methods.size());
6331 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006332 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006333 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6334 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6335 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6336 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6337 ObjCMethodDecl *MD = Methods[i];
6338 if (i == 0)
6339 Result += "\t{{(struct objc_selector *)\"";
6340 else
6341 Result += "\t{(struct objc_selector *)\"";
6342 Result += (MD)->getSelector().getAsString(); Result += "\"";
6343 Result += ", ";
6344 std::string MethodTypeString;
6345 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6346 Result += "\""; Result += MethodTypeString; Result += "\"";
6347 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006348 if (!MethodImpl)
6349 Result += "0";
6350 else {
6351 Result += "(void *)";
6352 Result += RewriteObj.MethodInternalNames[MD];
6353 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006354 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006355 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006356 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006357 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006358 }
6359 Result += "};\n";
6360 }
6361}
6362
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006363static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006364 ASTContext *Context, std::string &Result,
6365 ArrayRef<ObjCPropertyDecl *> Properties,
6366 const Decl *Container,
6367 StringRef VarName,
6368 StringRef ProtocolName) {
6369 if (Properties.size() > 0) {
6370 Result += "\nstatic ";
6371 Write__prop_list_t_TypeDecl(Result, Properties.size());
6372 Result += " "; Result += VarName;
6373 Result += ProtocolName;
6374 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6375 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6376 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6377 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6378 ObjCPropertyDecl *PropDecl = Properties[i];
6379 if (i == 0)
6380 Result += "\t{{\"";
6381 else
6382 Result += "\t{\"";
6383 Result += PropDecl->getName(); Result += "\",";
6384 std::string PropertyTypeString, QuotePropertyTypeString;
6385 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6386 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6387 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6388 if (i == e-1)
6389 Result += "}}\n";
6390 else
6391 Result += "},\n";
6392 }
6393 Result += "};\n";
6394 }
6395}
6396
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006397// Metadata flags
6398enum MetaDataDlags {
6399 CLS = 0x0,
6400 CLS_META = 0x1,
6401 CLS_ROOT = 0x2,
6402 OBJC2_CLS_HIDDEN = 0x10,
6403 CLS_EXCEPTION = 0x20,
6404
6405 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6406 CLS_HAS_IVAR_RELEASER = 0x40,
6407 /// class was compiled with -fobjc-arr
6408 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6409};
6410
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006411static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6412 unsigned int flags,
6413 const std::string &InstanceStart,
6414 const std::string &InstanceSize,
6415 ArrayRef<ObjCMethodDecl *>baseMethods,
6416 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6417 ArrayRef<ObjCIvarDecl *>ivars,
6418 ArrayRef<ObjCPropertyDecl *>Properties,
6419 StringRef VarName,
6420 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006421 Result += "\nstatic struct _class_ro_t ";
6422 Result += VarName; Result += ClassName;
6423 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6424 Result += "\t";
6425 Result += llvm::utostr(flags); Result += ", ";
6426 Result += InstanceStart; Result += ", ";
6427 Result += InstanceSize; Result += ", \n";
6428 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006429 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6430 if (Triple.getArch() == llvm::Triple::x86_64)
6431 // uint32_t const reserved; // only when building for 64bit targets
6432 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006433 // const uint8_t * const ivarLayout;
6434 Result += "0, \n\t";
6435 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006436 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006437 if (baseMethods.size() > 0) {
6438 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006439 if (metaclass)
6440 Result += "_OBJC_$_CLASS_METHODS_";
6441 else
6442 Result += "_OBJC_$_INSTANCE_METHODS_";
6443 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006444 Result += ",\n\t";
6445 }
6446 else
6447 Result += "0, \n\t";
6448
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006449 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006450 Result += "(const struct _objc_protocol_list *)&";
6451 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6452 Result += ",\n\t";
6453 }
6454 else
6455 Result += "0, \n\t";
6456
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006457 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006458 Result += "(const struct _ivar_list_t *)&";
6459 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6460 Result += ",\n\t";
6461 }
6462 else
6463 Result += "0, \n\t";
6464
6465 // weakIvarLayout
6466 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006467 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006468 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006469 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006470 Result += ",\n";
6471 }
6472 else
6473 Result += "0, \n";
6474
6475 Result += "};\n";
6476}
6477
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006478static void Write_class_t(ASTContext *Context, std::string &Result,
6479 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006480 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6481 bool rootClass = (!CDecl->getSuperClass());
6482 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006483
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006484 if (!rootClass) {
6485 // Find the Root class
6486 RootClass = CDecl->getSuperClass();
6487 while (RootClass->getSuperClass()) {
6488 RootClass = RootClass->getSuperClass();
6489 }
6490 }
6491
6492 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006493 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006494 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006495 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006496 if (CDecl->getImplementation())
6497 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006498 else
6499 Result += "__declspec(dllimport) ";
6500
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006501 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006502 Result += CDecl->getNameAsString();
6503 Result += ";\n";
6504 }
6505 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006506 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006507 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006508 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006509 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006510 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006511 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006512 else
6513 Result += "__declspec(dllimport) ";
6514
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006515 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006516 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006517 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006518 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006519
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006520 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006521 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006522 if (RootClass->getImplementation())
6523 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006524 else
6525 Result += "__declspec(dllimport) ";
6526
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006527 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006528 Result += VarName;
6529 Result += RootClass->getNameAsString();
6530 Result += ";\n";
6531 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006532 }
6533
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006534 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6535 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006536 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6537 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006538 if (metaclass) {
6539 if (!rootClass) {
6540 Result += "0, // &"; Result += VarName;
6541 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006542 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006543 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006544 Result += CDecl->getSuperClass()->getNameAsString();
6545 Result += ",\n\t";
6546 }
6547 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006548 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006549 Result += CDecl->getNameAsString();
6550 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006551 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006552 Result += ",\n\t";
6553 }
6554 }
6555 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006556 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006557 Result += CDecl->getNameAsString();
6558 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006559 if (!rootClass) {
6560 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006561 Result += CDecl->getSuperClass()->getNameAsString();
6562 Result += ",\n\t";
6563 }
6564 else
6565 Result += "0,\n\t";
6566 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006567 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6568 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6569 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006570 Result += "&_OBJC_METACLASS_RO_$_";
6571 else
6572 Result += "&_OBJC_CLASS_RO_$_";
6573 Result += CDecl->getNameAsString();
6574 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006575
6576 // Add static function to initialize some of the meta-data fields.
6577 // avoid doing it twice.
6578 if (metaclass)
6579 return;
6580
6581 const ObjCInterfaceDecl *SuperClass =
6582 rootClass ? CDecl : CDecl->getSuperClass();
6583
6584 Result += "static void OBJC_CLASS_SETUP_$_";
6585 Result += CDecl->getNameAsString();
6586 Result += "(void ) {\n";
6587 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6588 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006589 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006590
6591 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006592 Result += ".superclass = ";
6593 if (rootClass)
6594 Result += "&OBJC_CLASS_$_";
6595 else
6596 Result += "&OBJC_METACLASS_$_";
6597
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006598 Result += SuperClass->getNameAsString(); Result += ";\n";
6599
6600 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6601 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6602
6603 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6604 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6605 Result += CDecl->getNameAsString(); Result += ";\n";
6606
6607 if (!rootClass) {
6608 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6609 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6610 Result += SuperClass->getNameAsString(); Result += ";\n";
6611 }
6612
6613 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6614 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6615 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006616}
6617
Fariborz Jahanian61186122012-02-17 18:40:41 +00006618static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6619 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006620 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006621 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006622 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6623 ArrayRef<ObjCMethodDecl *> ClassMethods,
6624 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6625 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006626 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006627 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006628 // must declare an extern class object in case this class is not implemented
6629 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006630 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006631 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006632 if (ClassDecl->getImplementation())
6633 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006634 else
6635 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006636
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006637 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006638 Result += "OBJC_CLASS_$_"; Result += ClassName;
6639 Result += ";\n";
6640
Fariborz Jahanian61186122012-02-17 18:40:41 +00006641 Result += "\nstatic struct _category_t ";
6642 Result += "_OBJC_$_CATEGORY_";
6643 Result += ClassName; Result += "_$_"; Result += CatName;
6644 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6645 Result += "{\n";
6646 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006647 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006648 Result += ",\n";
6649 if (InstanceMethods.size() > 0) {
6650 Result += "\t(const struct _method_list_t *)&";
6651 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6652 Result += ClassName; Result += "_$_"; Result += CatName;
6653 Result += ",\n";
6654 }
6655 else
6656 Result += "\t0,\n";
6657
6658 if (ClassMethods.size() > 0) {
6659 Result += "\t(const struct _method_list_t *)&";
6660 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6661 Result += ClassName; Result += "_$_"; Result += CatName;
6662 Result += ",\n";
6663 }
6664 else
6665 Result += "\t0,\n";
6666
6667 if (RefedProtocols.size() > 0) {
6668 Result += "\t(const struct _protocol_list_t *)&";
6669 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6670 Result += ClassName; Result += "_$_"; Result += CatName;
6671 Result += ",\n";
6672 }
6673 else
6674 Result += "\t0,\n";
6675
6676 if (ClassProperties.size() > 0) {
6677 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6678 Result += ClassName; Result += "_$_"; Result += CatName;
6679 Result += ",\n";
6680 }
6681 else
6682 Result += "\t0,\n";
6683
6684 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006685
6686 // Add static function to initialize the class pointer in the category structure.
6687 Result += "static void OBJC_CATEGORY_SETUP_$_";
6688 Result += ClassDecl->getNameAsString();
6689 Result += "_$_";
6690 Result += CatName;
6691 Result += "(void ) {\n";
6692 Result += "\t_OBJC_$_CATEGORY_";
6693 Result += ClassDecl->getNameAsString();
6694 Result += "_$_";
6695 Result += CatName;
6696 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6697 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006698}
6699
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006700static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6701 ASTContext *Context, std::string &Result,
6702 ArrayRef<ObjCMethodDecl *> Methods,
6703 StringRef VarName,
6704 StringRef ProtocolName) {
6705 if (Methods.size() == 0)
6706 return;
6707
6708 Result += "\nstatic const char *";
6709 Result += VarName; Result += ProtocolName;
6710 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6711 Result += "{\n";
6712 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6713 ObjCMethodDecl *MD = Methods[i];
6714 std::string MethodTypeString, QuoteMethodTypeString;
6715 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6716 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6717 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6718 if (i == e-1)
6719 Result += "\n};\n";
6720 else {
6721 Result += ",\n";
6722 }
6723 }
6724}
6725
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006726static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6727 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006728 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006729 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006730 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006731 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6732 // this is what happens:
6733 /**
6734 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6735 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6736 Class->getVisibility() == HiddenVisibility)
6737 Visibility shoud be: HiddenVisibility;
6738 else
6739 Visibility shoud be: DefaultVisibility;
6740 */
6741
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006742 Result += "\n";
6743 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6744 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006745 if (Context->getLangOpts().MicrosoftExt)
6746 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6747
6748 if (!Context->getLangOpts().MicrosoftExt ||
6749 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006750 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006751 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006752 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006753 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006754 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006755 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6756 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006757 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6758 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006759 }
6760}
6761
Fariborz Jahanianae932952012-02-10 20:47:10 +00006762static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6763 ASTContext *Context, std::string &Result,
6764 ArrayRef<ObjCIvarDecl *> Ivars,
6765 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006766 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006767 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006768 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006769
Fariborz Jahanianae932952012-02-10 20:47:10 +00006770 Result += "\nstatic ";
6771 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6772 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006773 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006774 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6775 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6776 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6777 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6778 ObjCIvarDecl *IvarDecl = Ivars[i];
6779 if (i == 0)
6780 Result += "\t{{";
6781 else
6782 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006783 Result += "(unsigned long int *)&";
6784 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006785 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006786
6787 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6788 std::string IvarTypeString, QuoteIvarTypeString;
6789 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6790 IvarDecl);
6791 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6792 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6793
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006794 // FIXME. this alignment represents the host alignment and need be changed to
6795 // represent the target alignment.
6796 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6797 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006798 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006799 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6800 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006801 if (i == e-1)
6802 Result += "}}\n";
6803 else
6804 Result += "},\n";
6805 }
6806 Result += "};\n";
6807 }
6808}
6809
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006810/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006811void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6812 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006813
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006814 // Do not synthesize the protocol more than once.
6815 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6816 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006817 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006818
6819 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6820 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006821 // Must write out all protocol definitions in current qualifier list,
6822 // and in their nested qualifiers before writing out current definition.
6823 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6824 E = PDecl->protocol_end(); I != E; ++I)
6825 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006826
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006827 // Construct method lists.
6828 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6829 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6830 for (ObjCProtocolDecl::instmeth_iterator
6831 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6832 I != E; ++I) {
6833 ObjCMethodDecl *MD = *I;
6834 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6835 OptInstanceMethods.push_back(MD);
6836 } else {
6837 InstanceMethods.push_back(MD);
6838 }
6839 }
6840
6841 for (ObjCProtocolDecl::classmeth_iterator
6842 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6843 I != E; ++I) {
6844 ObjCMethodDecl *MD = *I;
6845 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6846 OptClassMethods.push_back(MD);
6847 } else {
6848 ClassMethods.push_back(MD);
6849 }
6850 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006851 std::vector<ObjCMethodDecl *> AllMethods;
6852 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6853 AllMethods.push_back(InstanceMethods[i]);
6854 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6855 AllMethods.push_back(ClassMethods[i]);
6856 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6857 AllMethods.push_back(OptInstanceMethods[i]);
6858 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6859 AllMethods.push_back(OptClassMethods[i]);
6860
6861 Write__extendedMethodTypes_initializer(*this, Context, Result,
6862 AllMethods,
6863 "_OBJC_PROTOCOL_METHOD_TYPES_",
6864 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006865 // Protocol's super protocol list
6866 std::vector<ObjCProtocolDecl *> SuperProtocols;
6867 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6868 E = PDecl->protocol_end(); I != E; ++I)
6869 SuperProtocols.push_back(*I);
6870
6871 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6872 "_OBJC_PROTOCOL_REFS_",
6873 PDecl->getNameAsString());
6874
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006875 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006876 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006877 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006878
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006879 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006880 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006881 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006882
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006883 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006884 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006885 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006886
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006887 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006888 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006889 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006890
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006891 // Protocol's property metadata.
6892 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6893 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6894 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00006895 ProtocolProperties.push_back(*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006896
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006897 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006898 /* Container */0,
6899 "_OBJC_PROTOCOL_PROPERTIES_",
6900 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006901
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006902 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006903 Result += "\n";
6904 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006905 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006906 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006907 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006908 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6909 Result += "\t0,\n"; // id is; is null
6910 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006911 if (SuperProtocols.size() > 0) {
6912 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6913 Result += PDecl->getNameAsString(); Result += ",\n";
6914 }
6915 else
6916 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006917 if (InstanceMethods.size() > 0) {
6918 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6919 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006920 }
6921 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006922 Result += "\t0,\n";
6923
6924 if (ClassMethods.size() > 0) {
6925 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6926 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006927 }
6928 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006929 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006930
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006931 if (OptInstanceMethods.size() > 0) {
6932 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6933 Result += PDecl->getNameAsString(); Result += ",\n";
6934 }
6935 else
6936 Result += "\t0,\n";
6937
6938 if (OptClassMethods.size() > 0) {
6939 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6940 Result += PDecl->getNameAsString(); Result += ",\n";
6941 }
6942 else
6943 Result += "\t0,\n";
6944
6945 if (ProtocolProperties.size() > 0) {
6946 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6947 Result += PDecl->getNameAsString(); Result += ",\n";
6948 }
6949 else
6950 Result += "\t0,\n";
6951
6952 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6953 Result += "\t0,\n";
6954
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006955 if (AllMethods.size() > 0) {
6956 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6957 Result += PDecl->getNameAsString();
6958 Result += "\n};\n";
6959 }
6960 else
6961 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006962
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006963 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006964 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006965 Result += "struct _protocol_t *";
6966 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6967 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6968 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006969
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006970 // Mark this protocol as having been generated.
6971 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6972 llvm_unreachable("protocol already synthesized");
6973
6974}
6975
6976void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6977 const ObjCList<ObjCProtocolDecl> &Protocols,
6978 StringRef prefix, StringRef ClassName,
6979 std::string &Result) {
6980 if (Protocols.empty()) return;
6981
6982 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006983 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006984
6985 // Output the top lovel protocol meta-data for the class.
6986 /* struct _objc_protocol_list {
6987 struct _objc_protocol_list *next;
6988 int protocol_count;
6989 struct _objc_protocol *class_protocols[];
6990 }
6991 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006992 Result += "\n";
6993 if (LangOpts.MicrosoftExt)
6994 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6995 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006996 Result += "\tstruct _objc_protocol_list *next;\n";
6997 Result += "\tint protocol_count;\n";
6998 Result += "\tstruct _objc_protocol *class_protocols[";
6999 Result += utostr(Protocols.size());
7000 Result += "];\n} _OBJC_";
7001 Result += prefix;
7002 Result += "_PROTOCOLS_";
7003 Result += ClassName;
7004 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7005 "{\n\t0, ";
7006 Result += utostr(Protocols.size());
7007 Result += "\n";
7008
7009 Result += "\t,{&_OBJC_PROTOCOL_";
7010 Result += Protocols[0]->getNameAsString();
7011 Result += " \n";
7012
7013 for (unsigned i = 1; i != Protocols.size(); i++) {
7014 Result += "\t ,&_OBJC_PROTOCOL_";
7015 Result += Protocols[i]->getNameAsString();
7016 Result += "\n";
7017 }
7018 Result += "\t }\n};\n";
7019}
7020
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007021/// hasObjCExceptionAttribute - Return true if this class or any super
7022/// class has the __objc_exception__ attribute.
7023/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7024static bool hasObjCExceptionAttribute(ASTContext &Context,
7025 const ObjCInterfaceDecl *OID) {
7026 if (OID->hasAttr<ObjCExceptionAttr>())
7027 return true;
7028 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7029 return hasObjCExceptionAttribute(Context, Super);
7030 return false;
7031}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007032
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007033void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7034 std::string &Result) {
7035 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7036
7037 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00007038 if (CDecl->isImplicitInterfaceDecl())
7039 assert(false &&
7040 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007041
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007042 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007043 SmallVector<ObjCIvarDecl *, 8> IVars;
7044
7045 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7046 IVD; IVD = IVD->getNextIvar()) {
7047 // Ignore unnamed bit-fields.
7048 if (!IVD->getDeclName())
7049 continue;
7050 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007051 }
7052
Fariborz Jahanianae932952012-02-10 20:47:10 +00007053 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007054 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007055 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007056
7057 // Build _objc_method_list for class's instance methods if needed
7058 SmallVector<ObjCMethodDecl *, 32>
7059 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7060
7061 // If any of our property implementations have associated getters or
7062 // setters, produce metadata for them as well.
7063 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7064 PropEnd = IDecl->propimpl_end();
7065 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007066 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007067 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007068 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007069 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007070 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007071 if (!PD)
7072 continue;
7073 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007074 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007075 InstanceMethods.push_back(Getter);
7076 if (PD->isReadOnly())
7077 continue;
7078 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007079 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007080 InstanceMethods.push_back(Setter);
7081 }
7082
7083 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7084 "_OBJC_$_INSTANCE_METHODS_",
7085 IDecl->getNameAsString(), true);
7086
7087 SmallVector<ObjCMethodDecl *, 32>
7088 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7089
7090 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7091 "_OBJC_$_CLASS_METHODS_",
7092 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00007093
7094 // Protocols referenced in class declaration?
7095 // Protocol's super protocol list
7096 std::vector<ObjCProtocolDecl *> RefedProtocols;
7097 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7098 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7099 E = Protocols.end();
7100 I != E; ++I) {
7101 RefedProtocols.push_back(*I);
7102 // Must write out all protocol definitions in current qualifier list,
7103 // and in their nested qualifiers before writing out current definition.
7104 RewriteObjCProtocolMetaData(*I, Result);
7105 }
7106
7107 Write_protocol_list_initializer(Context, Result,
7108 RefedProtocols,
7109 "_OBJC_CLASS_PROTOCOLS_$_",
7110 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007111
7112 // Protocol's property metadata.
7113 std::vector<ObjCPropertyDecl *> ClassProperties;
7114 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7115 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007116 ClassProperties.push_back(*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007117
7118 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00007119 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00007120 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007121 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007122
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007123
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007124 // Data for initializing _class_ro_t metaclass meta-data
7125 uint32_t flags = CLS_META;
7126 std::string InstanceSize;
7127 std::string InstanceStart;
7128
7129
7130 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7131 if (classIsHidden)
7132 flags |= OBJC2_CLS_HIDDEN;
7133
7134 if (!CDecl->getSuperClass())
7135 // class is root
7136 flags |= CLS_ROOT;
7137 InstanceSize = "sizeof(struct _class_t)";
7138 InstanceStart = InstanceSize;
7139 Write__class_ro_t_initializer(Context, Result, flags,
7140 InstanceStart, InstanceSize,
7141 ClassMethods,
7142 0,
7143 0,
7144 0,
7145 "_OBJC_METACLASS_RO_$_",
7146 CDecl->getNameAsString());
7147
7148
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007149 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007150 flags = CLS;
7151 if (classIsHidden)
7152 flags |= OBJC2_CLS_HIDDEN;
7153
7154 if (hasObjCExceptionAttribute(*Context, CDecl))
7155 flags |= CLS_EXCEPTION;
7156
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007157 if (!CDecl->getSuperClass())
7158 // class is root
7159 flags |= CLS_ROOT;
7160
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007161 InstanceSize.clear();
7162 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007163 if (!ObjCSynthesizedStructs.count(CDecl)) {
7164 InstanceSize = "0";
7165 InstanceStart = "0";
7166 }
7167 else {
7168 InstanceSize = "sizeof(struct ";
7169 InstanceSize += CDecl->getNameAsString();
7170 InstanceSize += "_IMPL)";
7171
7172 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7173 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007174 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007175 }
7176 else
7177 InstanceStart = InstanceSize;
7178 }
7179 Write__class_ro_t_initializer(Context, Result, flags,
7180 InstanceStart, InstanceSize,
7181 InstanceMethods,
7182 RefedProtocols,
7183 IVars,
7184 ClassProperties,
7185 "_OBJC_CLASS_RO_$_",
7186 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007187
7188 Write_class_t(Context, Result,
7189 "OBJC_METACLASS_$_",
7190 CDecl, /*metaclass*/true);
7191
7192 Write_class_t(Context, Result,
7193 "OBJC_CLASS_$_",
7194 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007195
7196 if (ImplementationIsNonLazy(IDecl))
7197 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007198
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007199}
7200
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007201void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7202 int ClsDefCount = ClassImplementation.size();
7203 if (!ClsDefCount)
7204 return;
7205 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7206 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7207 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7208 for (int i = 0; i < ClsDefCount; i++) {
7209 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7210 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7211 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7212 Result += CDecl->getName(); Result += ",\n";
7213 }
7214 Result += "};\n";
7215}
7216
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007217void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7218 int ClsDefCount = ClassImplementation.size();
7219 int CatDefCount = CategoryImplementation.size();
7220
7221 // For each implemented class, write out all its meta data.
7222 for (int i = 0; i < ClsDefCount; i++)
7223 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7224
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007225 RewriteClassSetupInitHook(Result);
7226
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007227 // For each implemented category, write out all its meta data.
7228 for (int i = 0; i < CatDefCount; i++)
7229 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7230
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007231 RewriteCategorySetupInitHook(Result);
7232
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007233 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007234 if (LangOpts.MicrosoftExt)
7235 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007236 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7237 Result += llvm::utostr(ClsDefCount); Result += "]";
7238 Result +=
7239 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7240 "regular,no_dead_strip\")))= {\n";
7241 for (int i = 0; i < ClsDefCount; i++) {
7242 Result += "\t&OBJC_CLASS_$_";
7243 Result += ClassImplementation[i]->getNameAsString();
7244 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007245 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007246 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007247
7248 if (!DefinedNonLazyClasses.empty()) {
7249 if (LangOpts.MicrosoftExt)
7250 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7251 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7252 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7253 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7254 Result += ",\n";
7255 }
7256 Result += "};\n";
7257 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007258 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007259
7260 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007261 if (LangOpts.MicrosoftExt)
7262 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007263 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7264 Result += llvm::utostr(CatDefCount); Result += "]";
7265 Result +=
7266 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7267 "regular,no_dead_strip\")))= {\n";
7268 for (int i = 0; i < CatDefCount; i++) {
7269 Result += "\t&_OBJC_$_CATEGORY_";
7270 Result +=
7271 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7272 Result += "_$_";
7273 Result += CategoryImplementation[i]->getNameAsString();
7274 Result += ",\n";
7275 }
7276 Result += "};\n";
7277 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007278
7279 if (!DefinedNonLazyCategories.empty()) {
7280 if (LangOpts.MicrosoftExt)
7281 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7282 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7283 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7284 Result += "\t&_OBJC_$_CATEGORY_";
7285 Result +=
7286 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7287 Result += "_$_";
7288 Result += DefinedNonLazyCategories[i]->getNameAsString();
7289 Result += ",\n";
7290 }
7291 Result += "};\n";
7292 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007293}
7294
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007295void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7296 if (LangOpts.MicrosoftExt)
7297 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7298
7299 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7300 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007301 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007302}
7303
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007304/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7305/// implementation.
7306void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7307 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007308 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007309 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7310 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007311 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007312 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7313 CDecl = CDecl->getNextClassCategory())
7314 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7315 break;
7316
7317 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007318 FullCategoryName += "_$_";
7319 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007320
7321 // Build _objc_method_list for class's instance methods if needed
7322 SmallVector<ObjCMethodDecl *, 32>
7323 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7324
7325 // If any of our property implementations have associated getters or
7326 // setters, produce metadata for them as well.
7327 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7328 PropEnd = IDecl->propimpl_end();
7329 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007330 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007331 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007332 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007333 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007334 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007335 if (!PD)
7336 continue;
7337 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7338 InstanceMethods.push_back(Getter);
7339 if (PD->isReadOnly())
7340 continue;
7341 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7342 InstanceMethods.push_back(Setter);
7343 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007344
Fariborz Jahanian61186122012-02-17 18:40:41 +00007345 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7346 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7347 FullCategoryName, true);
7348
7349 SmallVector<ObjCMethodDecl *, 32>
7350 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7351
7352 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7353 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7354 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007355
7356 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007357 // Protocol's super protocol list
7358 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007359 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7360 E = CDecl->protocol_end();
7361
7362 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007363 RefedProtocols.push_back(*I);
7364 // Must write out all protocol definitions in current qualifier list,
7365 // and in their nested qualifiers before writing out current definition.
7366 RewriteObjCProtocolMetaData(*I, Result);
7367 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007368
Fariborz Jahanian61186122012-02-17 18:40:41 +00007369 Write_protocol_list_initializer(Context, Result,
7370 RefedProtocols,
7371 "_OBJC_CATEGORY_PROTOCOLS_$_",
7372 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007373
Fariborz Jahanian61186122012-02-17 18:40:41 +00007374 // Protocol's property metadata.
7375 std::vector<ObjCPropertyDecl *> ClassProperties;
7376 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7377 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007378 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007379
Fariborz Jahanian61186122012-02-17 18:40:41 +00007380 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007381 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007382 "_OBJC_$_PROP_LIST_",
7383 FullCategoryName);
7384
7385 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007386 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007387 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007388 InstanceMethods,
7389 ClassMethods,
7390 RefedProtocols,
7391 ClassProperties);
7392
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007393 // Determine if this category is also "non-lazy".
7394 if (ImplementationIsNonLazy(IDecl))
7395 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007396
7397}
7398
7399void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7400 int CatDefCount = CategoryImplementation.size();
7401 if (!CatDefCount)
7402 return;
7403 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7404 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7405 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7406 for (int i = 0; i < CatDefCount; i++) {
7407 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7408 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7409 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7410 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7411 Result += ClassDecl->getName();
7412 Result += "_$_";
7413 Result += CatDecl->getName();
7414 Result += ",\n";
7415 }
7416 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007417}
7418
7419// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7420/// class methods.
7421template<typename MethodIterator>
7422void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7423 MethodIterator MethodEnd,
7424 bool IsInstanceMethod,
7425 StringRef prefix,
7426 StringRef ClassName,
7427 std::string &Result) {
7428 if (MethodBegin == MethodEnd) return;
7429
7430 if (!objc_impl_method) {
7431 /* struct _objc_method {
7432 SEL _cmd;
7433 char *method_types;
7434 void *_imp;
7435 }
7436 */
7437 Result += "\nstruct _objc_method {\n";
7438 Result += "\tSEL _cmd;\n";
7439 Result += "\tchar *method_types;\n";
7440 Result += "\tvoid *_imp;\n";
7441 Result += "};\n";
7442
7443 objc_impl_method = true;
7444 }
7445
7446 // Build _objc_method_list for class's methods if needed
7447
7448 /* struct {
7449 struct _objc_method_list *next_method;
7450 int method_count;
7451 struct _objc_method method_list[];
7452 }
7453 */
7454 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007455 Result += "\n";
7456 if (LangOpts.MicrosoftExt) {
7457 if (IsInstanceMethod)
7458 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7459 else
7460 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7461 }
7462 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007463 Result += "\tstruct _objc_method_list *next_method;\n";
7464 Result += "\tint method_count;\n";
7465 Result += "\tstruct _objc_method method_list[";
7466 Result += utostr(NumMethods);
7467 Result += "];\n} _OBJC_";
7468 Result += prefix;
7469 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7470 Result += "_METHODS_";
7471 Result += ClassName;
7472 Result += " __attribute__ ((used, section (\"__OBJC, __";
7473 Result += IsInstanceMethod ? "inst" : "cls";
7474 Result += "_meth\")))= ";
7475 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7476
7477 Result += "\t,{{(SEL)\"";
7478 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7479 std::string MethodTypeString;
7480 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7481 Result += "\", \"";
7482 Result += MethodTypeString;
7483 Result += "\", (void *)";
7484 Result += MethodInternalNames[*MethodBegin];
7485 Result += "}\n";
7486 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7487 Result += "\t ,{(SEL)\"";
7488 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7489 std::string MethodTypeString;
7490 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7491 Result += "\", \"";
7492 Result += MethodTypeString;
7493 Result += "\", (void *)";
7494 Result += MethodInternalNames[*MethodBegin];
7495 Result += "}\n";
7496 }
7497 Result += "\t }\n};\n";
7498}
7499
7500Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7501 SourceRange OldRange = IV->getSourceRange();
7502 Expr *BaseExpr = IV->getBase();
7503
7504 // Rewrite the base, but without actually doing replaces.
7505 {
7506 DisableReplaceStmtScope S(*this);
7507 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7508 IV->setBase(BaseExpr);
7509 }
7510
7511 ObjCIvarDecl *D = IV->getDecl();
7512
7513 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007514
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007515 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7516 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007517 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007518 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7519 // lookup which class implements the instance variable.
7520 ObjCInterfaceDecl *clsDeclared = 0;
7521 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7522 clsDeclared);
7523 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7524
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007525 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007526 std::string IvarOffsetName;
7527 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7528
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007529 ReferencedIvars[clsDeclared].insert(D);
7530
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007531 // cast offset to "char *".
7532 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7533 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007534 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007535 BaseExpr);
7536 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7537 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7538 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007539 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7540 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007541 SourceLocation());
7542 BinaryOperator *addExpr =
7543 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7544 Context->getPointerType(Context->CharTy),
Lang Hamesbe9af122012-10-02 04:45:10 +00007545 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007546 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007547 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7548 SourceLocation(),
7549 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007550 QualType IvarT = D->getType();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007551
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007552 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007553 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007554 RD = RD->getDefinition();
7555 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007556 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007557 ObjCContainerDecl *CDecl =
7558 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7559 // ivar in class extensions requires special treatment.
7560 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7561 CDecl = CatDecl->getClassInterface();
7562 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007563 RecName += "_IMPL";
7564 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7565 SourceLocation(), SourceLocation(),
7566 &Context->Idents.get(RecName.c_str()));
7567 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7568 unsigned UnsignedIntSize =
7569 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7570 Expr *Zero = IntegerLiteral::Create(*Context,
7571 llvm::APInt(UnsignedIntSize, 0),
7572 Context->UnsignedIntTy, SourceLocation());
7573 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7574 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7575 Zero);
7576 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7577 SourceLocation(),
7578 &Context->Idents.get(D->getNameAsString()),
7579 IvarT, 0,
7580 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00007581 ICIS_NoInit);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007582 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7583 FD->getType(), VK_LValue,
7584 OK_Ordinary);
7585 IvarT = Context->getDecltypeType(ME, ME->getType());
7586 }
7587 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007588 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007589 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007590
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007591 castExpr = NoTypeInfoCStyleCastExpr(Context,
7592 castT,
7593 CK_BitCast,
7594 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007595
7596
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007597 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007598 VK_LValue, OK_Ordinary,
7599 SourceLocation());
7600 PE = new (Context) ParenExpr(OldRange.getBegin(),
7601 OldRange.getEnd(),
7602 Exp);
7603
7604 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007605 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007606
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007607 ReplaceStmtWithRange(IV, Replacement, OldRange);
7608 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007609}