blob: 979326cad1f32aef272caa8b290ed67f0a3c8355 [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
14#include "clang/Rewrite/ASTConsumers.h"
15#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ParentMap.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Lex/Lexer.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34 class RewriteModernObjC : public ASTConsumer {
35 protected:
36
37 enum {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
39 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
44 helpers */
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
46 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
58 static const int OBJC_ABI_VERSION = 7;
59
60 Rewriter Rewrite;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
63 ASTContext *Context;
64 SourceManager *SM;
65 TranslationUnitDecl *TUDecl;
66 FileID MainFileID;
67 const char *MainFileStart, *MainFileEnd;
68 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000076 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000077 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000078 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 // ObjC string constant support.
80 unsigned NumObjCStringLiterals;
81 VarDecl *ConstantStringClassReference;
82 RecordDecl *NSStringRecord;
83
84 // ObjC foreach break/continue generation support.
85 int BcLabelCount;
86
87 unsigned TryFinallyContainsReturnDiag;
88 // Needed for super.
89 ObjCMethodDecl *CurMethodDef;
90 RecordDecl *SuperStructDecl;
91 RecordDecl *ConstantStringDecl;
92
93 FunctionDecl *MsgSendFunctionDecl;
94 FunctionDecl *MsgSendSuperFunctionDecl;
95 FunctionDecl *MsgSendStretFunctionDecl;
96 FunctionDecl *MsgSendSuperStretFunctionDecl;
97 FunctionDecl *MsgSendFpretFunctionDecl;
98 FunctionDecl *GetClassFunctionDecl;
99 FunctionDecl *GetMetaClassFunctionDecl;
100 FunctionDecl *GetSuperClassFunctionDecl;
101 FunctionDecl *SelGetUidFunctionDecl;
102 FunctionDecl *CFStringFunctionDecl;
103 FunctionDecl *SuperContructorFunctionDecl;
104 FunctionDecl *CurFunctionDef;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000105
106 /* Misc. containers needed for meta-data rewrite. */
107 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
108 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
109 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
110 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000112 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000113 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000114 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
115 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
116
117 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
118 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
119
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000120 SmallVector<Stmt *, 32> Stmts;
121 SmallVector<int, 8> ObjCBcLabelNo;
122 // Remember all the @protocol(<expr>) expressions.
123 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
124
125 llvm::DenseSet<uint64_t> CopyDestroyCache;
126
127 // Block expressions.
128 SmallVector<BlockExpr *, 32> Blocks;
129 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000130 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000131
John McCallf4b88a42012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000133
134 // Block related declarations.
135 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
136 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
137 SmallVector<ValueDecl *, 8> BlockByRefDecls;
138 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
139 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
140 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
141 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
142
143 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000144 llvm::DenseMap<ObjCInterfaceDecl *,
145 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
146
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
151
152 // Needed for header files being rewritten
153 bool IsHeader;
154 bool SilenceRewriteMacroWarning;
155 bool objc_impl_method;
156
157 bool DisableReplaceStmt;
158 class DisableReplaceStmtScope {
159 RewriteModernObjC &R;
160 bool SavedValue;
161
162 public:
163 DisableReplaceStmtScope(RewriteModernObjC &R)
164 : R(R), SavedValue(R.DisableReplaceStmt) {
165 R.DisableReplaceStmt = true;
166 }
167 ~DisableReplaceStmtScope() {
168 R.DisableReplaceStmt = SavedValue;
169 }
170 };
171 void InitializeCommon(ASTContext &context);
172
173 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000174 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000175 // Top Level Driver code.
176 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
177 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
178 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
179 if (!Class->isThisDeclarationADefinition()) {
180 RewriteForwardClassDecl(D);
181 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000182 } else {
183 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000184 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000185 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000186 }
187 }
188
189 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
190 if (!Proto->isThisDeclarationADefinition()) {
191 RewriteForwardProtocolDecl(D);
192 break;
193 }
194 }
195
196 HandleTopLevelSingleDecl(*I);
197 }
198 return true;
199 }
200 void HandleTopLevelSingleDecl(Decl *D);
201 void HandleDeclInMainFile(Decl *D);
202 RewriteModernObjC(std::string inFile, raw_ostream *OS,
203 DiagnosticsEngine &D, const LangOptions &LOpts,
204 bool silenceMacroWarn);
205
206 ~RewriteModernObjC() {}
207
208 virtual void HandleTranslationUnit(ASTContext &C);
209
210 void ReplaceStmt(Stmt *Old, Stmt *New) {
211 Stmt *ReplacingStmt = ReplacedNodes[Old];
212
213 if (ReplacingStmt)
214 return; // We can't rewrite the same node twice.
215
216 if (DisableReplaceStmt)
217 return;
218
219 // If replacement succeeded or warning disabled return with no warning.
220 if (!Rewrite.ReplaceStmt(Old, New)) {
221 ReplacedNodes[Old] = New;
222 return;
223 }
224 if (SilenceRewriteMacroWarning)
225 return;
226 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
227 << Old->getSourceRange();
228 }
229
230 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
231 if (DisableReplaceStmt)
232 return;
233
234 // Measure the old text.
235 int Size = Rewrite.getRangeSize(SrcRange);
236 if (Size == -1) {
237 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
238 << Old->getSourceRange();
239 return;
240 }
241 // Get the new text.
242 std::string SStr;
243 llvm::raw_string_ostream S(SStr);
244 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
245 const std::string &Str = S.str();
246
247 // If replacement succeeded or warning disabled return with no warning.
248 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
249 ReplacedNodes[Old] = New;
250 return;
251 }
252 if (SilenceRewriteMacroWarning)
253 return;
254 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
255 << Old->getSourceRange();
256 }
257
258 void InsertText(SourceLocation Loc, StringRef Str,
259 bool InsertAfter = true) {
260 // If insertion succeeded or warning disabled return with no warning.
261 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
262 SilenceRewriteMacroWarning)
263 return;
264
265 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
266 }
267
268 void ReplaceText(SourceLocation Start, unsigned OrigLength,
269 StringRef Str) {
270 // If removal succeeded or warning disabled return with no warning.
271 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
272 SilenceRewriteMacroWarning)
273 return;
274
275 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
276 }
277
278 // Syntactic Rewriting.
279 void RewriteRecordBody(RecordDecl *RD);
280 void RewriteInclude();
281 void RewriteForwardClassDecl(DeclGroupRef D);
282 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
283 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
284 const std::string &typedefString);
285 void RewriteImplementations();
286 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
287 ObjCImplementationDecl *IMD,
288 ObjCCategoryImplDecl *CID);
289 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
290 void RewriteImplementationDecl(Decl *Dcl);
291 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
292 ObjCMethodDecl *MDecl, std::string &ResultStr);
293 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
294 const FunctionType *&FPRetType);
295 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
296 ValueDecl *VD, bool def=false);
297 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
298 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
299 void RewriteForwardProtocolDecl(DeclGroupRef D);
300 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
301 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
302 void RewriteProperty(ObjCPropertyDecl *prop);
303 void RewriteFunctionDecl(FunctionDecl *FD);
304 void RewriteBlockPointerType(std::string& Str, QualType Type);
305 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000306 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000307 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
308 void RewriteTypeOfDecl(VarDecl *VD);
309 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
310
311 // Expression Rewriting.
312 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
313 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
314 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
315 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
316 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
317 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
318 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000319 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000320 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000321 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000322 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000323 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000324 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
325 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
326 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
327 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
328 SourceLocation OrigEnd);
329 Stmt *RewriteBreakStmt(BreakStmt *S);
330 Stmt *RewriteContinueStmt(ContinueStmt *S);
331 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000332 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000333 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000334
335 // Block rewriting.
336 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
337
338 // Block specific rewrite rules.
339 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000340 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000341 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000342 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
343 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
344
345 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
346 std::string &Result);
347
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000348 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000349 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000350 bool &IsNamedDefinition);
351 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
352 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000353
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000354 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
355
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000356 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
357 std::string &Result);
358
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000359 virtual void Initialize(ASTContext &context);
360
361 // Misc. AST transformation routines. Somtimes they end up calling
362 // rewriting routines on the new ASTs.
363 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
364 Expr **args, unsigned nargs,
365 SourceLocation StartLoc=SourceLocation(),
366 SourceLocation EndLoc=SourceLocation());
367
368 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
369 SourceLocation StartLoc=SourceLocation(),
370 SourceLocation EndLoc=SourceLocation());
371
372 void SynthCountByEnumWithState(std::string &buf);
373 void SynthMsgSendFunctionDecl();
374 void SynthMsgSendSuperFunctionDecl();
375 void SynthMsgSendStretFunctionDecl();
376 void SynthMsgSendFpretFunctionDecl();
377 void SynthMsgSendSuperStretFunctionDecl();
378 void SynthGetClassFunctionDecl();
379 void SynthGetMetaClassFunctionDecl();
380 void SynthGetSuperClassFunctionDecl();
381 void SynthSelGetUidFunctionDecl();
382 void SynthSuperContructorFunctionDecl();
383
384 // Rewriting metadata
385 template<typename MethodIterator>
386 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
387 MethodIterator MethodEnd,
388 bool IsInstanceMethod,
389 StringRef prefix,
390 StringRef ClassName,
391 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000392 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
393 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000394 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000395 const ObjCList<ObjCProtocolDecl> &Prots,
396 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000397 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000398 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000399 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000400
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000401 void RewriteMetaDataIntoBuffer(std::string &Result);
402 void WriteImageInfo(std::string &Result);
403 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000404 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000405 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000406
407 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000408 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000409 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000410 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000411
412
413 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
414 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
415 StringRef funcName, std::string Tag);
416 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
417 StringRef funcName, std::string Tag);
418 std::string SynthesizeBlockImpl(BlockExpr *CE,
419 std::string Tag, std::string Desc);
420 std::string SynthesizeBlockDescriptor(std::string DescTag,
421 std::string ImplTag,
422 int i, StringRef funcName,
423 unsigned hasCopy);
424 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
425 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
426 StringRef FunName);
427 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
428 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000429 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000430
431 // Misc. helper routines.
432 QualType getProtocolType();
433 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000434 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
435 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
436 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
437
438 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
439 void CollectBlockDeclRefInfo(BlockExpr *Exp);
440 void GetBlockDeclRefExprs(Stmt *S);
441 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000442 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000443 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
444
445 // We avoid calling Type::isBlockPointerType(), since it operates on the
446 // canonical type. We only care if the top-level type is a closure pointer.
447 bool isTopLevelBlockPointerType(QualType T) {
448 return isa<BlockPointerType>(T);
449 }
450
451 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
452 /// to a function pointer type and upon success, returns true; false
453 /// otherwise.
454 bool convertBlockPointerToFunctionPointer(QualType &T) {
455 if (isTopLevelBlockPointerType(T)) {
456 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
457 T = Context->getPointerType(BPT->getPointeeType());
458 return true;
459 }
460 return false;
461 }
462
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000463 bool convertObjCTypeToCStyleType(QualType &T);
464
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000465 bool needToScanForQualifiers(QualType T);
466 QualType getSuperStructType();
467 QualType getConstantStringStructType();
468 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
469 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
470
471 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000472 if (T->isObjCQualifiedIdType()) {
473 bool isConst = T.isConstQualified();
474 T = isConst ? Context->getObjCIdType().withConst()
475 : Context->getObjCIdType();
476 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000477 else if (T->isObjCQualifiedClassType())
478 T = Context->getObjCClassType();
479 else if (T->isObjCObjectPointerType() &&
480 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
481 if (const ObjCObjectPointerType * OBJPT =
482 T->getAsObjCInterfacePointerType()) {
483 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
484 T = QualType(IFaceT, 0);
485 T = Context->getPointerType(T);
486 }
487 }
488 }
489
490 // FIXME: This predicate seems like it would be useful to add to ASTContext.
491 bool isObjCType(QualType T) {
492 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
493 return false;
494
495 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
496
497 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
498 OCT == Context->getCanonicalType(Context->getObjCClassType()))
499 return true;
500
501 if (const PointerType *PT = OCT->getAs<PointerType>()) {
502 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
503 PT->getPointeeType()->isObjCQualifiedIdType())
504 return true;
505 }
506 return false;
507 }
508 bool PointerTypeTakesAnyBlockArguments(QualType QT);
509 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
510 void GetExtentOfArgList(const char *Name, const char *&LParen,
511 const char *&RParen);
512
513 void QuoteDoublequotes(std::string &From, std::string &To) {
514 for (unsigned i = 0; i < From.length(); i++) {
515 if (From[i] == '"')
516 To += "\\\"";
517 else
518 To += From[i];
519 }
520 }
521
522 QualType getSimpleFunctionType(QualType result,
523 const QualType *args,
524 unsigned numArgs,
525 bool variadic = false) {
526 if (result == Context->getObjCInstanceType())
527 result = Context->getObjCIdType();
528 FunctionProtoType::ExtProtoInfo fpi;
529 fpi.Variadic = variadic;
530 return Context->getFunctionType(result, args, numArgs, fpi);
531 }
532
533 // Helper function: create a CStyleCastExpr with trivial type source info.
534 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
535 CastKind Kind, Expr *E) {
536 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
537 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
538 SourceLocation(), SourceLocation());
539 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000540
541 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
542 IdentifierInfo* II = &Context->Idents.get("load");
543 Selector LoadSel = Context->Selectors.getSelector(0, &II);
544 return OD->getClassMethod(LoadSel) != 0;
545 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000546 };
547
548}
549
550void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
551 NamedDecl *D) {
552 if (const FunctionProtoType *fproto
553 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
554 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
555 E = fproto->arg_type_end(); I && (I != E); ++I)
556 if (isTopLevelBlockPointerType(*I)) {
557 // All the args are checked/rewritten. Don't call twice!
558 RewriteBlockPointerDecl(D);
559 break;
560 }
561 }
562}
563
564void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
565 const PointerType *PT = funcType->getAs<PointerType>();
566 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
567 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
568}
569
570static bool IsHeaderFile(const std::string &Filename) {
571 std::string::size_type DotPos = Filename.rfind('.');
572
573 if (DotPos == std::string::npos) {
574 // no file extension
575 return false;
576 }
577
578 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
579 // C header: .h
580 // C++ header: .hh or .H;
581 return Ext == "h" || Ext == "hh" || Ext == "H";
582}
583
584RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
585 DiagnosticsEngine &D, const LangOptions &LOpts,
586 bool silenceMacroWarn)
587 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
588 SilenceRewriteMacroWarning(silenceMacroWarn) {
589 IsHeader = IsHeaderFile(inFile);
590 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
591 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000592 // FIXME. This should be an error. But if block is not called, it is OK. And it
593 // may break including some headers.
594 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
595 "rewriting block literal declared in global scope is not implemented");
596
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000597 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
598 DiagnosticsEngine::Warning,
599 "rewriter doesn't support user-specified control flow semantics "
600 "for @try/@finally (code may not execute properly)");
601}
602
603ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
604 raw_ostream* OS,
605 DiagnosticsEngine &Diags,
606 const LangOptions &LOpts,
607 bool SilenceRewriteMacroWarning) {
608 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
609}
610
611void RewriteModernObjC::InitializeCommon(ASTContext &context) {
612 Context = &context;
613 SM = &Context->getSourceManager();
614 TUDecl = Context->getTranslationUnitDecl();
615 MsgSendFunctionDecl = 0;
616 MsgSendSuperFunctionDecl = 0;
617 MsgSendStretFunctionDecl = 0;
618 MsgSendSuperStretFunctionDecl = 0;
619 MsgSendFpretFunctionDecl = 0;
620 GetClassFunctionDecl = 0;
621 GetMetaClassFunctionDecl = 0;
622 GetSuperClassFunctionDecl = 0;
623 SelGetUidFunctionDecl = 0;
624 CFStringFunctionDecl = 0;
625 ConstantStringClassReference = 0;
626 NSStringRecord = 0;
627 CurMethodDef = 0;
628 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000629 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000630 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000631 SuperStructDecl = 0;
632 ProtocolTypeDecl = 0;
633 ConstantStringDecl = 0;
634 BcLabelCount = 0;
635 SuperContructorFunctionDecl = 0;
636 NumObjCStringLiterals = 0;
637 PropParentMap = 0;
638 CurrentBody = 0;
639 DisableReplaceStmt = false;
640 objc_impl_method = false;
641
642 // Get the ID and start/end of the main file.
643 MainFileID = SM->getMainFileID();
644 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
645 MainFileStart = MainBuf->getBufferStart();
646 MainFileEnd = MainBuf->getBufferEnd();
647
David Blaikie4e4d0842012-03-11 07:00:24 +0000648 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000649}
650
651//===----------------------------------------------------------------------===//
652// Top Level Driver Code
653//===----------------------------------------------------------------------===//
654
655void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
656 if (Diags.hasErrorOccurred())
657 return;
658
659 // Two cases: either the decl could be in the main file, or it could be in a
660 // #included file. If the former, rewrite it now. If the later, check to see
661 // if we rewrote the #include/#import.
662 SourceLocation Loc = D->getLocation();
663 Loc = SM->getExpansionLoc(Loc);
664
665 // If this is for a builtin, ignore it.
666 if (Loc.isInvalid()) return;
667
668 // Look for built-in declarations that we need to refer during the rewrite.
669 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
670 RewriteFunctionDecl(FD);
671 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
672 // declared in <Foundation/NSString.h>
673 if (FVD->getName() == "_NSConstantStringClassReference") {
674 ConstantStringClassReference = FVD;
675 return;
676 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000677 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
678 RewriteCategoryDecl(CD);
679 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
680 if (PD->isThisDeclarationADefinition())
681 RewriteProtocolDecl(PD);
682 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000683 // FIXME. This will not work in all situations and leaving it out
684 // is harmless.
685 // RewriteLinkageSpec(LSD);
686
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000687 // Recurse into linkage specifications
688 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
689 DIEnd = LSD->decls_end();
690 DI != DIEnd; ) {
691 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
692 if (!IFace->isThisDeclarationADefinition()) {
693 SmallVector<Decl *, 8> DG;
694 SourceLocation StartLoc = IFace->getLocStart();
695 do {
696 if (isa<ObjCInterfaceDecl>(*DI) &&
697 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
698 StartLoc == (*DI)->getLocStart())
699 DG.push_back(*DI);
700 else
701 break;
702
703 ++DI;
704 } while (DI != DIEnd);
705 RewriteForwardClassDecl(DG);
706 continue;
707 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000708 else {
709 // Keep track of all interface declarations seen.
710 ObjCInterfacesSeen.push_back(IFace);
711 ++DI;
712 continue;
713 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000714 }
715
716 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
717 if (!Proto->isThisDeclarationADefinition()) {
718 SmallVector<Decl *, 8> DG;
719 SourceLocation StartLoc = Proto->getLocStart();
720 do {
721 if (isa<ObjCProtocolDecl>(*DI) &&
722 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
723 StartLoc == (*DI)->getLocStart())
724 DG.push_back(*DI);
725 else
726 break;
727
728 ++DI;
729 } while (DI != DIEnd);
730 RewriteForwardProtocolDecl(DG);
731 continue;
732 }
733 }
734
735 HandleTopLevelSingleDecl(*DI);
736 ++DI;
737 }
738 }
739 // If we have a decl in the main file, see if we should rewrite it.
740 if (SM->isFromMainFile(Loc))
741 return HandleDeclInMainFile(D);
742}
743
744//===----------------------------------------------------------------------===//
745// Syntactic (non-AST) Rewriting Code
746//===----------------------------------------------------------------------===//
747
748void RewriteModernObjC::RewriteInclude() {
749 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
750 StringRef MainBuf = SM->getBufferData(MainFileID);
751 const char *MainBufStart = MainBuf.begin();
752 const char *MainBufEnd = MainBuf.end();
753 size_t ImportLen = strlen("import");
754
755 // Loop over the whole file, looking for includes.
756 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
757 if (*BufPtr == '#') {
758 if (++BufPtr == MainBufEnd)
759 return;
760 while (*BufPtr == ' ' || *BufPtr == '\t')
761 if (++BufPtr == MainBufEnd)
762 return;
763 if (!strncmp(BufPtr, "import", ImportLen)) {
764 // replace import with include
765 SourceLocation ImportLoc =
766 LocStart.getLocWithOffset(BufPtr-MainBufStart);
767 ReplaceText(ImportLoc, ImportLen, "include");
768 BufPtr += ImportLen;
769 }
770 }
771 }
772}
773
774static std::string getIvarAccessString(ObjCIvarDecl *OID) {
775 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
776 std::string S;
777 S = "((struct ";
778 S += ClassDecl->getIdentifier()->getName();
779 S += "_IMPL *)self)->";
780 S += OID->getName();
781 return S;
782}
783
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000784/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
785/// been found in the class implementation. In this case, it must be synthesized.
786static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
787 ObjCPropertyDecl *PD,
788 bool getter) {
789 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
790 : !IMP->getInstanceMethod(PD->getSetterName());
791
792}
793
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000794void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
795 ObjCImplementationDecl *IMD,
796 ObjCCategoryImplDecl *CID) {
797 static bool objcGetPropertyDefined = false;
798 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000799 SourceLocation startGetterSetterLoc;
800
801 if (PID->getLocStart().isValid()) {
802 SourceLocation startLoc = PID->getLocStart();
803 InsertText(startLoc, "// ");
804 const char *startBuf = SM->getCharacterData(startLoc);
805 assert((*startBuf == '@') && "bogus @synthesize location");
806 const char *semiBuf = strchr(startBuf, ';');
807 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
808 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
809 }
810 else
811 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000812
813 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
814 return; // FIXME: is this correct?
815
816 // Generate the 'getter' function.
817 ObjCPropertyDecl *PD = PID->getPropertyDecl();
818 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
819
820 if (!OID)
821 return;
822 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000823 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000824 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
825 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
826 ObjCPropertyDecl::OBJC_PR_copy));
827 std::string Getr;
828 if (GenGetProperty && !objcGetPropertyDefined) {
829 objcGetPropertyDefined = true;
830 // FIXME. Is this attribute correct in all cases?
831 Getr = "\nextern \"C\" __declspec(dllimport) "
832 "id objc_getProperty(id, SEL, long, bool);\n";
833 }
834 RewriteObjCMethodDecl(OID->getContainingInterface(),
835 PD->getGetterMethodDecl(), Getr);
836 Getr += "{ ";
837 // Synthesize an explicit cast to gain access to the ivar.
838 // See objc-act.c:objc_synthesize_new_getter() for details.
839 if (GenGetProperty) {
840 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
841 Getr += "typedef ";
842 const FunctionType *FPRetType = 0;
843 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
844 FPRetType);
845 Getr += " _TYPE";
846 if (FPRetType) {
847 Getr += ")"; // close the precedence "scope" for "*".
848
849 // Now, emit the argument types (if any).
850 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
851 Getr += "(";
852 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
853 if (i) Getr += ", ";
854 std::string ParamStr = FT->getArgType(i).getAsString(
855 Context->getPrintingPolicy());
856 Getr += ParamStr;
857 }
858 if (FT->isVariadic()) {
859 if (FT->getNumArgs()) Getr += ", ";
860 Getr += "...";
861 }
862 Getr += ")";
863 } else
864 Getr += "()";
865 }
866 Getr += ";\n";
867 Getr += "return (_TYPE)";
868 Getr += "objc_getProperty(self, _cmd, ";
869 RewriteIvarOffsetComputation(OID, Getr);
870 Getr += ", 1)";
871 }
872 else
873 Getr += "return " + getIvarAccessString(OID);
874 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000875 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000876 }
877
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000878 if (PD->isReadOnly() ||
879 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000880 return;
881
882 // Generate the 'setter' function.
883 std::string Setr;
884 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
885 ObjCPropertyDecl::OBJC_PR_copy);
886 if (GenSetProperty && !objcSetPropertyDefined) {
887 objcSetPropertyDefined = true;
888 // FIXME. Is this attribute correct in all cases?
889 Setr = "\nextern \"C\" __declspec(dllimport) "
890 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
891 }
892
893 RewriteObjCMethodDecl(OID->getContainingInterface(),
894 PD->getSetterMethodDecl(), Setr);
895 Setr += "{ ";
896 // Synthesize an explicit cast to initialize the ivar.
897 // See objc-act.c:objc_synthesize_new_setter() for details.
898 if (GenSetProperty) {
899 Setr += "objc_setProperty (self, _cmd, ";
900 RewriteIvarOffsetComputation(OID, Setr);
901 Setr += ", (id)";
902 Setr += PD->getName();
903 Setr += ", ";
904 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
905 Setr += "0, ";
906 else
907 Setr += "1, ";
908 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
909 Setr += "1)";
910 else
911 Setr += "0)";
912 }
913 else {
914 Setr += getIvarAccessString(OID) + " = ";
915 Setr += PD->getName();
916 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000917 Setr += "; }\n";
918 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000919}
920
921static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
922 std::string &typedefString) {
923 typedefString += "#ifndef _REWRITER_typedef_";
924 typedefString += ForwardDecl->getNameAsString();
925 typedefString += "\n";
926 typedefString += "#define _REWRITER_typedef_";
927 typedefString += ForwardDecl->getNameAsString();
928 typedefString += "\n";
929 typedefString += "typedef struct objc_object ";
930 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000931 // typedef struct { } _objc_exc_Classname;
932 typedefString += ";\ntypedef struct {} _objc_exc_";
933 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000934 typedefString += ";\n#endif\n";
935}
936
937void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
938 const std::string &typedefString) {
939 SourceLocation startLoc = ClassDecl->getLocStart();
940 const char *startBuf = SM->getCharacterData(startLoc);
941 const char *semiPtr = strchr(startBuf, ';');
942 // Replace the @class with typedefs corresponding to the classes.
943 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
944}
945
946void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
947 std::string typedefString;
948 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
949 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
950 if (I == D.begin()) {
951 // Translate to typedef's that forward reference structs with the same name
952 // as the class. As a convenience, we include the original declaration
953 // as a comment.
954 typedefString += "// @class ";
955 typedefString += ForwardDecl->getNameAsString();
956 typedefString += ";\n";
957 }
958 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
959 }
960 DeclGroupRef::iterator I = D.begin();
961 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
962}
963
964void RewriteModernObjC::RewriteForwardClassDecl(
965 const llvm::SmallVector<Decl*, 8> &D) {
966 std::string typedefString;
967 for (unsigned i = 0; i < D.size(); i++) {
968 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
969 if (i == 0) {
970 typedefString += "// @class ";
971 typedefString += ForwardDecl->getNameAsString();
972 typedefString += ";\n";
973 }
974 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
975 }
976 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
977}
978
979void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
980 // When method is a synthesized one, such as a getter/setter there is
981 // nothing to rewrite.
982 if (Method->isImplicit())
983 return;
984 SourceLocation LocStart = Method->getLocStart();
985 SourceLocation LocEnd = Method->getLocEnd();
986
987 if (SM->getExpansionLineNumber(LocEnd) >
988 SM->getExpansionLineNumber(LocStart)) {
989 InsertText(LocStart, "#if 0\n");
990 ReplaceText(LocEnd, 1, ";\n#endif\n");
991 } else {
992 InsertText(LocStart, "// ");
993 }
994}
995
996void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
997 SourceLocation Loc = prop->getAtLoc();
998
999 ReplaceText(Loc, 0, "// ");
1000 // FIXME: handle properties that are declared across multiple lines.
1001}
1002
1003void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1004 SourceLocation LocStart = CatDecl->getLocStart();
1005
1006 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001007 if (CatDecl->getIvarRBraceLoc().isValid()) {
1008 ReplaceText(LocStart, 1, "/** ");
1009 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1010 }
1011 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001012 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001013 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001014
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001015 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1016 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001017 RewriteProperty(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001018
1019 for (ObjCCategoryDecl::instmeth_iterator
1020 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1021 I != E; ++I)
1022 RewriteMethodDeclaration(*I);
1023 for (ObjCCategoryDecl::classmeth_iterator
1024 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1025 I != E; ++I)
1026 RewriteMethodDeclaration(*I);
1027
1028 // Lastly, comment out the @end.
1029 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1030 strlen("@end"), "/* @end */");
1031}
1032
1033void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1034 SourceLocation LocStart = PDecl->getLocStart();
1035 assert(PDecl->isThisDeclarationADefinition());
1036
1037 // FIXME: handle protocol headers that are declared across multiple lines.
1038 ReplaceText(LocStart, 0, "// ");
1039
1040 for (ObjCProtocolDecl::instmeth_iterator
1041 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1042 I != E; ++I)
1043 RewriteMethodDeclaration(*I);
1044 for (ObjCProtocolDecl::classmeth_iterator
1045 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1046 I != E; ++I)
1047 RewriteMethodDeclaration(*I);
1048
1049 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1050 E = PDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001051 RewriteProperty(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001052
1053 // Lastly, comment out the @end.
1054 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1055 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1056
1057 // Must comment out @optional/@required
1058 const char *startBuf = SM->getCharacterData(LocStart);
1059 const char *endBuf = SM->getCharacterData(LocEnd);
1060 for (const char *p = startBuf; p < endBuf; p++) {
1061 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1062 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1063 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1064
1065 }
1066 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1067 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1068 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1069
1070 }
1071 }
1072}
1073
1074void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1075 SourceLocation LocStart = (*D.begin())->getLocStart();
1076 if (LocStart.isInvalid())
1077 llvm_unreachable("Invalid SourceLocation");
1078 // FIXME: handle forward protocol that are declared across multiple lines.
1079 ReplaceText(LocStart, 0, "// ");
1080}
1081
1082void
1083RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1084 SourceLocation LocStart = DG[0]->getLocStart();
1085 if (LocStart.isInvalid())
1086 llvm_unreachable("Invalid SourceLocation");
1087 // FIXME: handle forward protocol that are declared across multiple lines.
1088 ReplaceText(LocStart, 0, "// ");
1089}
1090
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001091void
1092RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1093 SourceLocation LocStart = LSD->getExternLoc();
1094 if (LocStart.isInvalid())
1095 llvm_unreachable("Invalid extern SourceLocation");
1096
1097 ReplaceText(LocStart, 0, "// ");
1098 if (!LSD->hasBraces())
1099 return;
1100 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1101 SourceLocation LocRBrace = LSD->getRBraceLoc();
1102 if (LocRBrace.isInvalid())
1103 llvm_unreachable("Invalid rbrace SourceLocation");
1104 ReplaceText(LocRBrace, 0, "// ");
1105}
1106
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001107void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1108 const FunctionType *&FPRetType) {
1109 if (T->isObjCQualifiedIdType())
1110 ResultStr += "id";
1111 else if (T->isFunctionPointerType() ||
1112 T->isBlockPointerType()) {
1113 // needs special handling, since pointer-to-functions have special
1114 // syntax (where a decaration models use).
1115 QualType retType = T;
1116 QualType PointeeTy;
1117 if (const PointerType* PT = retType->getAs<PointerType>())
1118 PointeeTy = PT->getPointeeType();
1119 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1120 PointeeTy = BPT->getPointeeType();
1121 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1122 ResultStr += FPRetType->getResultType().getAsString(
1123 Context->getPrintingPolicy());
1124 ResultStr += "(*";
1125 }
1126 } else
1127 ResultStr += T.getAsString(Context->getPrintingPolicy());
1128}
1129
1130void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1131 ObjCMethodDecl *OMD,
1132 std::string &ResultStr) {
1133 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1134 const FunctionType *FPRetType = 0;
1135 ResultStr += "\nstatic ";
1136 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1137 ResultStr += " ";
1138
1139 // Unique method name
1140 std::string NameStr;
1141
1142 if (OMD->isInstanceMethod())
1143 NameStr += "_I_";
1144 else
1145 NameStr += "_C_";
1146
1147 NameStr += IDecl->getNameAsString();
1148 NameStr += "_";
1149
1150 if (ObjCCategoryImplDecl *CID =
1151 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1152 NameStr += CID->getNameAsString();
1153 NameStr += "_";
1154 }
1155 // Append selector names, replacing ':' with '_'
1156 {
1157 std::string selString = OMD->getSelector().getAsString();
1158 int len = selString.size();
1159 for (int i = 0; i < len; i++)
1160 if (selString[i] == ':')
1161 selString[i] = '_';
1162 NameStr += selString;
1163 }
1164 // Remember this name for metadata emission
1165 MethodInternalNames[OMD] = NameStr;
1166 ResultStr += NameStr;
1167
1168 // Rewrite arguments
1169 ResultStr += "(";
1170
1171 // invisible arguments
1172 if (OMD->isInstanceMethod()) {
1173 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1174 selfTy = Context->getPointerType(selfTy);
1175 if (!LangOpts.MicrosoftExt) {
1176 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1177 ResultStr += "struct ";
1178 }
1179 // When rewriting for Microsoft, explicitly omit the structure name.
1180 ResultStr += IDecl->getNameAsString();
1181 ResultStr += " *";
1182 }
1183 else
1184 ResultStr += Context->getObjCClassType().getAsString(
1185 Context->getPrintingPolicy());
1186
1187 ResultStr += " self, ";
1188 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1189 ResultStr += " _cmd";
1190
1191 // Method arguments.
1192 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1193 E = OMD->param_end(); PI != E; ++PI) {
1194 ParmVarDecl *PDecl = *PI;
1195 ResultStr += ", ";
1196 if (PDecl->getType()->isObjCQualifiedIdType()) {
1197 ResultStr += "id ";
1198 ResultStr += PDecl->getNameAsString();
1199 } else {
1200 std::string Name = PDecl->getNameAsString();
1201 QualType QT = PDecl->getType();
1202 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001203 (void)convertBlockPointerToFunctionPointer(QT);
1204 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001205 ResultStr += Name;
1206 }
1207 }
1208 if (OMD->isVariadic())
1209 ResultStr += ", ...";
1210 ResultStr += ") ";
1211
1212 if (FPRetType) {
1213 ResultStr += ")"; // close the precedence "scope" for "*".
1214
1215 // Now, emit the argument types (if any).
1216 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1217 ResultStr += "(";
1218 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1219 if (i) ResultStr += ", ";
1220 std::string ParamStr = FT->getArgType(i).getAsString(
1221 Context->getPrintingPolicy());
1222 ResultStr += ParamStr;
1223 }
1224 if (FT->isVariadic()) {
1225 if (FT->getNumArgs()) ResultStr += ", ";
1226 ResultStr += "...";
1227 }
1228 ResultStr += ")";
1229 } else {
1230 ResultStr += "()";
1231 }
1232 }
1233}
1234void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1235 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1236 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1237
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001238 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001239 if (IMD->getIvarRBraceLoc().isValid()) {
1240 ReplaceText(IMD->getLocStart(), 1, "/** ");
1241 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001242 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001243 else {
1244 InsertText(IMD->getLocStart(), "// ");
1245 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001246 }
1247 else
1248 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001249
1250 for (ObjCCategoryImplDecl::instmeth_iterator
1251 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1252 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1253 I != E; ++I) {
1254 std::string ResultStr;
1255 ObjCMethodDecl *OMD = *I;
1256 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1257 SourceLocation LocStart = OMD->getLocStart();
1258 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1259
1260 const char *startBuf = SM->getCharacterData(LocStart);
1261 const char *endBuf = SM->getCharacterData(LocEnd);
1262 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1263 }
1264
1265 for (ObjCCategoryImplDecl::classmeth_iterator
1266 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1267 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1268 I != E; ++I) {
1269 std::string ResultStr;
1270 ObjCMethodDecl *OMD = *I;
1271 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1272 SourceLocation LocStart = OMD->getLocStart();
1273 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1274
1275 const char *startBuf = SM->getCharacterData(LocStart);
1276 const char *endBuf = SM->getCharacterData(LocEnd);
1277 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1278 }
1279 for (ObjCCategoryImplDecl::propimpl_iterator
1280 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1281 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1282 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001283 RewritePropertyImplDecl(&*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001284 }
1285
1286 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1287}
1288
1289void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001290 // Do not synthesize more than once.
1291 if (ObjCSynthesizedStructs.count(ClassDecl))
1292 return;
1293 // Make sure super class's are written before current class is written.
1294 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1295 while (SuperClass) {
1296 RewriteInterfaceDecl(SuperClass);
1297 SuperClass = SuperClass->getSuperClass();
1298 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001299 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001300 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001301 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001302 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001303 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1304
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001305 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001306 // Mark this typedef as having been written into its c++ equivalent.
1307 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001308
1309 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001310 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001311 RewriteProperty(&*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001312 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001313 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001314 I != E; ++I)
1315 RewriteMethodDeclaration(*I);
1316 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001317 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001318 I != E; ++I)
1319 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001320
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001321 // Lastly, comment out the @end.
1322 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1323 "/* @end */");
1324 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001325}
1326
1327Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1328 SourceRange OldRange = PseudoOp->getSourceRange();
1329
1330 // We just magically know some things about the structure of this
1331 // expression.
1332 ObjCMessageExpr *OldMsg =
1333 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1334 PseudoOp->getNumSemanticExprs() - 1));
1335
1336 // Because the rewriter doesn't allow us to rewrite rewritten code,
1337 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001338 Expr *Base;
1339 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001340 {
1341 DisableReplaceStmtScope S(*this);
1342
1343 // Rebuild the base expression if we have one.
1344 Base = 0;
1345 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1346 Base = OldMsg->getInstanceReceiver();
1347 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1348 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1349 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001350
1351 unsigned numArgs = OldMsg->getNumArgs();
1352 for (unsigned i = 0; i < numArgs; i++) {
1353 Expr *Arg = OldMsg->getArg(i);
1354 if (isa<OpaqueValueExpr>(Arg))
1355 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1356 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1357 Args.push_back(Arg);
1358 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001359 }
1360
1361 // TODO: avoid this copy.
1362 SmallVector<SourceLocation, 1> SelLocs;
1363 OldMsg->getSelectorLocs(SelLocs);
1364
1365 ObjCMessageExpr *NewMsg = 0;
1366 switch (OldMsg->getReceiverKind()) {
1367 case ObjCMessageExpr::Class:
1368 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1369 OldMsg->getValueKind(),
1370 OldMsg->getLeftLoc(),
1371 OldMsg->getClassReceiverTypeInfo(),
1372 OldMsg->getSelector(),
1373 SelLocs,
1374 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001375 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001376 OldMsg->getRightLoc(),
1377 OldMsg->isImplicit());
1378 break;
1379
1380 case ObjCMessageExpr::Instance:
1381 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1382 OldMsg->getValueKind(),
1383 OldMsg->getLeftLoc(),
1384 Base,
1385 OldMsg->getSelector(),
1386 SelLocs,
1387 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001388 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001389 OldMsg->getRightLoc(),
1390 OldMsg->isImplicit());
1391 break;
1392
1393 case ObjCMessageExpr::SuperClass:
1394 case ObjCMessageExpr::SuperInstance:
1395 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1396 OldMsg->getValueKind(),
1397 OldMsg->getLeftLoc(),
1398 OldMsg->getSuperLoc(),
1399 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1400 OldMsg->getSuperType(),
1401 OldMsg->getSelector(),
1402 SelLocs,
1403 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001404 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001405 OldMsg->getRightLoc(),
1406 OldMsg->isImplicit());
1407 break;
1408 }
1409
1410 Stmt *Replacement = SynthMessageExpr(NewMsg);
1411 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1412 return Replacement;
1413}
1414
1415Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1416 SourceRange OldRange = PseudoOp->getSourceRange();
1417
1418 // We just magically know some things about the structure of this
1419 // expression.
1420 ObjCMessageExpr *OldMsg =
1421 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1422
1423 // Because the rewriter doesn't allow us to rewrite rewritten code,
1424 // we need to suppress rewriting the sub-statements.
1425 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001426 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001427 {
1428 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001429 // Rebuild the base expression if we have one.
1430 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1431 Base = OldMsg->getInstanceReceiver();
1432 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1433 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1434 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001435 unsigned numArgs = OldMsg->getNumArgs();
1436 for (unsigned i = 0; i < numArgs; i++) {
1437 Expr *Arg = OldMsg->getArg(i);
1438 if (isa<OpaqueValueExpr>(Arg))
1439 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1440 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1441 Args.push_back(Arg);
1442 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001443 }
1444
1445 // Intentionally empty.
1446 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001447
1448 ObjCMessageExpr *NewMsg = 0;
1449 switch (OldMsg->getReceiverKind()) {
1450 case ObjCMessageExpr::Class:
1451 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1452 OldMsg->getValueKind(),
1453 OldMsg->getLeftLoc(),
1454 OldMsg->getClassReceiverTypeInfo(),
1455 OldMsg->getSelector(),
1456 SelLocs,
1457 OldMsg->getMethodDecl(),
1458 Args,
1459 OldMsg->getRightLoc(),
1460 OldMsg->isImplicit());
1461 break;
1462
1463 case ObjCMessageExpr::Instance:
1464 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1465 OldMsg->getValueKind(),
1466 OldMsg->getLeftLoc(),
1467 Base,
1468 OldMsg->getSelector(),
1469 SelLocs,
1470 OldMsg->getMethodDecl(),
1471 Args,
1472 OldMsg->getRightLoc(),
1473 OldMsg->isImplicit());
1474 break;
1475
1476 case ObjCMessageExpr::SuperClass:
1477 case ObjCMessageExpr::SuperInstance:
1478 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1479 OldMsg->getValueKind(),
1480 OldMsg->getLeftLoc(),
1481 OldMsg->getSuperLoc(),
1482 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1483 OldMsg->getSuperType(),
1484 OldMsg->getSelector(),
1485 SelLocs,
1486 OldMsg->getMethodDecl(),
1487 Args,
1488 OldMsg->getRightLoc(),
1489 OldMsg->isImplicit());
1490 break;
1491 }
1492
1493 Stmt *Replacement = SynthMessageExpr(NewMsg);
1494 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1495 return Replacement;
1496}
1497
1498/// SynthCountByEnumWithState - To print:
1499/// ((unsigned int (*)
1500/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1501/// (void *)objc_msgSend)((id)l_collection,
1502/// sel_registerName(
1503/// "countByEnumeratingWithState:objects:count:"),
1504/// &enumState,
1505/// (id *)__rw_items, (unsigned int)16)
1506///
1507void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1508 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1509 "id *, unsigned int))(void *)objc_msgSend)";
1510 buf += "\n\t\t";
1511 buf += "((id)l_collection,\n\t\t";
1512 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1513 buf += "\n\t\t";
1514 buf += "&enumState, "
1515 "(id *)__rw_items, (unsigned int)16)";
1516}
1517
1518/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1519/// statement to exit to its outer synthesized loop.
1520///
1521Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1522 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1523 return S;
1524 // replace break with goto __break_label
1525 std::string buf;
1526
1527 SourceLocation startLoc = S->getLocStart();
1528 buf = "goto __break_label_";
1529 buf += utostr(ObjCBcLabelNo.back());
1530 ReplaceText(startLoc, strlen("break"), buf);
1531
1532 return 0;
1533}
1534
1535/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1536/// statement to continue with its inner synthesized loop.
1537///
1538Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1539 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1540 return S;
1541 // replace continue with goto __continue_label
1542 std::string buf;
1543
1544 SourceLocation startLoc = S->getLocStart();
1545 buf = "goto __continue_label_";
1546 buf += utostr(ObjCBcLabelNo.back());
1547 ReplaceText(startLoc, strlen("continue"), buf);
1548
1549 return 0;
1550}
1551
1552/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1553/// It rewrites:
1554/// for ( type elem in collection) { stmts; }
1555
1556/// Into:
1557/// {
1558/// type elem;
1559/// struct __objcFastEnumerationState enumState = { 0 };
1560/// id __rw_items[16];
1561/// id l_collection = (id)collection;
1562/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1563/// objects:__rw_items count:16];
1564/// if (limit) {
1565/// unsigned long startMutations = *enumState.mutationsPtr;
1566/// do {
1567/// unsigned long counter = 0;
1568/// do {
1569/// if (startMutations != *enumState.mutationsPtr)
1570/// objc_enumerationMutation(l_collection);
1571/// elem = (type)enumState.itemsPtr[counter++];
1572/// stmts;
1573/// __continue_label: ;
1574/// } while (counter < limit);
1575/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1576/// objects:__rw_items count:16]);
1577/// elem = nil;
1578/// __break_label: ;
1579/// }
1580/// else
1581/// elem = nil;
1582/// }
1583///
1584Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1585 SourceLocation OrigEnd) {
1586 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1587 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1588 "ObjCForCollectionStmt Statement stack mismatch");
1589 assert(!ObjCBcLabelNo.empty() &&
1590 "ObjCForCollectionStmt - Label No stack empty");
1591
1592 SourceLocation startLoc = S->getLocStart();
1593 const char *startBuf = SM->getCharacterData(startLoc);
1594 StringRef elementName;
1595 std::string elementTypeAsString;
1596 std::string buf;
1597 buf = "\n{\n\t";
1598 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1599 // type elem;
1600 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1601 QualType ElementType = cast<ValueDecl>(D)->getType();
1602 if (ElementType->isObjCQualifiedIdType() ||
1603 ElementType->isObjCQualifiedInterfaceType())
1604 // Simply use 'id' for all qualified types.
1605 elementTypeAsString = "id";
1606 else
1607 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1608 buf += elementTypeAsString;
1609 buf += " ";
1610 elementName = D->getName();
1611 buf += elementName;
1612 buf += ";\n\t";
1613 }
1614 else {
1615 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1616 elementName = DR->getDecl()->getName();
1617 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1618 if (VD->getType()->isObjCQualifiedIdType() ||
1619 VD->getType()->isObjCQualifiedInterfaceType())
1620 // Simply use 'id' for all qualified types.
1621 elementTypeAsString = "id";
1622 else
1623 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1624 }
1625
1626 // struct __objcFastEnumerationState enumState = { 0 };
1627 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1628 // id __rw_items[16];
1629 buf += "id __rw_items[16];\n\t";
1630 // id l_collection = (id)
1631 buf += "id l_collection = (id)";
1632 // Find start location of 'collection' the hard way!
1633 const char *startCollectionBuf = startBuf;
1634 startCollectionBuf += 3; // skip 'for'
1635 startCollectionBuf = strchr(startCollectionBuf, '(');
1636 startCollectionBuf++; // skip '('
1637 // find 'in' and skip it.
1638 while (*startCollectionBuf != ' ' ||
1639 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1640 (*(startCollectionBuf+3) != ' ' &&
1641 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1642 startCollectionBuf++;
1643 startCollectionBuf += 3;
1644
1645 // Replace: "for (type element in" with string constructed thus far.
1646 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1647 // Replace ')' in for '(' type elem in collection ')' with ';'
1648 SourceLocation rightParenLoc = S->getRParenLoc();
1649 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1650 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1651 buf = ";\n\t";
1652
1653 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1654 // objects:__rw_items count:16];
1655 // which is synthesized into:
1656 // unsigned int limit =
1657 // ((unsigned int (*)
1658 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1659 // (void *)objc_msgSend)((id)l_collection,
1660 // sel_registerName(
1661 // "countByEnumeratingWithState:objects:count:"),
1662 // (struct __objcFastEnumerationState *)&state,
1663 // (id *)__rw_items, (unsigned int)16);
1664 buf += "unsigned long limit =\n\t\t";
1665 SynthCountByEnumWithState(buf);
1666 buf += ";\n\t";
1667 /// if (limit) {
1668 /// unsigned long startMutations = *enumState.mutationsPtr;
1669 /// do {
1670 /// unsigned long counter = 0;
1671 /// do {
1672 /// if (startMutations != *enumState.mutationsPtr)
1673 /// objc_enumerationMutation(l_collection);
1674 /// elem = (type)enumState.itemsPtr[counter++];
1675 buf += "if (limit) {\n\t";
1676 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1677 buf += "do {\n\t\t";
1678 buf += "unsigned long counter = 0;\n\t\t";
1679 buf += "do {\n\t\t\t";
1680 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1681 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1682 buf += elementName;
1683 buf += " = (";
1684 buf += elementTypeAsString;
1685 buf += ")enumState.itemsPtr[counter++];";
1686 // Replace ')' in for '(' type elem in collection ')' with all of these.
1687 ReplaceText(lparenLoc, 1, buf);
1688
1689 /// __continue_label: ;
1690 /// } while (counter < limit);
1691 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1692 /// objects:__rw_items count:16]);
1693 /// elem = nil;
1694 /// __break_label: ;
1695 /// }
1696 /// else
1697 /// elem = nil;
1698 /// }
1699 ///
1700 buf = ";\n\t";
1701 buf += "__continue_label_";
1702 buf += utostr(ObjCBcLabelNo.back());
1703 buf += ": ;";
1704 buf += "\n\t\t";
1705 buf += "} while (counter < limit);\n\t";
1706 buf += "} while (limit = ";
1707 SynthCountByEnumWithState(buf);
1708 buf += ");\n\t";
1709 buf += elementName;
1710 buf += " = ((";
1711 buf += elementTypeAsString;
1712 buf += ")0);\n\t";
1713 buf += "__break_label_";
1714 buf += utostr(ObjCBcLabelNo.back());
1715 buf += ": ;\n\t";
1716 buf += "}\n\t";
1717 buf += "else\n\t\t";
1718 buf += elementName;
1719 buf += " = ((";
1720 buf += elementTypeAsString;
1721 buf += ")0);\n\t";
1722 buf += "}\n";
1723
1724 // Insert all these *after* the statement body.
1725 // FIXME: If this should support Obj-C++, support CXXTryStmt
1726 if (isa<CompoundStmt>(S->getBody())) {
1727 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1728 InsertText(endBodyLoc, buf);
1729 } else {
1730 /* Need to treat single statements specially. For example:
1731 *
1732 * for (A *a in b) if (stuff()) break;
1733 * for (A *a in b) xxxyy;
1734 *
1735 * The following code simply scans ahead to the semi to find the actual end.
1736 */
1737 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1738 const char *semiBuf = strchr(stmtBuf, ';');
1739 assert(semiBuf && "Can't find ';'");
1740 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1741 InsertText(endBodyLoc, buf);
1742 }
1743 Stmts.pop_back();
1744 ObjCBcLabelNo.pop_back();
1745 return 0;
1746}
1747
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001748static void Write_RethrowObject(std::string &buf) {
1749 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1750 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1751 buf += "\tid rethrow;\n";
1752 buf += "\t} _fin_force_rethow(_rethrow);";
1753}
1754
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001755/// RewriteObjCSynchronizedStmt -
1756/// This routine rewrites @synchronized(expr) stmt;
1757/// into:
1758/// objc_sync_enter(expr);
1759/// @try stmt @finally { objc_sync_exit(expr); }
1760///
1761Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1762 // Get the start location and compute the semi location.
1763 SourceLocation startLoc = S->getLocStart();
1764 const char *startBuf = SM->getCharacterData(startLoc);
1765
1766 assert((*startBuf == '@') && "bogus @synchronized location");
1767
1768 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001769 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001770
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001771 const char *lparenBuf = startBuf;
1772 while (*lparenBuf != '(') lparenBuf++;
1773 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001774
1775 buf = "; objc_sync_enter(_sync_obj);\n";
1776 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1777 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1778 buf += "\n\tid sync_exit;";
1779 buf += "\n\t} _sync_exit(_sync_obj);\n";
1780
1781 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1782 // the sync expression is typically a message expression that's already
1783 // been rewritten! (which implies the SourceLocation's are invalid).
1784 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1785 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1786 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1787 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1788
1789 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1790 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1791 assert (*LBraceLocBuf == '{');
1792 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001793
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001794 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001795 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1796 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001797
1798 buf = "} catch (id e) {_rethrow = e;}\n";
1799 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001800 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001801 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001802
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001803 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001804
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001805 return 0;
1806}
1807
1808void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1809{
1810 // Perform a bottom up traversal of all children.
1811 for (Stmt::child_range CI = S->children(); CI; ++CI)
1812 if (*CI)
1813 WarnAboutReturnGotoStmts(*CI);
1814
1815 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1816 Diags.Report(Context->getFullLoc(S->getLocStart()),
1817 TryFinallyContainsReturnDiag);
1818 }
1819 return;
1820}
1821
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001822Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001823 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001824 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001825 std::string buf;
1826
1827 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001828 if (noCatch)
1829 buf = "{ id volatile _rethrow = 0;\n";
1830 else {
1831 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1832 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001833 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001834 // Get the start location and compute the semi location.
1835 SourceLocation startLoc = S->getLocStart();
1836 const char *startBuf = SM->getCharacterData(startLoc);
1837
1838 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001839 if (finalStmt)
1840 ReplaceText(startLoc, 1, buf);
1841 else
1842 // @try -> try
1843 ReplaceText(startLoc, 1, "");
1844
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001845 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1846 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001847 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001848
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001849 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001850 bool AtRemoved = false;
1851 if (catchDecl) {
1852 QualType t = catchDecl->getType();
1853 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1854 // Should be a pointer to a class.
1855 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1856 if (IDecl) {
1857 std::string Result;
1858 startBuf = SM->getCharacterData(startLoc);
1859 assert((*startBuf == '@') && "bogus @catch location");
1860 SourceLocation rParenLoc = Catch->getRParenLoc();
1861 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1862
1863 // _objc_exc_Foo *_e as argument to catch.
1864 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1865 Result += " *_"; Result += catchDecl->getNameAsString();
1866 Result += ")";
1867 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1868 // Foo *e = (Foo *)_e;
1869 Result.clear();
1870 Result = "{ ";
1871 Result += IDecl->getNameAsString();
1872 Result += " *"; Result += catchDecl->getNameAsString();
1873 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1874 Result += "_"; Result += catchDecl->getNameAsString();
1875
1876 Result += "; ";
1877 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1878 ReplaceText(lBraceLoc, 1, Result);
1879 AtRemoved = true;
1880 }
1881 }
1882 }
1883 if (!AtRemoved)
1884 // @catch -> catch
1885 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001886
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001887 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001888 if (finalStmt) {
1889 buf.clear();
1890 if (noCatch)
1891 buf = "catch (id e) {_rethrow = e;}\n";
1892 else
1893 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1894
1895 SourceLocation startFinalLoc = finalStmt->getLocStart();
1896 ReplaceText(startFinalLoc, 8, buf);
1897 Stmt *body = finalStmt->getFinallyBody();
1898 SourceLocation startFinalBodyLoc = body->getLocStart();
1899 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001900 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001901 ReplaceText(startFinalBodyLoc, 1, buf);
1902
1903 SourceLocation endFinalBodyLoc = body->getLocEnd();
1904 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001905 // Now check for any return/continue/go statements within the @try.
1906 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001907 }
1908
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001909 return 0;
1910}
1911
1912// This can't be done with ReplaceStmt(S, ThrowExpr), since
1913// the throw expression is typically a message expression that's already
1914// been rewritten! (which implies the SourceLocation's are invalid).
1915Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1916 // Get the start location and compute the semi location.
1917 SourceLocation startLoc = S->getLocStart();
1918 const char *startBuf = SM->getCharacterData(startLoc);
1919
1920 assert((*startBuf == '@') && "bogus @throw location");
1921
1922 std::string buf;
1923 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1924 if (S->getThrowExpr())
1925 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001926 else
1927 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001928
1929 // handle "@ throw" correctly.
1930 const char *wBuf = strchr(startBuf, 'w');
1931 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1932 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1933
1934 const char *semiBuf = strchr(startBuf, ';');
1935 assert((*semiBuf == ';') && "@throw: can't find ';'");
1936 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001937 if (S->getThrowExpr())
1938 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001939 return 0;
1940}
1941
1942Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1943 // Create a new string expression.
1944 QualType StrType = Context->getPointerType(Context->CharTy);
1945 std::string StrEncoding;
1946 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1947 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1948 StringLiteral::Ascii, false,
1949 StrType, SourceLocation());
1950 ReplaceStmt(Exp, Replacement);
1951
1952 // Replace this subexpr in the parent.
1953 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1954 return Replacement;
1955}
1956
1957Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1958 if (!SelGetUidFunctionDecl)
1959 SynthSelGetUidFunctionDecl();
1960 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1961 // Create a call to sel_registerName("selName").
1962 SmallVector<Expr*, 8> SelExprs;
1963 QualType argType = Context->getPointerType(Context->CharTy);
1964 SelExprs.push_back(StringLiteral::Create(*Context,
1965 Exp->getSelector().getAsString(),
1966 StringLiteral::Ascii, false,
1967 argType, SourceLocation()));
1968 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1969 &SelExprs[0], SelExprs.size());
1970 ReplaceStmt(Exp, SelExp);
1971 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1972 return SelExp;
1973}
1974
1975CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1976 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1977 SourceLocation EndLoc) {
1978 // Get the type, we will need to reference it in a couple spots.
1979 QualType msgSendType = FD->getType();
1980
1981 // Create a reference to the objc_msgSend() declaration.
1982 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001983 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001984
1985 // Now, we cast the reference to a pointer to the objc_msgSend type.
1986 QualType pToFunc = Context->getPointerType(msgSendType);
1987 ImplicitCastExpr *ICE =
1988 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1989 DRE, 0, VK_RValue);
1990
1991 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1992
1993 CallExpr *Exp =
1994 new (Context) CallExpr(*Context, ICE, args, nargs,
1995 FT->getCallResultType(*Context),
1996 VK_RValue, EndLoc);
1997 return Exp;
1998}
1999
2000static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2001 const char *&startRef, const char *&endRef) {
2002 while (startBuf < endBuf) {
2003 if (*startBuf == '<')
2004 startRef = startBuf; // mark the start.
2005 if (*startBuf == '>') {
2006 if (startRef && *startRef == '<') {
2007 endRef = startBuf; // mark the end.
2008 return true;
2009 }
2010 return false;
2011 }
2012 startBuf++;
2013 }
2014 return false;
2015}
2016
2017static void scanToNextArgument(const char *&argRef) {
2018 int angle = 0;
2019 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2020 if (*argRef == '<')
2021 angle++;
2022 else if (*argRef == '>')
2023 angle--;
2024 argRef++;
2025 }
2026 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2027}
2028
2029bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2030 if (T->isObjCQualifiedIdType())
2031 return true;
2032 if (const PointerType *PT = T->getAs<PointerType>()) {
2033 if (PT->getPointeeType()->isObjCQualifiedIdType())
2034 return true;
2035 }
2036 if (T->isObjCObjectPointerType()) {
2037 T = T->getPointeeType();
2038 return T->isObjCQualifiedInterfaceType();
2039 }
2040 if (T->isArrayType()) {
2041 QualType ElemTy = Context->getBaseElementType(T);
2042 return needToScanForQualifiers(ElemTy);
2043 }
2044 return false;
2045}
2046
2047void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2048 QualType Type = E->getType();
2049 if (needToScanForQualifiers(Type)) {
2050 SourceLocation Loc, EndLoc;
2051
2052 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2053 Loc = ECE->getLParenLoc();
2054 EndLoc = ECE->getRParenLoc();
2055 } else {
2056 Loc = E->getLocStart();
2057 EndLoc = E->getLocEnd();
2058 }
2059 // This will defend against trying to rewrite synthesized expressions.
2060 if (Loc.isInvalid() || EndLoc.isInvalid())
2061 return;
2062
2063 const char *startBuf = SM->getCharacterData(Loc);
2064 const char *endBuf = SM->getCharacterData(EndLoc);
2065 const char *startRef = 0, *endRef = 0;
2066 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2067 // Get the locations of the startRef, endRef.
2068 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2069 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2070 // Comment out the protocol references.
2071 InsertText(LessLoc, "/*");
2072 InsertText(GreaterLoc, "*/");
2073 }
2074 }
2075}
2076
2077void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2078 SourceLocation Loc;
2079 QualType Type;
2080 const FunctionProtoType *proto = 0;
2081 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2082 Loc = VD->getLocation();
2083 Type = VD->getType();
2084 }
2085 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2086 Loc = FD->getLocation();
2087 // Check for ObjC 'id' and class types that have been adorned with protocol
2088 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2089 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2090 assert(funcType && "missing function type");
2091 proto = dyn_cast<FunctionProtoType>(funcType);
2092 if (!proto)
2093 return;
2094 Type = proto->getResultType();
2095 }
2096 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2097 Loc = FD->getLocation();
2098 Type = FD->getType();
2099 }
2100 else
2101 return;
2102
2103 if (needToScanForQualifiers(Type)) {
2104 // Since types are unique, we need to scan the buffer.
2105
2106 const char *endBuf = SM->getCharacterData(Loc);
2107 const char *startBuf = endBuf;
2108 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2109 startBuf--; // scan backward (from the decl location) for return type.
2110 const char *startRef = 0, *endRef = 0;
2111 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2112 // Get the locations of the startRef, endRef.
2113 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2114 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2115 // Comment out the protocol references.
2116 InsertText(LessLoc, "/*");
2117 InsertText(GreaterLoc, "*/");
2118 }
2119 }
2120 if (!proto)
2121 return; // most likely, was a variable
2122 // Now check arguments.
2123 const char *startBuf = SM->getCharacterData(Loc);
2124 const char *startFuncBuf = startBuf;
2125 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2126 if (needToScanForQualifiers(proto->getArgType(i))) {
2127 // Since types are unique, we need to scan the buffer.
2128
2129 const char *endBuf = startBuf;
2130 // scan forward (from the decl location) for argument types.
2131 scanToNextArgument(endBuf);
2132 const char *startRef = 0, *endRef = 0;
2133 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2134 // Get the locations of the startRef, endRef.
2135 SourceLocation LessLoc =
2136 Loc.getLocWithOffset(startRef-startFuncBuf);
2137 SourceLocation GreaterLoc =
2138 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2139 // Comment out the protocol references.
2140 InsertText(LessLoc, "/*");
2141 InsertText(GreaterLoc, "*/");
2142 }
2143 startBuf = ++endBuf;
2144 }
2145 else {
2146 // If the function name is derived from a macro expansion, then the
2147 // argument buffer will not follow the name. Need to speak with Chris.
2148 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2149 startBuf++; // scan forward (from the decl location) for argument types.
2150 startBuf++;
2151 }
2152 }
2153}
2154
2155void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2156 QualType QT = ND->getType();
2157 const Type* TypePtr = QT->getAs<Type>();
2158 if (!isa<TypeOfExprType>(TypePtr))
2159 return;
2160 while (isa<TypeOfExprType>(TypePtr)) {
2161 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2162 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2163 TypePtr = QT->getAs<Type>();
2164 }
2165 // FIXME. This will not work for multiple declarators; as in:
2166 // __typeof__(a) b,c,d;
2167 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2168 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2169 const char *startBuf = SM->getCharacterData(DeclLoc);
2170 if (ND->getInit()) {
2171 std::string Name(ND->getNameAsString());
2172 TypeAsString += " " + Name + " = ";
2173 Expr *E = ND->getInit();
2174 SourceLocation startLoc;
2175 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2176 startLoc = ECE->getLParenLoc();
2177 else
2178 startLoc = E->getLocStart();
2179 startLoc = SM->getExpansionLoc(startLoc);
2180 const char *endBuf = SM->getCharacterData(startLoc);
2181 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2182 }
2183 else {
2184 SourceLocation X = ND->getLocEnd();
2185 X = SM->getExpansionLoc(X);
2186 const char *endBuf = SM->getCharacterData(X);
2187 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2188 }
2189}
2190
2191// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2192void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2193 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2194 SmallVector<QualType, 16> ArgTys;
2195 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2196 QualType getFuncType =
2197 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2198 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2199 SourceLocation(),
2200 SourceLocation(),
2201 SelGetUidIdent, getFuncType, 0,
2202 SC_Extern,
2203 SC_None, false);
2204}
2205
2206void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2207 // declared in <objc/objc.h>
2208 if (FD->getIdentifier() &&
2209 FD->getName() == "sel_registerName") {
2210 SelGetUidFunctionDecl = FD;
2211 return;
2212 }
2213 RewriteObjCQualifiedInterfaceTypes(FD);
2214}
2215
2216void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2217 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2218 const char *argPtr = TypeString.c_str();
2219 if (!strchr(argPtr, '^')) {
2220 Str += TypeString;
2221 return;
2222 }
2223 while (*argPtr) {
2224 Str += (*argPtr == '^' ? '*' : *argPtr);
2225 argPtr++;
2226 }
2227}
2228
2229// FIXME. Consolidate this routine with RewriteBlockPointerType.
2230void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2231 ValueDecl *VD) {
2232 QualType Type = VD->getType();
2233 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2234 const char *argPtr = TypeString.c_str();
2235 int paren = 0;
2236 while (*argPtr) {
2237 switch (*argPtr) {
2238 case '(':
2239 Str += *argPtr;
2240 paren++;
2241 break;
2242 case ')':
2243 Str += *argPtr;
2244 paren--;
2245 break;
2246 case '^':
2247 Str += '*';
2248 if (paren == 1)
2249 Str += VD->getNameAsString();
2250 break;
2251 default:
2252 Str += *argPtr;
2253 break;
2254 }
2255 argPtr++;
2256 }
2257}
2258
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002259void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2260 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2261 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2262 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2263 if (!proto)
2264 return;
2265 QualType Type = proto->getResultType();
2266 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2267 FdStr += " ";
2268 FdStr += FD->getName();
2269 FdStr += "(";
2270 unsigned numArgs = proto->getNumArgs();
2271 for (unsigned i = 0; i < numArgs; i++) {
2272 QualType ArgType = proto->getArgType(i);
2273 RewriteBlockPointerType(FdStr, ArgType);
2274 if (i+1 < numArgs)
2275 FdStr += ", ";
2276 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002277 if (FD->isVariadic()) {
2278 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2279 }
2280 else
2281 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002282 InsertText(FunLocStart, FdStr);
2283}
2284
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002285// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002286void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2287 if (SuperContructorFunctionDecl)
2288 return;
2289 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2290 SmallVector<QualType, 16> ArgTys;
2291 QualType argT = Context->getObjCIdType();
2292 assert(!argT.isNull() && "Can't find 'id' type");
2293 ArgTys.push_back(argT);
2294 ArgTys.push_back(argT);
2295 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2296 &ArgTys[0], ArgTys.size());
2297 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2298 SourceLocation(),
2299 SourceLocation(),
2300 msgSendIdent, msgSendType, 0,
2301 SC_Extern,
2302 SC_None, false);
2303}
2304
2305// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2306void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2307 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2308 SmallVector<QualType, 16> ArgTys;
2309 QualType argT = Context->getObjCIdType();
2310 assert(!argT.isNull() && "Can't find 'id' type");
2311 ArgTys.push_back(argT);
2312 argT = Context->getObjCSelType();
2313 assert(!argT.isNull() && "Can't find 'SEL' type");
2314 ArgTys.push_back(argT);
2315 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2316 &ArgTys[0], ArgTys.size(),
2317 true /*isVariadic*/);
2318 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2319 SourceLocation(),
2320 SourceLocation(),
2321 msgSendIdent, msgSendType, 0,
2322 SC_Extern,
2323 SC_None, false);
2324}
2325
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002326// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002327void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2328 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002329 SmallVector<QualType, 2> ArgTys;
2330 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002331 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002332 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002333 true /*isVariadic*/);
2334 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2335 SourceLocation(),
2336 SourceLocation(),
2337 msgSendIdent, msgSendType, 0,
2338 SC_Extern,
2339 SC_None, false);
2340}
2341
2342// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2343void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2344 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2345 SmallVector<QualType, 16> ArgTys;
2346 QualType argT = Context->getObjCIdType();
2347 assert(!argT.isNull() && "Can't find 'id' type");
2348 ArgTys.push_back(argT);
2349 argT = Context->getObjCSelType();
2350 assert(!argT.isNull() && "Can't find 'SEL' type");
2351 ArgTys.push_back(argT);
2352 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2353 &ArgTys[0], ArgTys.size(),
2354 true /*isVariadic*/);
2355 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2356 SourceLocation(),
2357 SourceLocation(),
2358 msgSendIdent, msgSendType, 0,
2359 SC_Extern,
2360 SC_None, false);
2361}
2362
2363// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002364// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002365void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2366 IdentifierInfo *msgSendIdent =
2367 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002368 SmallVector<QualType, 2> ArgTys;
2369 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002370 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002371 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002372 true /*isVariadic*/);
2373 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2374 SourceLocation(),
2375 SourceLocation(),
2376 msgSendIdent, msgSendType, 0,
2377 SC_Extern,
2378 SC_None, false);
2379}
2380
2381// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2382void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2383 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2384 SmallVector<QualType, 16> ArgTys;
2385 QualType argT = Context->getObjCIdType();
2386 assert(!argT.isNull() && "Can't find 'id' type");
2387 ArgTys.push_back(argT);
2388 argT = Context->getObjCSelType();
2389 assert(!argT.isNull() && "Can't find 'SEL' type");
2390 ArgTys.push_back(argT);
2391 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2392 &ArgTys[0], ArgTys.size(),
2393 true /*isVariadic*/);
2394 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2395 SourceLocation(),
2396 SourceLocation(),
2397 msgSendIdent, msgSendType, 0,
2398 SC_Extern,
2399 SC_None, false);
2400}
2401
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002402// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002403void RewriteModernObjC::SynthGetClassFunctionDecl() {
2404 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2405 SmallVector<QualType, 16> ArgTys;
2406 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002407 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002408 &ArgTys[0], ArgTys.size());
2409 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2410 SourceLocation(),
2411 SourceLocation(),
2412 getClassIdent, getClassType, 0,
2413 SC_Extern,
2414 SC_None, false);
2415}
2416
2417// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2418void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2419 IdentifierInfo *getSuperClassIdent =
2420 &Context->Idents.get("class_getSuperclass");
2421 SmallVector<QualType, 16> ArgTys;
2422 ArgTys.push_back(Context->getObjCClassType());
2423 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2424 &ArgTys[0], ArgTys.size());
2425 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2426 SourceLocation(),
2427 SourceLocation(),
2428 getSuperClassIdent,
2429 getClassType, 0,
2430 SC_Extern,
2431 SC_None,
2432 false);
2433}
2434
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002435// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002436void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2437 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2438 SmallVector<QualType, 16> ArgTys;
2439 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002440 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002441 &ArgTys[0], ArgTys.size());
2442 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2443 SourceLocation(),
2444 SourceLocation(),
2445 getClassIdent, getClassType, 0,
2446 SC_Extern,
2447 SC_None, false);
2448}
2449
2450Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2451 QualType strType = getConstantStringStructType();
2452
2453 std::string S = "__NSConstantStringImpl_";
2454
2455 std::string tmpName = InFileName;
2456 unsigned i;
2457 for (i=0; i < tmpName.length(); i++) {
2458 char c = tmpName.at(i);
2459 // replace any non alphanumeric characters with '_'.
2460 if (!isalpha(c) && (c < '0' || c > '9'))
2461 tmpName[i] = '_';
2462 }
2463 S += tmpName;
2464 S += "_";
2465 S += utostr(NumObjCStringLiterals++);
2466
2467 Preamble += "static __NSConstantStringImpl " + S;
2468 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2469 Preamble += "0x000007c8,"; // utf8_str
2470 // The pretty printer for StringLiteral handles escape characters properly.
2471 std::string prettyBufS;
2472 llvm::raw_string_ostream prettyBuf(prettyBufS);
2473 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2474 PrintingPolicy(LangOpts));
2475 Preamble += prettyBuf.str();
2476 Preamble += ",";
2477 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2478
2479 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2480 SourceLocation(), &Context->Idents.get(S),
2481 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002482 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002483 SourceLocation());
2484 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2485 Context->getPointerType(DRE->getType()),
2486 VK_RValue, OK_Ordinary,
2487 SourceLocation());
2488 // cast to NSConstantString *
2489 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2490 CK_CPointerToObjCPointerCast, Unop);
2491 ReplaceStmt(Exp, cast);
2492 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2493 return cast;
2494}
2495
Fariborz Jahanian55947042012-03-27 20:17:30 +00002496Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2497 unsigned IntSize =
2498 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2499
2500 Expr *FlagExp = IntegerLiteral::Create(*Context,
2501 llvm::APInt(IntSize, Exp->getValue()),
2502 Context->IntTy, Exp->getLocation());
2503 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2504 CK_BitCast, FlagExp);
2505 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2506 cast);
2507 ReplaceStmt(Exp, PE);
2508 return PE;
2509}
2510
Patrick Beardeb382ec2012-04-19 00:25:12 +00002511Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002512 // synthesize declaration of helper functions needed in this routine.
2513 if (!SelGetUidFunctionDecl)
2514 SynthSelGetUidFunctionDecl();
2515 // use objc_msgSend() for all.
2516 if (!MsgSendFunctionDecl)
2517 SynthMsgSendFunctionDecl();
2518 if (!GetClassFunctionDecl)
2519 SynthGetClassFunctionDecl();
2520
2521 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2522 SourceLocation StartLoc = Exp->getLocStart();
2523 SourceLocation EndLoc = Exp->getLocEnd();
2524
2525 // Synthesize a call to objc_msgSend().
2526 SmallVector<Expr*, 4> MsgExprs;
2527 SmallVector<Expr*, 4> ClsExprs;
2528 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002529
Patrick Beardeb382ec2012-04-19 00:25:12 +00002530 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2531 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2532 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002533
Patrick Beardeb382ec2012-04-19 00:25:12 +00002534 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002535 ClsExprs.push_back(StringLiteral::Create(*Context,
2536 clsName->getName(),
2537 StringLiteral::Ascii, false,
2538 argType, SourceLocation()));
2539 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2540 &ClsExprs[0],
2541 ClsExprs.size(),
2542 StartLoc, EndLoc);
2543 MsgExprs.push_back(Cls);
2544
Patrick Beardeb382ec2012-04-19 00:25:12 +00002545 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002546 // it will be the 2nd argument.
2547 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002548 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002549 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002550 StringLiteral::Ascii, false,
2551 argType, SourceLocation()));
2552 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2553 &SelExprs[0], SelExprs.size(),
2554 StartLoc, EndLoc);
2555 MsgExprs.push_back(SelExp);
2556
Patrick Beardeb382ec2012-04-19 00:25:12 +00002557 // User provided sub-expression is the 3rd, and last, argument.
2558 Expr *subExpr = Exp->getSubExpr();
2559 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002560 QualType type = ICE->getType();
2561 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2562 CastKind CK = CK_BitCast;
2563 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2564 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002565 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002566 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002567 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002568
2569 SmallVector<QualType, 4> ArgTypes;
2570 ArgTypes.push_back(Context->getObjCIdType());
2571 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002572 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2573 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002574 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002575
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002576 QualType returnType = Exp->getType();
2577 // Get the type, we will need to reference it in a couple spots.
2578 QualType msgSendType = MsgSendFlavor->getType();
2579
2580 // Create a reference to the objc_msgSend() declaration.
2581 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2582 VK_LValue, SourceLocation());
2583
2584 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002585 Context->getPointerType(Context->VoidTy),
2586 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002587
2588 // Now do the "normal" pointer to function cast.
2589 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002590 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2591 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002592 castType = Context->getPointerType(castType);
2593 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2594 cast);
2595
2596 // Don't forget the parens to enforce the proper binding.
2597 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2598
2599 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2600 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2601 MsgExprs.size(),
2602 FT->getResultType(), VK_RValue,
2603 EndLoc);
2604 ReplaceStmt(Exp, CE);
2605 return CE;
2606}
2607
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002608Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2609 // synthesize declaration of helper functions needed in this routine.
2610 if (!SelGetUidFunctionDecl)
2611 SynthSelGetUidFunctionDecl();
2612 // use objc_msgSend() for all.
2613 if (!MsgSendFunctionDecl)
2614 SynthMsgSendFunctionDecl();
2615 if (!GetClassFunctionDecl)
2616 SynthGetClassFunctionDecl();
2617
2618 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2619 SourceLocation StartLoc = Exp->getLocStart();
2620 SourceLocation EndLoc = Exp->getLocEnd();
2621
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002622 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002623 QualType IntQT = Context->IntTy;
2624 QualType NSArrayFType =
2625 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002626 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002627 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2628 DeclRefExpr *NSArrayDRE =
2629 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2630 SourceLocation());
2631
2632 SmallVector<Expr*, 16> InitExprs;
2633 unsigned NumElements = Exp->getNumElements();
2634 unsigned UnsignedIntSize =
2635 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2636 Expr *count = IntegerLiteral::Create(*Context,
2637 llvm::APInt(UnsignedIntSize, NumElements),
2638 Context->UnsignedIntTy, SourceLocation());
2639 InitExprs.push_back(count);
2640 for (unsigned i = 0; i < NumElements; i++)
2641 InitExprs.push_back(Exp->getElement(i));
2642 Expr *NSArrayCallExpr =
2643 new (Context) CallExpr(*Context, NSArrayDRE, &InitExprs[0], InitExprs.size(),
2644 NSArrayFType, VK_LValue, SourceLocation());
2645
2646 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2647 SourceLocation(),
2648 &Context->Idents.get("arr"),
2649 Context->getPointerType(Context->VoidPtrTy), 0,
2650 /*BitWidth=*/0, /*Mutable=*/true,
2651 /*HasInit=*/false);
2652 MemberExpr *ArrayLiteralME =
2653 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2654 SourceLocation(),
2655 ARRFD->getType(), VK_LValue,
2656 OK_Ordinary);
2657 QualType ConstIdT = Context->getObjCIdType().withConst();
2658 CStyleCastExpr * ArrayLiteralObjects =
2659 NoTypeInfoCStyleCastExpr(Context,
2660 Context->getPointerType(ConstIdT),
2661 CK_BitCast,
2662 ArrayLiteralME);
2663
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002664 // Synthesize a call to objc_msgSend().
2665 SmallVector<Expr*, 32> MsgExprs;
2666 SmallVector<Expr*, 4> ClsExprs;
2667 QualType argType = Context->getPointerType(Context->CharTy);
2668 QualType expType = Exp->getType();
2669
2670 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2671 ObjCInterfaceDecl *Class =
2672 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2673
2674 IdentifierInfo *clsName = Class->getIdentifier();
2675 ClsExprs.push_back(StringLiteral::Create(*Context,
2676 clsName->getName(),
2677 StringLiteral::Ascii, false,
2678 argType, SourceLocation()));
2679 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2680 &ClsExprs[0],
2681 ClsExprs.size(),
2682 StartLoc, EndLoc);
2683 MsgExprs.push_back(Cls);
2684
2685 // Create a call to sel_registerName("arrayWithObjects:count:").
2686 // it will be the 2nd argument.
2687 SmallVector<Expr*, 4> SelExprs;
2688 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2689 SelExprs.push_back(StringLiteral::Create(*Context,
2690 ArrayMethod->getSelector().getAsString(),
2691 StringLiteral::Ascii, false,
2692 argType, SourceLocation()));
2693 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2694 &SelExprs[0], SelExprs.size(),
2695 StartLoc, EndLoc);
2696 MsgExprs.push_back(SelExp);
2697
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002698 // (const id [])objects
2699 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002700
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002701 // (NSUInteger)cnt
2702 Expr *cnt = IntegerLiteral::Create(*Context,
2703 llvm::APInt(UnsignedIntSize, NumElements),
2704 Context->UnsignedIntTy, SourceLocation());
2705 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002706
2707
2708 SmallVector<QualType, 4> ArgTypes;
2709 ArgTypes.push_back(Context->getObjCIdType());
2710 ArgTypes.push_back(Context->getObjCSelType());
2711 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2712 E = ArrayMethod->param_end(); PI != E; ++PI)
2713 ArgTypes.push_back((*PI)->getType());
2714
2715 QualType returnType = Exp->getType();
2716 // Get the type, we will need to reference it in a couple spots.
2717 QualType msgSendType = MsgSendFlavor->getType();
2718
2719 // Create a reference to the objc_msgSend() declaration.
2720 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2721 VK_LValue, SourceLocation());
2722
2723 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2724 Context->getPointerType(Context->VoidTy),
2725 CK_BitCast, DRE);
2726
2727 // Now do the "normal" pointer to function cast.
2728 QualType castType =
2729 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2730 ArrayMethod->isVariadic());
2731 castType = Context->getPointerType(castType);
2732 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2733 cast);
2734
2735 // Don't forget the parens to enforce the proper binding.
2736 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2737
2738 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2739 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2740 MsgExprs.size(),
2741 FT->getResultType(), VK_RValue,
2742 EndLoc);
2743 ReplaceStmt(Exp, CE);
2744 return CE;
2745}
2746
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002747Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2748 // synthesize declaration of helper functions needed in this routine.
2749 if (!SelGetUidFunctionDecl)
2750 SynthSelGetUidFunctionDecl();
2751 // use objc_msgSend() for all.
2752 if (!MsgSendFunctionDecl)
2753 SynthMsgSendFunctionDecl();
2754 if (!GetClassFunctionDecl)
2755 SynthGetClassFunctionDecl();
2756
2757 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2758 SourceLocation StartLoc = Exp->getLocStart();
2759 SourceLocation EndLoc = Exp->getLocEnd();
2760
2761 // Build the expression: __NSContainer_literal(int, ...).arr
2762 QualType IntQT = Context->IntTy;
2763 QualType NSDictFType =
2764 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2765 std::string NSDictFName("__NSContainer_literal");
2766 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2767 DeclRefExpr *NSDictDRE =
2768 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2769 SourceLocation());
2770
2771 SmallVector<Expr*, 16> KeyExprs;
2772 SmallVector<Expr*, 16> ValueExprs;
2773
2774 unsigned NumElements = Exp->getNumElements();
2775 unsigned UnsignedIntSize =
2776 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2777 Expr *count = IntegerLiteral::Create(*Context,
2778 llvm::APInt(UnsignedIntSize, NumElements),
2779 Context->UnsignedIntTy, SourceLocation());
2780 KeyExprs.push_back(count);
2781 ValueExprs.push_back(count);
2782 for (unsigned i = 0; i < NumElements; i++) {
2783 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2784 KeyExprs.push_back(Element.Key);
2785 ValueExprs.push_back(Element.Value);
2786 }
2787
2788 // (const id [])objects
2789 Expr *NSValueCallExpr =
2790 new (Context) CallExpr(*Context, NSDictDRE, &ValueExprs[0], ValueExprs.size(),
2791 NSDictFType, VK_LValue, SourceLocation());
2792
2793 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2794 SourceLocation(),
2795 &Context->Idents.get("arr"),
2796 Context->getPointerType(Context->VoidPtrTy), 0,
2797 /*BitWidth=*/0, /*Mutable=*/true,
2798 /*HasInit=*/false);
2799 MemberExpr *DictLiteralValueME =
2800 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2801 SourceLocation(),
2802 ARRFD->getType(), VK_LValue,
2803 OK_Ordinary);
2804 QualType ConstIdT = Context->getObjCIdType().withConst();
2805 CStyleCastExpr * DictValueObjects =
2806 NoTypeInfoCStyleCastExpr(Context,
2807 Context->getPointerType(ConstIdT),
2808 CK_BitCast,
2809 DictLiteralValueME);
2810 // (const id <NSCopying> [])keys
2811 Expr *NSKeyCallExpr =
2812 new (Context) CallExpr(*Context, NSDictDRE, &KeyExprs[0], KeyExprs.size(),
2813 NSDictFType, VK_LValue, SourceLocation());
2814
2815 MemberExpr *DictLiteralKeyME =
2816 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2817 SourceLocation(),
2818 ARRFD->getType(), VK_LValue,
2819 OK_Ordinary);
2820
2821 CStyleCastExpr * DictKeyObjects =
2822 NoTypeInfoCStyleCastExpr(Context,
2823 Context->getPointerType(ConstIdT),
2824 CK_BitCast,
2825 DictLiteralKeyME);
2826
2827
2828
2829 // Synthesize a call to objc_msgSend().
2830 SmallVector<Expr*, 32> MsgExprs;
2831 SmallVector<Expr*, 4> ClsExprs;
2832 QualType argType = Context->getPointerType(Context->CharTy);
2833 QualType expType = Exp->getType();
2834
2835 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2836 ObjCInterfaceDecl *Class =
2837 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2838
2839 IdentifierInfo *clsName = Class->getIdentifier();
2840 ClsExprs.push_back(StringLiteral::Create(*Context,
2841 clsName->getName(),
2842 StringLiteral::Ascii, false,
2843 argType, SourceLocation()));
2844 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2845 &ClsExprs[0],
2846 ClsExprs.size(),
2847 StartLoc, EndLoc);
2848 MsgExprs.push_back(Cls);
2849
2850 // Create a call to sel_registerName("arrayWithObjects:count:").
2851 // it will be the 2nd argument.
2852 SmallVector<Expr*, 4> SelExprs;
2853 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2854 SelExprs.push_back(StringLiteral::Create(*Context,
2855 DictMethod->getSelector().getAsString(),
2856 StringLiteral::Ascii, false,
2857 argType, SourceLocation()));
2858 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2859 &SelExprs[0], SelExprs.size(),
2860 StartLoc, EndLoc);
2861 MsgExprs.push_back(SelExp);
2862
2863 // (const id [])objects
2864 MsgExprs.push_back(DictValueObjects);
2865
2866 // (const id <NSCopying> [])keys
2867 MsgExprs.push_back(DictKeyObjects);
2868
2869 // (NSUInteger)cnt
2870 Expr *cnt = IntegerLiteral::Create(*Context,
2871 llvm::APInt(UnsignedIntSize, NumElements),
2872 Context->UnsignedIntTy, SourceLocation());
2873 MsgExprs.push_back(cnt);
2874
2875
2876 SmallVector<QualType, 8> ArgTypes;
2877 ArgTypes.push_back(Context->getObjCIdType());
2878 ArgTypes.push_back(Context->getObjCSelType());
2879 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2880 E = DictMethod->param_end(); PI != E; ++PI) {
2881 QualType T = (*PI)->getType();
2882 if (const PointerType* PT = T->getAs<PointerType>()) {
2883 QualType PointeeTy = PT->getPointeeType();
2884 convertToUnqualifiedObjCType(PointeeTy);
2885 T = Context->getPointerType(PointeeTy);
2886 }
2887 ArgTypes.push_back(T);
2888 }
2889
2890 QualType returnType = Exp->getType();
2891 // Get the type, we will need to reference it in a couple spots.
2892 QualType msgSendType = MsgSendFlavor->getType();
2893
2894 // Create a reference to the objc_msgSend() declaration.
2895 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2896 VK_LValue, SourceLocation());
2897
2898 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2899 Context->getPointerType(Context->VoidTy),
2900 CK_BitCast, DRE);
2901
2902 // Now do the "normal" pointer to function cast.
2903 QualType castType =
2904 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2905 DictMethod->isVariadic());
2906 castType = Context->getPointerType(castType);
2907 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2908 cast);
2909
2910 // Don't forget the parens to enforce the proper binding.
2911 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2912
2913 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2914 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2915 MsgExprs.size(),
2916 FT->getResultType(), VK_RValue,
2917 EndLoc);
2918 ReplaceStmt(Exp, CE);
2919 return CE;
2920}
2921
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002922// struct __rw_objc_super {
2923// struct objc_object *object; struct objc_object *superClass;
2924// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002925QualType RewriteModernObjC::getSuperStructType() {
2926 if (!SuperStructDecl) {
2927 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2928 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002929 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002930 QualType FieldTypes[2];
2931
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002932 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002933 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002934 // struct objc_object *superClass;
2935 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002936
2937 // Create fields
2938 for (unsigned i = 0; i < 2; ++i) {
2939 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2940 SourceLocation(),
2941 SourceLocation(), 0,
2942 FieldTypes[i], 0,
2943 /*BitWidth=*/0,
2944 /*Mutable=*/false,
2945 /*HasInit=*/false));
2946 }
2947
2948 SuperStructDecl->completeDefinition();
2949 }
2950 return Context->getTagDeclType(SuperStructDecl);
2951}
2952
2953QualType RewriteModernObjC::getConstantStringStructType() {
2954 if (!ConstantStringDecl) {
2955 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2956 SourceLocation(), SourceLocation(),
2957 &Context->Idents.get("__NSConstantStringImpl"));
2958 QualType FieldTypes[4];
2959
2960 // struct objc_object *receiver;
2961 FieldTypes[0] = Context->getObjCIdType();
2962 // int flags;
2963 FieldTypes[1] = Context->IntTy;
2964 // char *str;
2965 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2966 // long length;
2967 FieldTypes[3] = Context->LongTy;
2968
2969 // Create fields
2970 for (unsigned i = 0; i < 4; ++i) {
2971 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2972 ConstantStringDecl,
2973 SourceLocation(),
2974 SourceLocation(), 0,
2975 FieldTypes[i], 0,
2976 /*BitWidth=*/0,
2977 /*Mutable=*/true,
2978 /*HasInit=*/false));
2979 }
2980
2981 ConstantStringDecl->completeDefinition();
2982 }
2983 return Context->getTagDeclType(ConstantStringDecl);
2984}
2985
2986Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2987 SourceLocation StartLoc,
2988 SourceLocation EndLoc) {
2989 if (!SelGetUidFunctionDecl)
2990 SynthSelGetUidFunctionDecl();
2991 if (!MsgSendFunctionDecl)
2992 SynthMsgSendFunctionDecl();
2993 if (!MsgSendSuperFunctionDecl)
2994 SynthMsgSendSuperFunctionDecl();
2995 if (!MsgSendStretFunctionDecl)
2996 SynthMsgSendStretFunctionDecl();
2997 if (!MsgSendSuperStretFunctionDecl)
2998 SynthMsgSendSuperStretFunctionDecl();
2999 if (!MsgSendFpretFunctionDecl)
3000 SynthMsgSendFpretFunctionDecl();
3001 if (!GetClassFunctionDecl)
3002 SynthGetClassFunctionDecl();
3003 if (!GetSuperClassFunctionDecl)
3004 SynthGetSuperClassFunctionDecl();
3005 if (!GetMetaClassFunctionDecl)
3006 SynthGetMetaClassFunctionDecl();
3007
3008 // default to objc_msgSend().
3009 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3010 // May need to use objc_msgSend_stret() as well.
3011 FunctionDecl *MsgSendStretFlavor = 0;
3012 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3013 QualType resultType = mDecl->getResultType();
3014 if (resultType->isRecordType())
3015 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3016 else if (resultType->isRealFloatingType())
3017 MsgSendFlavor = MsgSendFpretFunctionDecl;
3018 }
3019
3020 // Synthesize a call to objc_msgSend().
3021 SmallVector<Expr*, 8> MsgExprs;
3022 switch (Exp->getReceiverKind()) {
3023 case ObjCMessageExpr::SuperClass: {
3024 MsgSendFlavor = MsgSendSuperFunctionDecl;
3025 if (MsgSendStretFlavor)
3026 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3027 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3028
3029 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3030
3031 SmallVector<Expr*, 4> InitExprs;
3032
3033 // set the receiver to self, the first argument to all methods.
3034 InitExprs.push_back(
3035 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3036 CK_BitCast,
3037 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003038 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003039 Context->getObjCIdType(),
3040 VK_RValue,
3041 SourceLocation()))
3042 ); // set the 'receiver'.
3043
3044 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3045 SmallVector<Expr*, 8> ClsExprs;
3046 QualType argType = Context->getPointerType(Context->CharTy);
3047 ClsExprs.push_back(StringLiteral::Create(*Context,
3048 ClassDecl->getIdentifier()->getName(),
3049 StringLiteral::Ascii, false,
3050 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003051 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003052 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3053 &ClsExprs[0],
3054 ClsExprs.size(),
3055 StartLoc,
3056 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003057 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003058 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003059 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3060 &ClsExprs[0], ClsExprs.size(),
3061 StartLoc, EndLoc);
3062
3063 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3064 // To turn off a warning, type-cast to 'id'
3065 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3066 NoTypeInfoCStyleCastExpr(Context,
3067 Context->getObjCIdType(),
3068 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003069 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003070 QualType superType = getSuperStructType();
3071 Expr *SuperRep;
3072
3073 if (LangOpts.MicrosoftExt) {
3074 SynthSuperContructorFunctionDecl();
3075 // Simulate a contructor call...
3076 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003077 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003078 SourceLocation());
3079 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3080 InitExprs.size(),
3081 superType, VK_LValue,
3082 SourceLocation());
3083 // The code for super is a little tricky to prevent collision with
3084 // the structure definition in the header. The rewriter has it's own
3085 // internal definition (__rw_objc_super) that is uses. This is why
3086 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003087 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003088 //
3089 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3090 Context->getPointerType(SuperRep->getType()),
3091 VK_RValue, OK_Ordinary,
3092 SourceLocation());
3093 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3094 Context->getPointerType(superType),
3095 CK_BitCast, SuperRep);
3096 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003097 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003098 InitListExpr *ILE =
3099 new (Context) InitListExpr(*Context, SourceLocation(),
3100 &InitExprs[0], InitExprs.size(),
3101 SourceLocation());
3102 TypeSourceInfo *superTInfo
3103 = Context->getTrivialTypeSourceInfo(superType);
3104 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3105 superType, VK_LValue,
3106 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003107 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003108 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3109 Context->getPointerType(SuperRep->getType()),
3110 VK_RValue, OK_Ordinary,
3111 SourceLocation());
3112 }
3113 MsgExprs.push_back(SuperRep);
3114 break;
3115 }
3116
3117 case ObjCMessageExpr::Class: {
3118 SmallVector<Expr*, 8> ClsExprs;
3119 QualType argType = Context->getPointerType(Context->CharTy);
3120 ObjCInterfaceDecl *Class
3121 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3122 IdentifierInfo *clsName = Class->getIdentifier();
3123 ClsExprs.push_back(StringLiteral::Create(*Context,
3124 clsName->getName(),
3125 StringLiteral::Ascii, false,
3126 argType, SourceLocation()));
3127 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3128 &ClsExprs[0],
3129 ClsExprs.size(),
3130 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003131 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3132 Context->getObjCIdType(),
3133 CK_BitCast, Cls);
3134 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003135 break;
3136 }
3137
3138 case ObjCMessageExpr::SuperInstance:{
3139 MsgSendFlavor = MsgSendSuperFunctionDecl;
3140 if (MsgSendStretFlavor)
3141 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3142 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3143 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3144 SmallVector<Expr*, 4> InitExprs;
3145
3146 InitExprs.push_back(
3147 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3148 CK_BitCast,
3149 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003150 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003151 Context->getObjCIdType(),
3152 VK_RValue, SourceLocation()))
3153 ); // set the 'receiver'.
3154
3155 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3156 SmallVector<Expr*, 8> ClsExprs;
3157 QualType argType = Context->getPointerType(Context->CharTy);
3158 ClsExprs.push_back(StringLiteral::Create(*Context,
3159 ClassDecl->getIdentifier()->getName(),
3160 StringLiteral::Ascii, false, argType,
3161 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003162 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003163 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3164 &ClsExprs[0],
3165 ClsExprs.size(),
3166 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003167 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003168 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003169 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3170 &ClsExprs[0], ClsExprs.size(),
3171 StartLoc, EndLoc);
3172
3173 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3174 // To turn off a warning, type-cast to 'id'
3175 InitExprs.push_back(
3176 // set 'super class', using class_getSuperclass().
3177 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3178 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003179 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003180 QualType superType = getSuperStructType();
3181 Expr *SuperRep;
3182
3183 if (LangOpts.MicrosoftExt) {
3184 SynthSuperContructorFunctionDecl();
3185 // Simulate a contructor call...
3186 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003187 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003188 SourceLocation());
3189 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3190 InitExprs.size(),
3191 superType, VK_LValue, SourceLocation());
3192 // The code for super is a little tricky to prevent collision with
3193 // the structure definition in the header. The rewriter has it's own
3194 // internal definition (__rw_objc_super) that is uses. This is why
3195 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003196 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003197 //
3198 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3199 Context->getPointerType(SuperRep->getType()),
3200 VK_RValue, OK_Ordinary,
3201 SourceLocation());
3202 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3203 Context->getPointerType(superType),
3204 CK_BitCast, SuperRep);
3205 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003206 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003207 InitListExpr *ILE =
3208 new (Context) InitListExpr(*Context, SourceLocation(),
3209 &InitExprs[0], InitExprs.size(),
3210 SourceLocation());
3211 TypeSourceInfo *superTInfo
3212 = Context->getTrivialTypeSourceInfo(superType);
3213 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3214 superType, VK_RValue, ILE,
3215 false);
3216 }
3217 MsgExprs.push_back(SuperRep);
3218 break;
3219 }
3220
3221 case ObjCMessageExpr::Instance: {
3222 // Remove all type-casts because it may contain objc-style types; e.g.
3223 // Foo<Proto> *.
3224 Expr *recExpr = Exp->getInstanceReceiver();
3225 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3226 recExpr = CE->getSubExpr();
3227 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3228 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3229 ? CK_BlockPointerToObjCPointerCast
3230 : CK_CPointerToObjCPointerCast;
3231
3232 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3233 CK, recExpr);
3234 MsgExprs.push_back(recExpr);
3235 break;
3236 }
3237 }
3238
3239 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3240 SmallVector<Expr*, 8> SelExprs;
3241 QualType argType = Context->getPointerType(Context->CharTy);
3242 SelExprs.push_back(StringLiteral::Create(*Context,
3243 Exp->getSelector().getAsString(),
3244 StringLiteral::Ascii, false,
3245 argType, SourceLocation()));
3246 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3247 &SelExprs[0], SelExprs.size(),
3248 StartLoc,
3249 EndLoc);
3250 MsgExprs.push_back(SelExp);
3251
3252 // Now push any user supplied arguments.
3253 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3254 Expr *userExpr = Exp->getArg(i);
3255 // Make all implicit casts explicit...ICE comes in handy:-)
3256 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3257 // Reuse the ICE type, it is exactly what the doctor ordered.
3258 QualType type = ICE->getType();
3259 if (needToScanForQualifiers(type))
3260 type = Context->getObjCIdType();
3261 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3262 (void)convertBlockPointerToFunctionPointer(type);
3263 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3264 CastKind CK;
3265 if (SubExpr->getType()->isIntegralType(*Context) &&
3266 type->isBooleanType()) {
3267 CK = CK_IntegralToBoolean;
3268 } else if (type->isObjCObjectPointerType()) {
3269 if (SubExpr->getType()->isBlockPointerType()) {
3270 CK = CK_BlockPointerToObjCPointerCast;
3271 } else if (SubExpr->getType()->isPointerType()) {
3272 CK = CK_CPointerToObjCPointerCast;
3273 } else {
3274 CK = CK_BitCast;
3275 }
3276 } else {
3277 CK = CK_BitCast;
3278 }
3279
3280 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3281 }
3282 // Make id<P...> cast into an 'id' cast.
3283 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3284 if (CE->getType()->isObjCQualifiedIdType()) {
3285 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3286 userExpr = CE->getSubExpr();
3287 CastKind CK;
3288 if (userExpr->getType()->isIntegralType(*Context)) {
3289 CK = CK_IntegralToPointer;
3290 } else if (userExpr->getType()->isBlockPointerType()) {
3291 CK = CK_BlockPointerToObjCPointerCast;
3292 } else if (userExpr->getType()->isPointerType()) {
3293 CK = CK_CPointerToObjCPointerCast;
3294 } else {
3295 CK = CK_BitCast;
3296 }
3297 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3298 CK, userExpr);
3299 }
3300 }
3301 MsgExprs.push_back(userExpr);
3302 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3303 // out the argument in the original expression (since we aren't deleting
3304 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3305 //Exp->setArg(i, 0);
3306 }
3307 // Generate the funky cast.
3308 CastExpr *cast;
3309 SmallVector<QualType, 8> ArgTypes;
3310 QualType returnType;
3311
3312 // Push 'id' and 'SEL', the 2 implicit arguments.
3313 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3314 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3315 else
3316 ArgTypes.push_back(Context->getObjCIdType());
3317 ArgTypes.push_back(Context->getObjCSelType());
3318 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3319 // Push any user argument types.
3320 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3321 E = OMD->param_end(); PI != E; ++PI) {
3322 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3323 ? Context->getObjCIdType()
3324 : (*PI)->getType();
3325 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3326 (void)convertBlockPointerToFunctionPointer(t);
3327 ArgTypes.push_back(t);
3328 }
3329 returnType = Exp->getType();
3330 convertToUnqualifiedObjCType(returnType);
3331 (void)convertBlockPointerToFunctionPointer(returnType);
3332 } else {
3333 returnType = Context->getObjCIdType();
3334 }
3335 // Get the type, we will need to reference it in a couple spots.
3336 QualType msgSendType = MsgSendFlavor->getType();
3337
3338 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003339 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003340 VK_LValue, SourceLocation());
3341
3342 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3343 // If we don't do this cast, we get the following bizarre warning/note:
3344 // xx.m:13: warning: function called through a non-compatible type
3345 // xx.m:13: note: if this code is reached, the program will abort
3346 cast = NoTypeInfoCStyleCastExpr(Context,
3347 Context->getPointerType(Context->VoidTy),
3348 CK_BitCast, DRE);
3349
3350 // Now do the "normal" pointer to function cast.
3351 QualType castType =
3352 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3353 // If we don't have a method decl, force a variadic cast.
3354 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3355 castType = Context->getPointerType(castType);
3356 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3357 cast);
3358
3359 // Don't forget the parens to enforce the proper binding.
3360 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3361
3362 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3363 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3364 MsgExprs.size(),
3365 FT->getResultType(), VK_RValue,
3366 EndLoc);
3367 Stmt *ReplacingStmt = CE;
3368 if (MsgSendStretFlavor) {
3369 // We have the method which returns a struct/union. Must also generate
3370 // call to objc_msgSend_stret and hang both varieties on a conditional
3371 // expression which dictate which one to envoke depending on size of
3372 // method's return type.
3373
3374 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003375 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3376 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003377 VK_LValue, SourceLocation());
3378 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3379 cast = NoTypeInfoCStyleCastExpr(Context,
3380 Context->getPointerType(Context->VoidTy),
3381 CK_BitCast, STDRE);
3382 // Now do the "normal" pointer to function cast.
3383 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3384 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3385 castType = Context->getPointerType(castType);
3386 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3387 cast);
3388
3389 // Don't forget the parens to enforce the proper binding.
3390 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3391
3392 FT = msgSendType->getAs<FunctionType>();
3393 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3394 MsgExprs.size(),
3395 FT->getResultType(), VK_RValue,
3396 SourceLocation());
3397
3398 // Build sizeof(returnType)
3399 UnaryExprOrTypeTraitExpr *sizeofExpr =
3400 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3401 Context->getTrivialTypeSourceInfo(returnType),
3402 Context->getSizeType(), SourceLocation(),
3403 SourceLocation());
3404 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3405 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3406 // For X86 it is more complicated and some kind of target specific routine
3407 // is needed to decide what to do.
3408 unsigned IntSize =
3409 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3410 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3411 llvm::APInt(IntSize, 8),
3412 Context->IntTy,
3413 SourceLocation());
3414 BinaryOperator *lessThanExpr =
3415 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3416 VK_RValue, OK_Ordinary, SourceLocation());
3417 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3418 ConditionalOperator *CondExpr =
3419 new (Context) ConditionalOperator(lessThanExpr,
3420 SourceLocation(), CE,
3421 SourceLocation(), STCE,
3422 returnType, VK_RValue, OK_Ordinary);
3423 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3424 CondExpr);
3425 }
3426 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3427 return ReplacingStmt;
3428}
3429
3430Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3431 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3432 Exp->getLocEnd());
3433
3434 // Now do the actual rewrite.
3435 ReplaceStmt(Exp, ReplacingStmt);
3436
3437 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3438 return ReplacingStmt;
3439}
3440
3441// typedef struct objc_object Protocol;
3442QualType RewriteModernObjC::getProtocolType() {
3443 if (!ProtocolTypeDecl) {
3444 TypeSourceInfo *TInfo
3445 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3446 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3447 SourceLocation(), SourceLocation(),
3448 &Context->Idents.get("Protocol"),
3449 TInfo);
3450 }
3451 return Context->getTypeDeclType(ProtocolTypeDecl);
3452}
3453
3454/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3455/// a synthesized/forward data reference (to the protocol's metadata).
3456/// The forward references (and metadata) are generated in
3457/// RewriteModernObjC::HandleTranslationUnit().
3458Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003459 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3460 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003461 IdentifierInfo *ID = &Context->Idents.get(Name);
3462 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3463 SourceLocation(), ID, getProtocolType(), 0,
3464 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003465 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3466 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003467 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3468 Context->getPointerType(DRE->getType()),
3469 VK_RValue, OK_Ordinary, SourceLocation());
3470 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3471 CK_BitCast,
3472 DerefExpr);
3473 ReplaceStmt(Exp, castExpr);
3474 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3475 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3476 return castExpr;
3477
3478}
3479
3480bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3481 const char *endBuf) {
3482 while (startBuf < endBuf) {
3483 if (*startBuf == '#') {
3484 // Skip whitespace.
3485 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3486 ;
3487 if (!strncmp(startBuf, "if", strlen("if")) ||
3488 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3489 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3490 !strncmp(startBuf, "define", strlen("define")) ||
3491 !strncmp(startBuf, "undef", strlen("undef")) ||
3492 !strncmp(startBuf, "else", strlen("else")) ||
3493 !strncmp(startBuf, "elif", strlen("elif")) ||
3494 !strncmp(startBuf, "endif", strlen("endif")) ||
3495 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3496 !strncmp(startBuf, "include", strlen("include")) ||
3497 !strncmp(startBuf, "import", strlen("import")) ||
3498 !strncmp(startBuf, "include_next", strlen("include_next")))
3499 return true;
3500 }
3501 startBuf++;
3502 }
3503 return false;
3504}
3505
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003506/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3507/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003508bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003509 TagDecl *Tag,
3510 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003511 if (!IDecl)
3512 return false;
3513 SourceLocation TagLocation;
3514 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3515 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003516 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003517 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003518 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003519 TagLocation = RD->getLocation();
3520 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003521 IDecl->getLocation(), TagLocation);
3522 }
3523 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3524 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3525 return false;
3526 IsNamedDefinition = true;
3527 TagLocation = ED->getLocation();
3528 return Context->getSourceManager().isBeforeInTranslationUnit(
3529 IDecl->getLocation(), TagLocation);
3530
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003531 }
3532 return false;
3533}
3534
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003535/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003536/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003537bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3538 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003539 if (isa<TypedefType>(Type)) {
3540 Result += "\t";
3541 return false;
3542 }
3543
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003544 if (Type->isArrayType()) {
3545 QualType ElemTy = Context->getBaseElementType(Type);
3546 return RewriteObjCFieldDeclType(ElemTy, Result);
3547 }
3548 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003549 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3550 if (RD->isCompleteDefinition()) {
3551 if (RD->isStruct())
3552 Result += "\n\tstruct ";
3553 else if (RD->isUnion())
3554 Result += "\n\tunion ";
3555 else
3556 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003557
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003558 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003559 if (GlobalDefinedTags.count(RD)) {
3560 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003561 Result += " ";
3562 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003563 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003564 Result += " {\n";
3565 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003566 e = RD->field_end(); i != e; ++i) {
David Blaikie262bc182012-04-30 02:36:29 +00003567 FieldDecl *FD = &*i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003568 RewriteObjCFieldDecl(FD, Result);
3569 }
3570 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003571 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003572 }
3573 }
3574 else if (Type->isEnumeralType()) {
3575 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3576 if (ED->isCompleteDefinition()) {
3577 Result += "\n\tenum ";
3578 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003579 if (GlobalDefinedTags.count(ED)) {
3580 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003581 Result += " ";
3582 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003583 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003584
3585 Result += " {\n";
3586 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3587 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3588 Result += "\t"; Result += EC->getName(); Result += " = ";
3589 llvm::APSInt Val = EC->getInitVal();
3590 Result += Val.toString(10);
3591 Result += ",\n";
3592 }
3593 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003594 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003595 }
3596 }
3597
3598 Result += "\t";
3599 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003600 return false;
3601}
3602
3603
3604/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3605/// It handles elaborated types, as well as enum types in the process.
3606void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3607 std::string &Result) {
3608 QualType Type = fieldDecl->getType();
3609 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003610
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003611 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3612 if (!EleboratedType)
3613 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003614 Result += Name;
3615 if (fieldDecl->isBitField()) {
3616 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3617 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003618 else if (EleboratedType && Type->isArrayType()) {
3619 CanQualType CType = Context->getCanonicalType(Type);
3620 while (isa<ArrayType>(CType)) {
3621 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3622 Result += "[";
3623 llvm::APInt Dim = CAT->getSize();
3624 Result += utostr(Dim.getZExtValue());
3625 Result += "]";
3626 }
3627 CType = CType->getAs<ArrayType>()->getElementType();
3628 }
3629 }
3630
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003631 Result += ";\n";
3632}
3633
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003634/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3635/// named aggregate types into the input buffer.
3636void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3637 std::string &Result) {
3638 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003639 if (isa<TypedefType>(Type))
3640 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003641 if (Type->isArrayType())
3642 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003643 ObjCContainerDecl *IDecl =
3644 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003645
3646 TagDecl *TD = 0;
3647 if (Type->isRecordType()) {
3648 TD = Type->getAs<RecordType>()->getDecl();
3649 }
3650 else if (Type->isEnumeralType()) {
3651 TD = Type->getAs<EnumType>()->getDecl();
3652 }
3653
3654 if (TD) {
3655 if (GlobalDefinedTags.count(TD))
3656 return;
3657
3658 bool IsNamedDefinition = false;
3659 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3660 RewriteObjCFieldDeclType(Type, Result);
3661 Result += ";";
3662 }
3663 if (IsNamedDefinition)
3664 GlobalDefinedTags.insert(TD);
3665 }
3666
3667}
3668
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003669/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3670/// an objective-c class with ivars.
3671void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3672 std::string &Result) {
3673 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3674 assert(CDecl->getName() != "" &&
3675 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003676 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003677 SmallVector<ObjCIvarDecl *, 8> IVars;
3678 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003679 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003680 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003681
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003682 SourceLocation LocStart = CDecl->getLocStart();
3683 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003684
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003685 const char *startBuf = SM->getCharacterData(LocStart);
3686 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003687
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003688 // If no ivars and no root or if its root, directly or indirectly,
3689 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003690 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003691 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3692 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3693 ReplaceText(LocStart, endBuf-startBuf, Result);
3694 return;
3695 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003696
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003697 // Insert named struct/union definitions inside class to
3698 // outer scope. This follows semantics of locally defined
3699 // struct/unions in objective-c classes.
3700 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3701 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3702
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003703 Result += "\nstruct ";
3704 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003705 Result += "_IMPL {\n";
3706
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003707 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003708 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3709 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3710 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003711 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003712
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003713 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3714 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003715
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003716 Result += "};\n";
3717 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3718 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003719 // Mark this struct as having been generated.
3720 if (!ObjCSynthesizedStructs.insert(CDecl))
3721 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003722}
3723
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003724static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3725 ObjCIvarDecl *IvarDecl, std::string &Result) {
3726 Result += "OBJC_IVAR_$_";
3727 Result += IDecl->getName();
3728 Result += "$";
3729 Result += IvarDecl->getName();
3730}
3731
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003732/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3733/// have been referenced in an ivar access expression.
3734void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3735 std::string &Result) {
3736 // write out ivar offset symbols which have been referenced in an ivar
3737 // access expression.
3738 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3739 if (Ivars.empty())
3740 return;
3741 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3742 e = Ivars.end(); i != e; i++) {
3743 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003744 Result += "\n";
3745 if (LangOpts.MicrosoftExt)
3746 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003747 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003748 if (LangOpts.MicrosoftExt &&
3749 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003750 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3751 Result += "__declspec(dllimport) ";
3752
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003753 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003754 WriteInternalIvarName(CDecl, IvarDecl, Result);
3755 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003756 }
3757}
3758
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003759//===----------------------------------------------------------------------===//
3760// Meta Data Emission
3761//===----------------------------------------------------------------------===//
3762
3763
3764/// RewriteImplementations - This routine rewrites all method implementations
3765/// and emits meta-data.
3766
3767void RewriteModernObjC::RewriteImplementations() {
3768 int ClsDefCount = ClassImplementation.size();
3769 int CatDefCount = CategoryImplementation.size();
3770
3771 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003772 for (int i = 0; i < ClsDefCount; i++) {
3773 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3774 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3775 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003776 assert(false &&
3777 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003778 RewriteImplementationDecl(OIMP);
3779 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003780
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003781 for (int i = 0; i < CatDefCount; i++) {
3782 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3783 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3784 if (CDecl->isImplicitInterfaceDecl())
3785 assert(false &&
3786 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003787 RewriteImplementationDecl(CIMP);
3788 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003789}
3790
3791void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3792 const std::string &Name,
3793 ValueDecl *VD, bool def) {
3794 assert(BlockByRefDeclNo.count(VD) &&
3795 "RewriteByRefString: ByRef decl missing");
3796 if (def)
3797 ResultStr += "struct ";
3798 ResultStr += "__Block_byref_" + Name +
3799 "_" + utostr(BlockByRefDeclNo[VD]) ;
3800}
3801
3802static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3803 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3804 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3805 return false;
3806}
3807
3808std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3809 StringRef funcName,
3810 std::string Tag) {
3811 const FunctionType *AFT = CE->getFunctionType();
3812 QualType RT = AFT->getResultType();
3813 std::string StructRef = "struct " + Tag;
3814 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003815 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003816
3817 BlockDecl *BD = CE->getBlockDecl();
3818
3819 if (isa<FunctionNoProtoType>(AFT)) {
3820 // No user-supplied arguments. Still need to pass in a pointer to the
3821 // block (to reference imported block decl refs).
3822 S += "(" + StructRef + " *__cself)";
3823 } else if (BD->param_empty()) {
3824 S += "(" + StructRef + " *__cself)";
3825 } else {
3826 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3827 assert(FT && "SynthesizeBlockFunc: No function proto");
3828 S += '(';
3829 // first add the implicit argument.
3830 S += StructRef + " *__cself, ";
3831 std::string ParamStr;
3832 for (BlockDecl::param_iterator AI = BD->param_begin(),
3833 E = BD->param_end(); AI != E; ++AI) {
3834 if (AI != BD->param_begin()) S += ", ";
3835 ParamStr = (*AI)->getNameAsString();
3836 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003837 (void)convertBlockPointerToFunctionPointer(QT);
3838 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003839 S += ParamStr;
3840 }
3841 if (FT->isVariadic()) {
3842 if (!BD->param_empty()) S += ", ";
3843 S += "...";
3844 }
3845 S += ')';
3846 }
3847 S += " {\n";
3848
3849 // Create local declarations to avoid rewriting all closure decl ref exprs.
3850 // First, emit a declaration for all "by ref" decls.
3851 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3852 E = BlockByRefDecls.end(); I != E; ++I) {
3853 S += " ";
3854 std::string Name = (*I)->getNameAsString();
3855 std::string TypeString;
3856 RewriteByRefString(TypeString, Name, (*I));
3857 TypeString += " *";
3858 Name = TypeString + Name;
3859 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3860 }
3861 // Next, emit a declaration for all "by copy" declarations.
3862 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3863 E = BlockByCopyDecls.end(); I != E; ++I) {
3864 S += " ";
3865 // Handle nested closure invocation. For example:
3866 //
3867 // void (^myImportedClosure)(void);
3868 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3869 //
3870 // void (^anotherClosure)(void);
3871 // anotherClosure = ^(void) {
3872 // myImportedClosure(); // import and invoke the closure
3873 // };
3874 //
3875 if (isTopLevelBlockPointerType((*I)->getType())) {
3876 RewriteBlockPointerTypeVariable(S, (*I));
3877 S += " = (";
3878 RewriteBlockPointerType(S, (*I)->getType());
3879 S += ")";
3880 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3881 }
3882 else {
3883 std::string Name = (*I)->getNameAsString();
3884 QualType QT = (*I)->getType();
3885 if (HasLocalVariableExternalStorage(*I))
3886 QT = Context->getPointerType(QT);
3887 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3888 S += Name + " = __cself->" +
3889 (*I)->getNameAsString() + "; // bound by copy\n";
3890 }
3891 }
3892 std::string RewrittenStr = RewrittenBlockExprs[CE];
3893 const char *cstr = RewrittenStr.c_str();
3894 while (*cstr++ != '{') ;
3895 S += cstr;
3896 S += "\n";
3897 return S;
3898}
3899
3900std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3901 StringRef funcName,
3902 std::string Tag) {
3903 std::string StructRef = "struct " + Tag;
3904 std::string S = "static void __";
3905
3906 S += funcName;
3907 S += "_block_copy_" + utostr(i);
3908 S += "(" + StructRef;
3909 S += "*dst, " + StructRef;
3910 S += "*src) {";
3911 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3912 E = ImportedBlockDecls.end(); I != E; ++I) {
3913 ValueDecl *VD = (*I);
3914 S += "_Block_object_assign((void*)&dst->";
3915 S += (*I)->getNameAsString();
3916 S += ", (void*)src->";
3917 S += (*I)->getNameAsString();
3918 if (BlockByRefDeclsPtrSet.count((*I)))
3919 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3920 else if (VD->getType()->isBlockPointerType())
3921 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3922 else
3923 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3924 }
3925 S += "}\n";
3926
3927 S += "\nstatic void __";
3928 S += funcName;
3929 S += "_block_dispose_" + utostr(i);
3930 S += "(" + StructRef;
3931 S += "*src) {";
3932 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3933 E = ImportedBlockDecls.end(); I != E; ++I) {
3934 ValueDecl *VD = (*I);
3935 S += "_Block_object_dispose((void*)src->";
3936 S += (*I)->getNameAsString();
3937 if (BlockByRefDeclsPtrSet.count((*I)))
3938 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3939 else if (VD->getType()->isBlockPointerType())
3940 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3941 else
3942 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3943 }
3944 S += "}\n";
3945 return S;
3946}
3947
3948std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3949 std::string Desc) {
3950 std::string S = "\nstruct " + Tag;
3951 std::string Constructor = " " + Tag;
3952
3953 S += " {\n struct __block_impl impl;\n";
3954 S += " struct " + Desc;
3955 S += "* Desc;\n";
3956
3957 Constructor += "(void *fp, "; // Invoke function pointer.
3958 Constructor += "struct " + Desc; // Descriptor pointer.
3959 Constructor += " *desc";
3960
3961 if (BlockDeclRefs.size()) {
3962 // Output all "by copy" declarations.
3963 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3964 E = BlockByCopyDecls.end(); I != E; ++I) {
3965 S += " ";
3966 std::string FieldName = (*I)->getNameAsString();
3967 std::string ArgName = "_" + FieldName;
3968 // Handle nested closure invocation. For example:
3969 //
3970 // void (^myImportedBlock)(void);
3971 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3972 //
3973 // void (^anotherBlock)(void);
3974 // anotherBlock = ^(void) {
3975 // myImportedBlock(); // import and invoke the closure
3976 // };
3977 //
3978 if (isTopLevelBlockPointerType((*I)->getType())) {
3979 S += "struct __block_impl *";
3980 Constructor += ", void *" + ArgName;
3981 } else {
3982 QualType QT = (*I)->getType();
3983 if (HasLocalVariableExternalStorage(*I))
3984 QT = Context->getPointerType(QT);
3985 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3986 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3987 Constructor += ", " + ArgName;
3988 }
3989 S += FieldName + ";\n";
3990 }
3991 // Output all "by ref" declarations.
3992 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3993 E = BlockByRefDecls.end(); I != E; ++I) {
3994 S += " ";
3995 std::string FieldName = (*I)->getNameAsString();
3996 std::string ArgName = "_" + FieldName;
3997 {
3998 std::string TypeString;
3999 RewriteByRefString(TypeString, FieldName, (*I));
4000 TypeString += " *";
4001 FieldName = TypeString + FieldName;
4002 ArgName = TypeString + ArgName;
4003 Constructor += ", " + ArgName;
4004 }
4005 S += FieldName + "; // by ref\n";
4006 }
4007 // Finish writing the constructor.
4008 Constructor += ", int flags=0)";
4009 // Initialize all "by copy" arguments.
4010 bool firsTime = true;
4011 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4012 E = BlockByCopyDecls.end(); I != E; ++I) {
4013 std::string Name = (*I)->getNameAsString();
4014 if (firsTime) {
4015 Constructor += " : ";
4016 firsTime = false;
4017 }
4018 else
4019 Constructor += ", ";
4020 if (isTopLevelBlockPointerType((*I)->getType()))
4021 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4022 else
4023 Constructor += Name + "(_" + Name + ")";
4024 }
4025 // Initialize all "by ref" arguments.
4026 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4027 E = BlockByRefDecls.end(); I != E; ++I) {
4028 std::string Name = (*I)->getNameAsString();
4029 if (firsTime) {
4030 Constructor += " : ";
4031 firsTime = false;
4032 }
4033 else
4034 Constructor += ", ";
4035 Constructor += Name + "(_" + Name + "->__forwarding)";
4036 }
4037
4038 Constructor += " {\n";
4039 if (GlobalVarDecl)
4040 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4041 else
4042 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4043 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4044
4045 Constructor += " Desc = desc;\n";
4046 } else {
4047 // Finish writing the constructor.
4048 Constructor += ", int flags=0) {\n";
4049 if (GlobalVarDecl)
4050 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4051 else
4052 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4053 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4054 Constructor += " Desc = desc;\n";
4055 }
4056 Constructor += " ";
4057 Constructor += "}\n";
4058 S += Constructor;
4059 S += "};\n";
4060 return S;
4061}
4062
4063std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4064 std::string ImplTag, int i,
4065 StringRef FunName,
4066 unsigned hasCopy) {
4067 std::string S = "\nstatic struct " + DescTag;
4068
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004069 S += " {\n size_t reserved;\n";
4070 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004071 if (hasCopy) {
4072 S += " void (*copy)(struct ";
4073 S += ImplTag; S += "*, struct ";
4074 S += ImplTag; S += "*);\n";
4075
4076 S += " void (*dispose)(struct ";
4077 S += ImplTag; S += "*);\n";
4078 }
4079 S += "} ";
4080
4081 S += DescTag + "_DATA = { 0, sizeof(struct ";
4082 S += ImplTag + ")";
4083 if (hasCopy) {
4084 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4085 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4086 }
4087 S += "};\n";
4088 return S;
4089}
4090
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004091/// getFunctionSourceLocation - returns start location of a function
4092/// definition. Complication arises when function has declared as
4093/// extern "C" or extern "C" {...}
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004094static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
4095 FunctionDecl *FD) {
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00004096 if (FD->isExternC() && !FD->isMain()) {
4097 const DeclContext *DC = FD->getDeclContext();
4098 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
4099 // if it is extern "C" {...}, return function decl's own location.
4100 if (!LSD->getRBraceLoc().isValid())
4101 return LSD->getExternLoc();
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004102 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00004103 if (FD->getStorageClassAsWritten() != SC_None)
4104 R.RewriteBlockLiteralFunctionDecl(FD);
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004105 return FD->getTypeSpecStartLoc();
4106}
4107
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004108void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4109 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004110 bool RewriteSC = (GlobalVarDecl &&
4111 !Blocks.empty() &&
4112 GlobalVarDecl->getStorageClass() == SC_Static &&
4113 GlobalVarDecl->getType().getCVRQualifiers());
4114 if (RewriteSC) {
4115 std::string SC(" void __");
4116 SC += GlobalVarDecl->getNameAsString();
4117 SC += "() {}";
4118 InsertText(FunLocStart, SC);
4119 }
4120
4121 // Insert closures that were part of the function.
4122 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4123 CollectBlockDeclRefInfo(Blocks[i]);
4124 // Need to copy-in the inner copied-in variables not actually used in this
4125 // block.
4126 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004127 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004128 ValueDecl *VD = Exp->getDecl();
4129 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004130 if (!VD->hasAttr<BlocksAttr>()) {
4131 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4132 BlockByCopyDeclsPtrSet.insert(VD);
4133 BlockByCopyDecls.push_back(VD);
4134 }
4135 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004136 }
John McCallf4b88a42012-03-10 09:33:50 +00004137
4138 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004139 BlockByRefDeclsPtrSet.insert(VD);
4140 BlockByRefDecls.push_back(VD);
4141 }
John McCallf4b88a42012-03-10 09:33:50 +00004142
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004143 // imported objects in the inner blocks not used in the outer
4144 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004145 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004146 VD->getType()->isBlockPointerType())
4147 ImportedBlockDecls.insert(VD);
4148 }
4149
4150 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4151 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4152
4153 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4154
4155 InsertText(FunLocStart, CI);
4156
4157 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4158
4159 InsertText(FunLocStart, CF);
4160
4161 if (ImportedBlockDecls.size()) {
4162 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4163 InsertText(FunLocStart, HF);
4164 }
4165 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4166 ImportedBlockDecls.size() > 0);
4167 InsertText(FunLocStart, BD);
4168
4169 BlockDeclRefs.clear();
4170 BlockByRefDecls.clear();
4171 BlockByRefDeclsPtrSet.clear();
4172 BlockByCopyDecls.clear();
4173 BlockByCopyDeclsPtrSet.clear();
4174 ImportedBlockDecls.clear();
4175 }
4176 if (RewriteSC) {
4177 // Must insert any 'const/volatile/static here. Since it has been
4178 // removed as result of rewriting of block literals.
4179 std::string SC;
4180 if (GlobalVarDecl->getStorageClass() == SC_Static)
4181 SC = "static ";
4182 if (GlobalVarDecl->getType().isConstQualified())
4183 SC += "const ";
4184 if (GlobalVarDecl->getType().isVolatileQualified())
4185 SC += "volatile ";
4186 if (GlobalVarDecl->getType().isRestrictQualified())
4187 SC += "restrict ";
4188 InsertText(FunLocStart, SC);
4189 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004190 if (GlobalConstructionExp) {
4191 // extra fancy dance for global literal expression.
4192
4193 // Always the latest block expression on the block stack.
4194 std::string Tag = "__";
4195 Tag += FunName;
4196 Tag += "_block_impl_";
4197 Tag += utostr(Blocks.size()-1);
4198 std::string globalBuf = "static ";
4199 globalBuf += Tag; globalBuf += " ";
4200 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004201
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004202 llvm::raw_string_ostream constructorExprBuf(SStr);
4203 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
4204 PrintingPolicy(LangOpts));
4205 globalBuf += constructorExprBuf.str();
4206 globalBuf += ";\n";
4207 InsertText(FunLocStart, globalBuf);
4208 GlobalConstructionExp = 0;
4209 }
4210
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004211 Blocks.clear();
4212 InnerDeclRefsCount.clear();
4213 InnerDeclRefs.clear();
4214 RewrittenBlockExprs.clear();
4215}
4216
4217void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004218 SourceLocation FunLocStart =
4219 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4220 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004221 StringRef FuncName = FD->getName();
4222
4223 SynthesizeBlockLiterals(FunLocStart, FuncName);
4224}
4225
4226static void BuildUniqueMethodName(std::string &Name,
4227 ObjCMethodDecl *MD) {
4228 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4229 Name = IFace->getName();
4230 Name += "__" + MD->getSelector().getAsString();
4231 // Convert colons to underscores.
4232 std::string::size_type loc = 0;
4233 while ((loc = Name.find(":", loc)) != std::string::npos)
4234 Name.replace(loc, 1, "_");
4235}
4236
4237void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4238 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4239 //SourceLocation FunLocStart = MD->getLocStart();
4240 SourceLocation FunLocStart = MD->getLocStart();
4241 std::string FuncName;
4242 BuildUniqueMethodName(FuncName, MD);
4243 SynthesizeBlockLiterals(FunLocStart, FuncName);
4244}
4245
4246void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4247 for (Stmt::child_range CI = S->children(); CI; ++CI)
4248 if (*CI) {
4249 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4250 GetBlockDeclRefExprs(CBE->getBody());
4251 else
4252 GetBlockDeclRefExprs(*CI);
4253 }
4254 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004255 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4256 if (DRE->refersToEnclosingLocal()) {
4257 // FIXME: Handle enums.
4258 if (!isa<FunctionDecl>(DRE->getDecl()))
4259 BlockDeclRefs.push_back(DRE);
4260 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4261 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004262 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004263 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004264
4265 return;
4266}
4267
4268void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004269 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004270 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4271 for (Stmt::child_range CI = S->children(); CI; ++CI)
4272 if (*CI) {
4273 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4274 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4275 GetInnerBlockDeclRefExprs(CBE->getBody(),
4276 InnerBlockDeclRefs,
4277 InnerContexts);
4278 }
4279 else
4280 GetInnerBlockDeclRefExprs(*CI,
4281 InnerBlockDeclRefs,
4282 InnerContexts);
4283
4284 }
4285 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004286 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4287 if (DRE->refersToEnclosingLocal()) {
4288 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4289 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4290 InnerBlockDeclRefs.push_back(DRE);
4291 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4292 if (Var->isFunctionOrMethodVarDecl())
4293 ImportedLocalExternalDecls.insert(Var);
4294 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004295 }
4296
4297 return;
4298}
4299
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004300/// convertObjCTypeToCStyleType - This routine converts such objc types
4301/// as qualified objects, and blocks to their closest c/c++ types that
4302/// it can. It returns true if input type was modified.
4303bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4304 QualType oldT = T;
4305 convertBlockPointerToFunctionPointer(T);
4306 if (T->isFunctionPointerType()) {
4307 QualType PointeeTy;
4308 if (const PointerType* PT = T->getAs<PointerType>()) {
4309 PointeeTy = PT->getPointeeType();
4310 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4311 T = convertFunctionTypeOfBlocks(FT);
4312 T = Context->getPointerType(T);
4313 }
4314 }
4315 }
4316
4317 convertToUnqualifiedObjCType(T);
4318 return T != oldT;
4319}
4320
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004321/// convertFunctionTypeOfBlocks - This routine converts a function type
4322/// whose result type may be a block pointer or whose argument type(s)
4323/// might be block pointers to an equivalent function type replacing
4324/// all block pointers to function pointers.
4325QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4326 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4327 // FTP will be null for closures that don't take arguments.
4328 // Generate a funky cast.
4329 SmallVector<QualType, 8> ArgTypes;
4330 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004331 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004332
4333 if (FTP) {
4334 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4335 E = FTP->arg_type_end(); I && (I != E); ++I) {
4336 QualType t = *I;
4337 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004338 if (convertObjCTypeToCStyleType(t))
4339 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004340 ArgTypes.push_back(t);
4341 }
4342 }
4343 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004344 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004345 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4346 else FuncType = QualType(FT, 0);
4347 return FuncType;
4348}
4349
4350Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4351 // Navigate to relevant type information.
4352 const BlockPointerType *CPT = 0;
4353
4354 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4355 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004356 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4357 CPT = MExpr->getType()->getAs<BlockPointerType>();
4358 }
4359 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4360 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4361 }
4362 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4363 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4364 else if (const ConditionalOperator *CEXPR =
4365 dyn_cast<ConditionalOperator>(BlockExp)) {
4366 Expr *LHSExp = CEXPR->getLHS();
4367 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4368 Expr *RHSExp = CEXPR->getRHS();
4369 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4370 Expr *CONDExp = CEXPR->getCond();
4371 ConditionalOperator *CondExpr =
4372 new (Context) ConditionalOperator(CONDExp,
4373 SourceLocation(), cast<Expr>(LHSStmt),
4374 SourceLocation(), cast<Expr>(RHSStmt),
4375 Exp->getType(), VK_RValue, OK_Ordinary);
4376 return CondExpr;
4377 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4378 CPT = IRE->getType()->getAs<BlockPointerType>();
4379 } else if (const PseudoObjectExpr *POE
4380 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4381 CPT = POE->getType()->castAs<BlockPointerType>();
4382 } else {
4383 assert(1 && "RewriteBlockClass: Bad type");
4384 }
4385 assert(CPT && "RewriteBlockClass: Bad type");
4386 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4387 assert(FT && "RewriteBlockClass: Bad type");
4388 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4389 // FTP will be null for closures that don't take arguments.
4390
4391 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4392 SourceLocation(), SourceLocation(),
4393 &Context->Idents.get("__block_impl"));
4394 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4395
4396 // Generate a funky cast.
4397 SmallVector<QualType, 8> ArgTypes;
4398
4399 // Push the block argument type.
4400 ArgTypes.push_back(PtrBlock);
4401 if (FTP) {
4402 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4403 E = FTP->arg_type_end(); I && (I != E); ++I) {
4404 QualType t = *I;
4405 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4406 if (!convertBlockPointerToFunctionPointer(t))
4407 convertToUnqualifiedObjCType(t);
4408 ArgTypes.push_back(t);
4409 }
4410 }
4411 // Now do the pointer to function cast.
4412 QualType PtrToFuncCastType
4413 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4414
4415 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4416
4417 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4418 CK_BitCast,
4419 const_cast<Expr*>(BlockExp));
4420 // Don't forget the parens to enforce the proper binding.
4421 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4422 BlkCast);
4423 //PE->dump();
4424
4425 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4426 SourceLocation(),
4427 &Context->Idents.get("FuncPtr"),
4428 Context->VoidPtrTy, 0,
4429 /*BitWidth=*/0, /*Mutable=*/true,
4430 /*HasInit=*/false);
4431 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4432 FD->getType(), VK_LValue,
4433 OK_Ordinary);
4434
4435
4436 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4437 CK_BitCast, ME);
4438 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4439
4440 SmallVector<Expr*, 8> BlkExprs;
4441 // Add the implicit argument.
4442 BlkExprs.push_back(BlkCast);
4443 // Add the user arguments.
4444 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4445 E = Exp->arg_end(); I != E; ++I) {
4446 BlkExprs.push_back(*I);
4447 }
4448 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4449 BlkExprs.size(),
4450 Exp->getType(), VK_RValue,
4451 SourceLocation());
4452 return CE;
4453}
4454
4455// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004456// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004457// For example:
4458//
4459// int main() {
4460// __block Foo *f;
4461// __block int i;
4462//
4463// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004464// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004465// i = 77;
4466// };
4467//}
John McCallf4b88a42012-03-10 09:33:50 +00004468Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004469 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4470 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004471 ValueDecl *VD = DeclRefExp->getDecl();
4472 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004473
4474 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4475 SourceLocation(),
4476 &Context->Idents.get("__forwarding"),
4477 Context->VoidPtrTy, 0,
4478 /*BitWidth=*/0, /*Mutable=*/true,
4479 /*HasInit=*/false);
4480 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4481 FD, SourceLocation(),
4482 FD->getType(), VK_LValue,
4483 OK_Ordinary);
4484
4485 StringRef Name = VD->getName();
4486 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4487 &Context->Idents.get(Name),
4488 Context->VoidPtrTy, 0,
4489 /*BitWidth=*/0, /*Mutable=*/true,
4490 /*HasInit=*/false);
4491 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4492 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4493
4494
4495
4496 // Need parens to enforce precedence.
4497 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4498 DeclRefExp->getExprLoc(),
4499 ME);
4500 ReplaceStmt(DeclRefExp, PE);
4501 return PE;
4502}
4503
4504// Rewrites the imported local variable V with external storage
4505// (static, extern, etc.) as *V
4506//
4507Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4508 ValueDecl *VD = DRE->getDecl();
4509 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4510 if (!ImportedLocalExternalDecls.count(Var))
4511 return DRE;
4512 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4513 VK_LValue, OK_Ordinary,
4514 DRE->getLocation());
4515 // Need parens to enforce precedence.
4516 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4517 Exp);
4518 ReplaceStmt(DRE, PE);
4519 return PE;
4520}
4521
4522void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4523 SourceLocation LocStart = CE->getLParenLoc();
4524 SourceLocation LocEnd = CE->getRParenLoc();
4525
4526 // Need to avoid trying to rewrite synthesized casts.
4527 if (LocStart.isInvalid())
4528 return;
4529 // Need to avoid trying to rewrite casts contained in macros.
4530 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4531 return;
4532
4533 const char *startBuf = SM->getCharacterData(LocStart);
4534 const char *endBuf = SM->getCharacterData(LocEnd);
4535 QualType QT = CE->getType();
4536 const Type* TypePtr = QT->getAs<Type>();
4537 if (isa<TypeOfExprType>(TypePtr)) {
4538 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4539 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4540 std::string TypeAsString = "(";
4541 RewriteBlockPointerType(TypeAsString, QT);
4542 TypeAsString += ")";
4543 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4544 return;
4545 }
4546 // advance the location to startArgList.
4547 const char *argPtr = startBuf;
4548
4549 while (*argPtr++ && (argPtr < endBuf)) {
4550 switch (*argPtr) {
4551 case '^':
4552 // Replace the '^' with '*'.
4553 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4554 ReplaceText(LocStart, 1, "*");
4555 break;
4556 }
4557 }
4558 return;
4559}
4560
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004561void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4562 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004563 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4564 CastKind != CK_AnyPointerToBlockPointerCast)
4565 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004566
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004567 QualType QT = IC->getType();
4568 (void)convertBlockPointerToFunctionPointer(QT);
4569 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4570 std::string Str = "(";
4571 Str += TypeString;
4572 Str += ")";
4573 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4574
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004575 return;
4576}
4577
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004578void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4579 SourceLocation DeclLoc = FD->getLocation();
4580 unsigned parenCount = 0;
4581
4582 // We have 1 or more arguments that have closure pointers.
4583 const char *startBuf = SM->getCharacterData(DeclLoc);
4584 const char *startArgList = strchr(startBuf, '(');
4585
4586 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4587
4588 parenCount++;
4589 // advance the location to startArgList.
4590 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4591 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4592
4593 const char *argPtr = startArgList;
4594
4595 while (*argPtr++ && parenCount) {
4596 switch (*argPtr) {
4597 case '^':
4598 // Replace the '^' with '*'.
4599 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4600 ReplaceText(DeclLoc, 1, "*");
4601 break;
4602 case '(':
4603 parenCount++;
4604 break;
4605 case ')':
4606 parenCount--;
4607 break;
4608 }
4609 }
4610 return;
4611}
4612
4613bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4614 const FunctionProtoType *FTP;
4615 const PointerType *PT = QT->getAs<PointerType>();
4616 if (PT) {
4617 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4618 } else {
4619 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4620 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4621 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4622 }
4623 if (FTP) {
4624 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4625 E = FTP->arg_type_end(); I != E; ++I)
4626 if (isTopLevelBlockPointerType(*I))
4627 return true;
4628 }
4629 return false;
4630}
4631
4632bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4633 const FunctionProtoType *FTP;
4634 const PointerType *PT = QT->getAs<PointerType>();
4635 if (PT) {
4636 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4637 } else {
4638 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4639 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4640 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4641 }
4642 if (FTP) {
4643 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4644 E = FTP->arg_type_end(); I != E; ++I) {
4645 if ((*I)->isObjCQualifiedIdType())
4646 return true;
4647 if ((*I)->isObjCObjectPointerType() &&
4648 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4649 return true;
4650 }
4651
4652 }
4653 return false;
4654}
4655
4656void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4657 const char *&RParen) {
4658 const char *argPtr = strchr(Name, '(');
4659 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4660
4661 LParen = argPtr; // output the start.
4662 argPtr++; // skip past the left paren.
4663 unsigned parenCount = 1;
4664
4665 while (*argPtr && parenCount) {
4666 switch (*argPtr) {
4667 case '(': parenCount++; break;
4668 case ')': parenCount--; break;
4669 default: break;
4670 }
4671 if (parenCount) argPtr++;
4672 }
4673 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4674 RParen = argPtr; // output the end
4675}
4676
4677void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4678 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4679 RewriteBlockPointerFunctionArgs(FD);
4680 return;
4681 }
4682 // Handle Variables and Typedefs.
4683 SourceLocation DeclLoc = ND->getLocation();
4684 QualType DeclT;
4685 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4686 DeclT = VD->getType();
4687 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4688 DeclT = TDD->getUnderlyingType();
4689 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4690 DeclT = FD->getType();
4691 else
4692 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4693
4694 const char *startBuf = SM->getCharacterData(DeclLoc);
4695 const char *endBuf = startBuf;
4696 // scan backward (from the decl location) for the end of the previous decl.
4697 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4698 startBuf--;
4699 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4700 std::string buf;
4701 unsigned OrigLength=0;
4702 // *startBuf != '^' if we are dealing with a pointer to function that
4703 // may take block argument types (which will be handled below).
4704 if (*startBuf == '^') {
4705 // Replace the '^' with '*', computing a negative offset.
4706 buf = '*';
4707 startBuf++;
4708 OrigLength++;
4709 }
4710 while (*startBuf != ')') {
4711 buf += *startBuf;
4712 startBuf++;
4713 OrigLength++;
4714 }
4715 buf += ')';
4716 OrigLength++;
4717
4718 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4719 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4720 // Replace the '^' with '*' for arguments.
4721 // Replace id<P> with id/*<>*/
4722 DeclLoc = ND->getLocation();
4723 startBuf = SM->getCharacterData(DeclLoc);
4724 const char *argListBegin, *argListEnd;
4725 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4726 while (argListBegin < argListEnd) {
4727 if (*argListBegin == '^')
4728 buf += '*';
4729 else if (*argListBegin == '<') {
4730 buf += "/*";
4731 buf += *argListBegin++;
4732 OrigLength++;;
4733 while (*argListBegin != '>') {
4734 buf += *argListBegin++;
4735 OrigLength++;
4736 }
4737 buf += *argListBegin;
4738 buf += "*/";
4739 }
4740 else
4741 buf += *argListBegin;
4742 argListBegin++;
4743 OrigLength++;
4744 }
4745 buf += ')';
4746 OrigLength++;
4747 }
4748 ReplaceText(Start, OrigLength, buf);
4749
4750 return;
4751}
4752
4753
4754/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4755/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4756/// struct Block_byref_id_object *src) {
4757/// _Block_object_assign (&_dest->object, _src->object,
4758/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4759/// [|BLOCK_FIELD_IS_WEAK]) // object
4760/// _Block_object_assign(&_dest->object, _src->object,
4761/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4762/// [|BLOCK_FIELD_IS_WEAK]) // block
4763/// }
4764/// And:
4765/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4766/// _Block_object_dispose(_src->object,
4767/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4768/// [|BLOCK_FIELD_IS_WEAK]) // object
4769/// _Block_object_dispose(_src->object,
4770/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4771/// [|BLOCK_FIELD_IS_WEAK]) // block
4772/// }
4773
4774std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4775 int flag) {
4776 std::string S;
4777 if (CopyDestroyCache.count(flag))
4778 return S;
4779 CopyDestroyCache.insert(flag);
4780 S = "static void __Block_byref_id_object_copy_";
4781 S += utostr(flag);
4782 S += "(void *dst, void *src) {\n";
4783
4784 // offset into the object pointer is computed as:
4785 // void * + void* + int + int + void* + void *
4786 unsigned IntSize =
4787 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4788 unsigned VoidPtrSize =
4789 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4790
4791 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4792 S += " _Block_object_assign((char*)dst + ";
4793 S += utostr(offset);
4794 S += ", *(void * *) ((char*)src + ";
4795 S += utostr(offset);
4796 S += "), ";
4797 S += utostr(flag);
4798 S += ");\n}\n";
4799
4800 S += "static void __Block_byref_id_object_dispose_";
4801 S += utostr(flag);
4802 S += "(void *src) {\n";
4803 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4804 S += utostr(offset);
4805 S += "), ";
4806 S += utostr(flag);
4807 S += ");\n}\n";
4808 return S;
4809}
4810
4811/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4812/// the declaration into:
4813/// struct __Block_byref_ND {
4814/// void *__isa; // NULL for everything except __weak pointers
4815/// struct __Block_byref_ND *__forwarding;
4816/// int32_t __flags;
4817/// int32_t __size;
4818/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4819/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4820/// typex ND;
4821/// };
4822///
4823/// It then replaces declaration of ND variable with:
4824/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4825/// __size=sizeof(struct __Block_byref_ND),
4826/// ND=initializer-if-any};
4827///
4828///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004829void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
4830 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004831 int flag = 0;
4832 int isa = 0;
4833 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4834 if (DeclLoc.isInvalid())
4835 // If type location is missing, it is because of missing type (a warning).
4836 // Use variable's location which is good for this case.
4837 DeclLoc = ND->getLocation();
4838 const char *startBuf = SM->getCharacterData(DeclLoc);
4839 SourceLocation X = ND->getLocEnd();
4840 X = SM->getExpansionLoc(X);
4841 const char *endBuf = SM->getCharacterData(X);
4842 std::string Name(ND->getNameAsString());
4843 std::string ByrefType;
4844 RewriteByRefString(ByrefType, Name, ND, true);
4845 ByrefType += " {\n";
4846 ByrefType += " void *__isa;\n";
4847 RewriteByRefString(ByrefType, Name, ND);
4848 ByrefType += " *__forwarding;\n";
4849 ByrefType += " int __flags;\n";
4850 ByrefType += " int __size;\n";
4851 // Add void *__Block_byref_id_object_copy;
4852 // void *__Block_byref_id_object_dispose; if needed.
4853 QualType Ty = ND->getType();
4854 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4855 if (HasCopyAndDispose) {
4856 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4857 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4858 }
4859
4860 QualType T = Ty;
4861 (void)convertBlockPointerToFunctionPointer(T);
4862 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4863
4864 ByrefType += " " + Name + ";\n";
4865 ByrefType += "};\n";
4866 // Insert this type in global scope. It is needed by helper function.
4867 SourceLocation FunLocStart;
4868 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004869 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004870 else {
4871 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4872 FunLocStart = CurMethodDef->getLocStart();
4873 }
4874 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004875
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004876 if (Ty.isObjCGCWeak()) {
4877 flag |= BLOCK_FIELD_IS_WEAK;
4878 isa = 1;
4879 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004880 if (HasCopyAndDispose) {
4881 flag = BLOCK_BYREF_CALLER;
4882 QualType Ty = ND->getType();
4883 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4884 if (Ty->isBlockPointerType())
4885 flag |= BLOCK_FIELD_IS_BLOCK;
4886 else
4887 flag |= BLOCK_FIELD_IS_OBJECT;
4888 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4889 if (!HF.empty())
4890 InsertText(FunLocStart, HF);
4891 }
4892
4893 // struct __Block_byref_ND ND =
4894 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4895 // initializer-if-any};
4896 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00004897 // FIXME. rewriter does not support __block c++ objects which
4898 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00004899 if (hasInit)
4900 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
4901 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
4902 if (CXXDecl && CXXDecl->isDefaultConstructor())
4903 hasInit = false;
4904 }
4905
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004906 unsigned flags = 0;
4907 if (HasCopyAndDispose)
4908 flags |= BLOCK_HAS_COPY_DISPOSE;
4909 Name = ND->getNameAsString();
4910 ByrefType.clear();
4911 RewriteByRefString(ByrefType, Name, ND);
4912 std::string ForwardingCastType("(");
4913 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004914 ByrefType += " " + Name + " = {(void*)";
4915 ByrefType += utostr(isa);
4916 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4917 ByrefType += utostr(flags);
4918 ByrefType += ", ";
4919 ByrefType += "sizeof(";
4920 RewriteByRefString(ByrefType, Name, ND);
4921 ByrefType += ")";
4922 if (HasCopyAndDispose) {
4923 ByrefType += ", __Block_byref_id_object_copy_";
4924 ByrefType += utostr(flag);
4925 ByrefType += ", __Block_byref_id_object_dispose_";
4926 ByrefType += utostr(flag);
4927 }
4928
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004929 if (!firstDecl) {
4930 // In multiple __block declarations, and for all but 1st declaration,
4931 // find location of the separating comma. This would be start location
4932 // where new text is to be inserted.
4933 DeclLoc = ND->getLocation();
4934 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
4935 const char *commaBuf = startDeclBuf;
4936 while (*commaBuf != ',')
4937 commaBuf--;
4938 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
4939 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
4940 startBuf = commaBuf;
4941 }
4942
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004943 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004944 ByrefType += "};\n";
4945 unsigned nameSize = Name.size();
4946 // for block or function pointer declaration. Name is aleady
4947 // part of the declaration.
4948 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4949 nameSize = 1;
4950 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4951 }
4952 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004953 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004954 SourceLocation startLoc;
4955 Expr *E = ND->getInit();
4956 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4957 startLoc = ECE->getLParenLoc();
4958 else
4959 startLoc = E->getLocStart();
4960 startLoc = SM->getExpansionLoc(startLoc);
4961 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004962 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004963
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004964 const char separator = lastDecl ? ';' : ',';
4965 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4966 const char *separatorBuf = strchr(startInitializerBuf, separator);
4967 assert((*separatorBuf == separator) &&
4968 "RewriteByRefVar: can't find ';' or ','");
4969 SourceLocation separatorLoc =
4970 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
4971
4972 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004973 }
4974 return;
4975}
4976
4977void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4978 // Add initializers for any closure decl refs.
4979 GetBlockDeclRefExprs(Exp->getBody());
4980 if (BlockDeclRefs.size()) {
4981 // Unique all "by copy" declarations.
4982 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004983 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004984 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4985 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4986 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4987 }
4988 }
4989 // Unique all "by ref" declarations.
4990 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004991 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004992 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4993 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4994 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4995 }
4996 }
4997 // Find any imported blocks...they will need special attention.
4998 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004999 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005000 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5001 BlockDeclRefs[i]->getType()->isBlockPointerType())
5002 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5003 }
5004}
5005
5006FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5007 IdentifierInfo *ID = &Context->Idents.get(name);
5008 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5009 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5010 SourceLocation(), ID, FType, 0, SC_Extern,
5011 SC_None, false, false);
5012}
5013
5014Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005015 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005016
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005017 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005018
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005019 Blocks.push_back(Exp);
5020
5021 CollectBlockDeclRefInfo(Exp);
5022
5023 // Add inner imported variables now used in current block.
5024 int countOfInnerDecls = 0;
5025 if (!InnerBlockDeclRefs.empty()) {
5026 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005027 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005028 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005029 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005030 // We need to save the copied-in variables in nested
5031 // blocks because it is needed at the end for some of the API generations.
5032 // See SynthesizeBlockLiterals routine.
5033 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5034 BlockDeclRefs.push_back(Exp);
5035 BlockByCopyDeclsPtrSet.insert(VD);
5036 BlockByCopyDecls.push_back(VD);
5037 }
John McCallf4b88a42012-03-10 09:33:50 +00005038 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005039 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5040 BlockDeclRefs.push_back(Exp);
5041 BlockByRefDeclsPtrSet.insert(VD);
5042 BlockByRefDecls.push_back(VD);
5043 }
5044 }
5045 // Find any imported blocks...they will need special attention.
5046 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005047 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005048 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5049 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5050 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5051 }
5052 InnerDeclRefsCount.push_back(countOfInnerDecls);
5053
5054 std::string FuncName;
5055
5056 if (CurFunctionDef)
5057 FuncName = CurFunctionDef->getNameAsString();
5058 else if (CurMethodDef)
5059 BuildUniqueMethodName(FuncName, CurMethodDef);
5060 else if (GlobalVarDecl)
5061 FuncName = std::string(GlobalVarDecl->getNameAsString());
5062
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005063 bool GlobalBlockExpr =
5064 block->getDeclContext()->getRedeclContext()->isFileContext();
5065
5066 if (GlobalBlockExpr && !GlobalVarDecl) {
5067 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5068 GlobalBlockExpr = false;
5069 }
5070
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005071 std::string BlockNumber = utostr(Blocks.size()-1);
5072
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005073 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5074
5075 // Get a pointer to the function type so we can cast appropriately.
5076 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5077 QualType FType = Context->getPointerType(BFT);
5078
5079 FunctionDecl *FD;
5080 Expr *NewRep;
5081
5082 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005083 std::string Tag;
5084
5085 if (GlobalBlockExpr)
5086 Tag = "__global_";
5087 else
5088 Tag = "__";
5089 Tag += FuncName + "_block_impl_" + BlockNumber;
5090
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005091 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005092 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005093 SourceLocation());
5094
5095 SmallVector<Expr*, 4> InitExprs;
5096
5097 // Initialize the block function.
5098 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005099 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5100 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005101 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5102 CK_BitCast, Arg);
5103 InitExprs.push_back(castExpr);
5104
5105 // Initialize the block descriptor.
5106 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5107
5108 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5109 SourceLocation(), SourceLocation(),
5110 &Context->Idents.get(DescData.c_str()),
5111 Context->VoidPtrTy, 0,
5112 SC_Static, SC_None);
5113 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005114 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005115 Context->VoidPtrTy,
5116 VK_LValue,
5117 SourceLocation()),
5118 UO_AddrOf,
5119 Context->getPointerType(Context->VoidPtrTy),
5120 VK_RValue, OK_Ordinary,
5121 SourceLocation());
5122 InitExprs.push_back(DescRefExpr);
5123
5124 // Add initializers for any closure decl refs.
5125 if (BlockDeclRefs.size()) {
5126 Expr *Exp;
5127 // Output all "by copy" declarations.
5128 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5129 E = BlockByCopyDecls.end(); I != E; ++I) {
5130 if (isObjCType((*I)->getType())) {
5131 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5132 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005133 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5134 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005135 if (HasLocalVariableExternalStorage(*I)) {
5136 QualType QT = (*I)->getType();
5137 QT = Context->getPointerType(QT);
5138 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5139 OK_Ordinary, SourceLocation());
5140 }
5141 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5142 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005143 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5144 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005145 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5146 CK_BitCast, Arg);
5147 } else {
5148 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005149 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5150 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005151 if (HasLocalVariableExternalStorage(*I)) {
5152 QualType QT = (*I)->getType();
5153 QT = Context->getPointerType(QT);
5154 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5155 OK_Ordinary, SourceLocation());
5156 }
5157
5158 }
5159 InitExprs.push_back(Exp);
5160 }
5161 // Output all "by ref" declarations.
5162 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5163 E = BlockByRefDecls.end(); I != E; ++I) {
5164 ValueDecl *ND = (*I);
5165 std::string Name(ND->getNameAsString());
5166 std::string RecName;
5167 RewriteByRefString(RecName, Name, ND, true);
5168 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5169 + sizeof("struct"));
5170 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5171 SourceLocation(), SourceLocation(),
5172 II);
5173 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5174 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5175
5176 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005177 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005178 SourceLocation());
5179 bool isNestedCapturedVar = false;
5180 if (block)
5181 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5182 ce = block->capture_end(); ci != ce; ++ci) {
5183 const VarDecl *variable = ci->getVariable();
5184 if (variable == ND && ci->isNested()) {
5185 assert (ci->isByRef() &&
5186 "SynthBlockInitExpr - captured block variable is not byref");
5187 isNestedCapturedVar = true;
5188 break;
5189 }
5190 }
5191 // captured nested byref variable has its address passed. Do not take
5192 // its address again.
5193 if (!isNestedCapturedVar)
5194 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5195 Context->getPointerType(Exp->getType()),
5196 VK_RValue, OK_Ordinary, SourceLocation());
5197 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5198 InitExprs.push_back(Exp);
5199 }
5200 }
5201 if (ImportedBlockDecls.size()) {
5202 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5203 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5204 unsigned IntSize =
5205 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5206 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5207 Context->IntTy, SourceLocation());
5208 InitExprs.push_back(FlagExp);
5209 }
5210 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5211 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005212
5213 if (GlobalBlockExpr) {
5214 assert (GlobalConstructionExp == 0 &&
5215 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5216 GlobalConstructionExp = NewRep;
5217 NewRep = DRE;
5218 }
5219
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005220 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5221 Context->getPointerType(NewRep->getType()),
5222 VK_RValue, OK_Ordinary, SourceLocation());
5223 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5224 NewRep);
5225 BlockDeclRefs.clear();
5226 BlockByRefDecls.clear();
5227 BlockByRefDeclsPtrSet.clear();
5228 BlockByCopyDecls.clear();
5229 BlockByCopyDeclsPtrSet.clear();
5230 ImportedBlockDecls.clear();
5231 return NewRep;
5232}
5233
5234bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5235 if (const ObjCForCollectionStmt * CS =
5236 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5237 return CS->getElement() == DS;
5238 return false;
5239}
5240
5241//===----------------------------------------------------------------------===//
5242// Function Body / Expression rewriting
5243//===----------------------------------------------------------------------===//
5244
5245Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5246 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5247 isa<DoStmt>(S) || isa<ForStmt>(S))
5248 Stmts.push_back(S);
5249 else if (isa<ObjCForCollectionStmt>(S)) {
5250 Stmts.push_back(S);
5251 ObjCBcLabelNo.push_back(++BcLabelCount);
5252 }
5253
5254 // Pseudo-object operations and ivar references need special
5255 // treatment because we're going to recursively rewrite them.
5256 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5257 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5258 return RewritePropertyOrImplicitSetter(PseudoOp);
5259 } else {
5260 return RewritePropertyOrImplicitGetter(PseudoOp);
5261 }
5262 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5263 return RewriteObjCIvarRefExpr(IvarRefExpr);
5264 }
5265
5266 SourceRange OrigStmtRange = S->getSourceRange();
5267
5268 // Perform a bottom up rewrite of all children.
5269 for (Stmt::child_range CI = S->children(); CI; ++CI)
5270 if (*CI) {
5271 Stmt *childStmt = (*CI);
5272 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5273 if (newStmt) {
5274 *CI = newStmt;
5275 }
5276 }
5277
5278 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005279 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005280 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5281 InnerContexts.insert(BE->getBlockDecl());
5282 ImportedLocalExternalDecls.clear();
5283 GetInnerBlockDeclRefExprs(BE->getBody(),
5284 InnerBlockDeclRefs, InnerContexts);
5285 // Rewrite the block body in place.
5286 Stmt *SaveCurrentBody = CurrentBody;
5287 CurrentBody = BE->getBody();
5288 PropParentMap = 0;
5289 // block literal on rhs of a property-dot-sytax assignment
5290 // must be replaced by its synthesize ast so getRewrittenText
5291 // works as expected. In this case, what actually ends up on RHS
5292 // is the blockTranscribed which is the helper function for the
5293 // block literal; as in: self.c = ^() {[ace ARR];};
5294 bool saveDisableReplaceStmt = DisableReplaceStmt;
5295 DisableReplaceStmt = false;
5296 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5297 DisableReplaceStmt = saveDisableReplaceStmt;
5298 CurrentBody = SaveCurrentBody;
5299 PropParentMap = 0;
5300 ImportedLocalExternalDecls.clear();
5301 // Now we snarf the rewritten text and stash it away for later use.
5302 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5303 RewrittenBlockExprs[BE] = Str;
5304
5305 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5306
5307 //blockTranscribed->dump();
5308 ReplaceStmt(S, blockTranscribed);
5309 return blockTranscribed;
5310 }
5311 // Handle specific things.
5312 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5313 return RewriteAtEncode(AtEncode);
5314
5315 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5316 return RewriteAtSelector(AtSelector);
5317
5318 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5319 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005320
5321 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5322 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005323
Patrick Beardeb382ec2012-04-19 00:25:12 +00005324 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5325 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005326
5327 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5328 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005329
5330 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5331 dyn_cast<ObjCDictionaryLiteral>(S))
5332 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005333
5334 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5335#if 0
5336 // Before we rewrite it, put the original message expression in a comment.
5337 SourceLocation startLoc = MessExpr->getLocStart();
5338 SourceLocation endLoc = MessExpr->getLocEnd();
5339
5340 const char *startBuf = SM->getCharacterData(startLoc);
5341 const char *endBuf = SM->getCharacterData(endLoc);
5342
5343 std::string messString;
5344 messString += "// ";
5345 messString.append(startBuf, endBuf-startBuf+1);
5346 messString += "\n";
5347
5348 // FIXME: Missing definition of
5349 // InsertText(clang::SourceLocation, char const*, unsigned int).
5350 // InsertText(startLoc, messString.c_str(), messString.size());
5351 // Tried this, but it didn't work either...
5352 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5353#endif
5354 return RewriteMessageExpr(MessExpr);
5355 }
5356
5357 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5358 return RewriteObjCTryStmt(StmtTry);
5359
5360 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5361 return RewriteObjCSynchronizedStmt(StmtTry);
5362
5363 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5364 return RewriteObjCThrowStmt(StmtThrow);
5365
5366 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5367 return RewriteObjCProtocolExpr(ProtocolExp);
5368
5369 if (ObjCForCollectionStmt *StmtForCollection =
5370 dyn_cast<ObjCForCollectionStmt>(S))
5371 return RewriteObjCForCollectionStmt(StmtForCollection,
5372 OrigStmtRange.getEnd());
5373 if (BreakStmt *StmtBreakStmt =
5374 dyn_cast<BreakStmt>(S))
5375 return RewriteBreakStmt(StmtBreakStmt);
5376 if (ContinueStmt *StmtContinueStmt =
5377 dyn_cast<ContinueStmt>(S))
5378 return RewriteContinueStmt(StmtContinueStmt);
5379
5380 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5381 // and cast exprs.
5382 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5383 // FIXME: What we're doing here is modifying the type-specifier that
5384 // precedes the first Decl. In the future the DeclGroup should have
5385 // a separate type-specifier that we can rewrite.
5386 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5387 // the context of an ObjCForCollectionStmt. For example:
5388 // NSArray *someArray;
5389 // for (id <FooProtocol> index in someArray) ;
5390 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5391 // and it depends on the original text locations/positions.
5392 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5393 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5394
5395 // Blocks rewrite rules.
5396 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5397 DI != DE; ++DI) {
5398 Decl *SD = *DI;
5399 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5400 if (isTopLevelBlockPointerType(ND->getType()))
5401 RewriteBlockPointerDecl(ND);
5402 else if (ND->getType()->isFunctionPointerType())
5403 CheckFunctionPointerDecl(ND->getType(), ND);
5404 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5405 if (VD->hasAttr<BlocksAttr>()) {
5406 static unsigned uniqueByrefDeclCount = 0;
5407 assert(!BlockByRefDeclNo.count(ND) &&
5408 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5409 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005410 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005411 }
5412 else
5413 RewriteTypeOfDecl(VD);
5414 }
5415 }
5416 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5417 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5418 RewriteBlockPointerDecl(TD);
5419 else if (TD->getUnderlyingType()->isFunctionPointerType())
5420 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5421 }
5422 }
5423 }
5424
5425 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5426 RewriteObjCQualifiedInterfaceTypes(CE);
5427
5428 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5429 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5430 assert(!Stmts.empty() && "Statement stack is empty");
5431 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5432 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5433 && "Statement stack mismatch");
5434 Stmts.pop_back();
5435 }
5436 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005437 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5438 ValueDecl *VD = DRE->getDecl();
5439 if (VD->hasAttr<BlocksAttr>())
5440 return RewriteBlockDeclRefExpr(DRE);
5441 if (HasLocalVariableExternalStorage(VD))
5442 return RewriteLocalVariableExternalStorage(DRE);
5443 }
5444
5445 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5446 if (CE->getCallee()->getType()->isBlockPointerType()) {
5447 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5448 ReplaceStmt(S, BlockCall);
5449 return BlockCall;
5450 }
5451 }
5452 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5453 RewriteCastExpr(CE);
5454 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005455 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5456 RewriteImplicitCastObjCExpr(ICE);
5457 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005458#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005459
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005460 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5461 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5462 ICE->getSubExpr(),
5463 SourceLocation());
5464 // Get the new text.
5465 std::string SStr;
5466 llvm::raw_string_ostream Buf(SStr);
5467 Replacement->printPretty(Buf, *Context);
5468 const std::string &Str = Buf.str();
5469
5470 printf("CAST = %s\n", &Str[0]);
5471 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5472 delete S;
5473 return Replacement;
5474 }
5475#endif
5476 // Return this stmt unmodified.
5477 return S;
5478}
5479
5480void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5481 for (RecordDecl::field_iterator i = RD->field_begin(),
5482 e = RD->field_end(); i != e; ++i) {
David Blaikie262bc182012-04-30 02:36:29 +00005483 FieldDecl *FD = &*i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005484 if (isTopLevelBlockPointerType(FD->getType()))
5485 RewriteBlockPointerDecl(FD);
5486 if (FD->getType()->isObjCQualifiedIdType() ||
5487 FD->getType()->isObjCQualifiedInterfaceType())
5488 RewriteObjCQualifiedInterfaceTypes(FD);
5489 }
5490}
5491
5492/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5493/// main file of the input.
5494void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5495 switch (D->getKind()) {
5496 case Decl::Function: {
5497 FunctionDecl *FD = cast<FunctionDecl>(D);
5498 if (FD->isOverloadedOperator())
5499 return;
5500
5501 // Since function prototypes don't have ParmDecl's, we check the function
5502 // prototype. This enables us to rewrite function declarations and
5503 // definitions using the same code.
5504 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5505
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005506 if (!FD->isThisDeclarationADefinition())
5507 break;
5508
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005509 // FIXME: If this should support Obj-C++, support CXXTryStmt
5510 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5511 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005512 CurrentBody = Body;
5513 Body =
5514 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5515 FD->setBody(Body);
5516 CurrentBody = 0;
5517 if (PropParentMap) {
5518 delete PropParentMap;
5519 PropParentMap = 0;
5520 }
5521 // This synthesizes and inserts the block "impl" struct, invoke function,
5522 // and any copy/dispose helper functions.
5523 InsertBlockLiteralsWithinFunction(FD);
5524 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005525 }
5526 break;
5527 }
5528 case Decl::ObjCMethod: {
5529 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5530 if (CompoundStmt *Body = MD->getCompoundBody()) {
5531 CurMethodDef = MD;
5532 CurrentBody = Body;
5533 Body =
5534 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5535 MD->setBody(Body);
5536 CurrentBody = 0;
5537 if (PropParentMap) {
5538 delete PropParentMap;
5539 PropParentMap = 0;
5540 }
5541 InsertBlockLiteralsWithinMethod(MD);
5542 CurMethodDef = 0;
5543 }
5544 break;
5545 }
5546 case Decl::ObjCImplementation: {
5547 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5548 ClassImplementation.push_back(CI);
5549 break;
5550 }
5551 case Decl::ObjCCategoryImpl: {
5552 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5553 CategoryImplementation.push_back(CI);
5554 break;
5555 }
5556 case Decl::Var: {
5557 VarDecl *VD = cast<VarDecl>(D);
5558 RewriteObjCQualifiedInterfaceTypes(VD);
5559 if (isTopLevelBlockPointerType(VD->getType()))
5560 RewriteBlockPointerDecl(VD);
5561 else if (VD->getType()->isFunctionPointerType()) {
5562 CheckFunctionPointerDecl(VD->getType(), VD);
5563 if (VD->getInit()) {
5564 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5565 RewriteCastExpr(CE);
5566 }
5567 }
5568 } else if (VD->getType()->isRecordType()) {
5569 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5570 if (RD->isCompleteDefinition())
5571 RewriteRecordBody(RD);
5572 }
5573 if (VD->getInit()) {
5574 GlobalVarDecl = VD;
5575 CurrentBody = VD->getInit();
5576 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5577 CurrentBody = 0;
5578 if (PropParentMap) {
5579 delete PropParentMap;
5580 PropParentMap = 0;
5581 }
5582 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5583 GlobalVarDecl = 0;
5584
5585 // This is needed for blocks.
5586 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5587 RewriteCastExpr(CE);
5588 }
5589 }
5590 break;
5591 }
5592 case Decl::TypeAlias:
5593 case Decl::Typedef: {
5594 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5595 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5596 RewriteBlockPointerDecl(TD);
5597 else if (TD->getUnderlyingType()->isFunctionPointerType())
5598 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5599 }
5600 break;
5601 }
5602 case Decl::CXXRecord:
5603 case Decl::Record: {
5604 RecordDecl *RD = cast<RecordDecl>(D);
5605 if (RD->isCompleteDefinition())
5606 RewriteRecordBody(RD);
5607 break;
5608 }
5609 default:
5610 break;
5611 }
5612 // Nothing yet.
5613}
5614
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005615/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5616/// protocol reference symbols in the for of:
5617/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5618static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5619 ObjCProtocolDecl *PDecl,
5620 std::string &Result) {
5621 // Also output .objc_protorefs$B section and its meta-data.
5622 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00005623 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005624 Result += "struct _protocol_t *";
5625 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5626 Result += PDecl->getNameAsString();
5627 Result += " = &";
5628 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5629 Result += ";\n";
5630}
5631
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005632void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5633 if (Diags.hasErrorOccurred())
5634 return;
5635
5636 RewriteInclude();
5637
5638 // Here's a great place to add any extra declarations that may be needed.
5639 // Write out meta data for each @protocol(<expr>).
5640 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005641 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005642 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005643 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5644 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005645
5646 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005647 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5648 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5649 // Write struct declaration for the class matching its ivar declarations.
5650 // Note that for modern abi, this is postponed until the end of TU
5651 // because class extensions and the implementation might declare their own
5652 // private ivars.
5653 RewriteInterfaceDecl(CDecl);
5654 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005655
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005656 if (ClassImplementation.size() || CategoryImplementation.size())
5657 RewriteImplementations();
5658
5659 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5660 // we are done.
5661 if (const RewriteBuffer *RewriteBuf =
5662 Rewrite.getRewriteBufferFor(MainFileID)) {
5663 //printf("Changed:\n");
5664 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5665 } else {
5666 llvm::errs() << "No changes\n";
5667 }
5668
5669 if (ClassImplementation.size() || CategoryImplementation.size() ||
5670 ProtocolExprDecls.size()) {
5671 // Rewrite Objective-c meta data*
5672 std::string ResultStr;
5673 RewriteMetaDataIntoBuffer(ResultStr);
5674 // Emit metadata.
5675 *OutFile << ResultStr;
5676 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005677 // Emit ImageInfo;
5678 {
5679 std::string ResultStr;
5680 WriteImageInfo(ResultStr);
5681 *OutFile << ResultStr;
5682 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005683 OutFile->flush();
5684}
5685
5686void RewriteModernObjC::Initialize(ASTContext &context) {
5687 InitializeCommon(context);
5688
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005689 Preamble += "#ifndef __OBJC2__\n";
5690 Preamble += "#define __OBJC2__\n";
5691 Preamble += "#endif\n";
5692
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005693 // declaring objc_selector outside the parameter list removes a silly
5694 // scope related warning...
5695 if (IsHeader)
5696 Preamble = "#pragma once\n";
5697 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005698 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5699 Preamble += "\n\tstruct objc_object *superClass; ";
5700 // Add a constructor for creating temporary objects.
5701 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5702 Preamble += ": object(o), superClass(s) {} ";
5703 Preamble += "\n};\n";
5704
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005705 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005706 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005707 // These are currently generated.
5708 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005709 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005710 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005711 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5712 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005713 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005714 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005715 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5716 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005717 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005718
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005719 // These need be generated for performance. Currently they are not,
5720 // using API calls instead.
5721 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5722 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5723 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5724
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005725 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005726 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5727 Preamble += "typedef struct objc_object Protocol;\n";
5728 Preamble += "#define _REWRITER_typedef_Protocol\n";
5729 Preamble += "#endif\n";
5730 if (LangOpts.MicrosoftExt) {
5731 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5732 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005733 }
5734 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005735 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005736
5737 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5738 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5739 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5740 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5741 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5742
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005743 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005744 Preamble += "(const char *);\n";
5745 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5746 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005747 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005748 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005749 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005750 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005751 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5752 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005753 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5754 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5755 Preamble += "struct __objcFastEnumerationState {\n\t";
5756 Preamble += "unsigned long state;\n\t";
5757 Preamble += "void **itemsPtr;\n\t";
5758 Preamble += "unsigned long *mutationsPtr;\n\t";
5759 Preamble += "unsigned long extra[5];\n};\n";
5760 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5761 Preamble += "#define __FASTENUMERATIONSTATE\n";
5762 Preamble += "#endif\n";
5763 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5764 Preamble += "struct __NSConstantStringImpl {\n";
5765 Preamble += " int *isa;\n";
5766 Preamble += " int flags;\n";
5767 Preamble += " char *str;\n";
5768 Preamble += " long length;\n";
5769 Preamble += "};\n";
5770 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5771 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5772 Preamble += "#else\n";
5773 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5774 Preamble += "#endif\n";
5775 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5776 Preamble += "#endif\n";
5777 // Blocks preamble.
5778 Preamble += "#ifndef BLOCK_IMPL\n";
5779 Preamble += "#define BLOCK_IMPL\n";
5780 Preamble += "struct __block_impl {\n";
5781 Preamble += " void *isa;\n";
5782 Preamble += " int Flags;\n";
5783 Preamble += " int Reserved;\n";
5784 Preamble += " void *FuncPtr;\n";
5785 Preamble += "};\n";
5786 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5787 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5788 Preamble += "extern \"C\" __declspec(dllexport) "
5789 "void _Block_object_assign(void *, const void *, const int);\n";
5790 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5791 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5792 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5793 Preamble += "#else\n";
5794 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5795 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5796 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5797 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5798 Preamble += "#endif\n";
5799 Preamble += "#endif\n";
5800 if (LangOpts.MicrosoftExt) {
5801 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5802 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5803 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5804 Preamble += "#define __attribute__(X)\n";
5805 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005806 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005807 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005808 Preamble += "#endif\n";
5809 Preamble += "#ifndef __block\n";
5810 Preamble += "#define __block\n";
5811 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005812 }
5813 else {
5814 Preamble += "#define __block\n";
5815 Preamble += "#define __weak\n";
5816 }
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005817
5818 // Declarations required for modern objective-c array and dictionary literals.
5819 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005820 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005821 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005822 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005823 Preamble += "\tva_list marker;\n";
5824 Preamble += "\tva_start(marker, count);\n";
5825 Preamble += "\tarr = new void *[count];\n";
5826 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5827 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5828 Preamble += "\tva_end( marker );\n";
5829 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00005830 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005831 Preamble += "\tdelete[] arr;\n";
5832 Preamble += " }\n";
5833 Preamble += "};\n";
5834
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005835 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5836 // as this avoids warning in any 64bit/32bit compilation model.
5837 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5838}
5839
5840/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5841/// ivar offset.
5842void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5843 std::string &Result) {
5844 if (ivar->isBitField()) {
5845 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5846 // place all bitfields at offset 0.
5847 Result += "0";
5848 } else {
5849 Result += "__OFFSETOFIVAR__(struct ";
5850 Result += ivar->getContainingInterface()->getNameAsString();
5851 if (LangOpts.MicrosoftExt)
5852 Result += "_IMPL";
5853 Result += ", ";
5854 Result += ivar->getNameAsString();
5855 Result += ")";
5856 }
5857}
5858
5859/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5860/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005861/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005862/// char *attributes;
5863/// }
5864
5865/// struct _prop_list_t {
5866/// uint32_t entsize; // sizeof(struct _prop_t)
5867/// uint32_t count_of_properties;
5868/// struct _prop_t prop_list[count_of_properties];
5869/// }
5870
5871/// struct _protocol_t;
5872
5873/// struct _protocol_list_t {
5874/// long protocol_count; // Note, this is 32/64 bit
5875/// struct _protocol_t * protocol_list[protocol_count];
5876/// }
5877
5878/// struct _objc_method {
5879/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005880/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005881/// char *_imp;
5882/// }
5883
5884/// struct _method_list_t {
5885/// uint32_t entsize; // sizeof(struct _objc_method)
5886/// uint32_t method_count;
5887/// struct _objc_method method_list[method_count];
5888/// }
5889
5890/// struct _protocol_t {
5891/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005892/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005893/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005894/// const struct method_list_t *instance_methods;
5895/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005896/// const struct method_list_t *optionalInstanceMethods;
5897/// const struct method_list_t *optionalClassMethods;
5898/// const struct _prop_list_t * properties;
5899/// const uint32_t size; // sizeof(struct _protocol_t)
5900/// const uint32_t flags; // = 0
5901/// const char ** extendedMethodTypes;
5902/// }
5903
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005904/// struct _ivar_t {
5905/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005906/// const char *name;
5907/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005908/// uint32_t alignment;
5909/// uint32_t size;
5910/// }
5911
5912/// struct _ivar_list_t {
5913/// uint32 entsize; // sizeof(struct _ivar_t)
5914/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005915/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005916/// }
5917
5918/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005919/// uint32_t flags;
5920/// uint32_t instanceStart;
5921/// uint32_t instanceSize;
5922/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005923/// const uint8_t *ivarLayout;
5924/// const char *name;
5925/// const struct _method_list_t *baseMethods;
5926/// const struct _protocol_list_t *baseProtocols;
5927/// const struct _ivar_list_t *ivars;
5928/// const uint8_t *weakIvarLayout;
5929/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005930/// }
5931
5932/// struct _class_t {
5933/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005934/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005935/// void *cache;
5936/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005937/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005938/// }
5939
5940/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005941/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005942/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005943/// const struct _method_list_t *instance_methods;
5944/// const struct _method_list_t *class_methods;
5945/// const struct _protocol_list_t *protocols;
5946/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005947/// }
5948
5949/// MessageRefTy - LLVM for:
5950/// struct _message_ref_t {
5951/// IMP messenger;
5952/// SEL name;
5953/// };
5954
5955/// SuperMessageRefTy - LLVM for:
5956/// struct _super_message_ref_t {
5957/// SUPER_IMP messenger;
5958/// SEL name;
5959/// };
5960
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005961static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005962 static bool meta_data_declared = false;
5963 if (meta_data_declared)
5964 return;
5965
5966 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005967 Result += "\tconst char *name;\n";
5968 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005969 Result += "};\n";
5970
5971 Result += "\nstruct _protocol_t;\n";
5972
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005973 Result += "\nstruct _objc_method {\n";
5974 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005975 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005976 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005977 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005978
5979 Result += "\nstruct _protocol_t {\n";
5980 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005981 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005982 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005983 Result += "\tconst struct method_list_t *instance_methods;\n";
5984 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005985 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5986 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5987 Result += "\tconst struct _prop_list_t * properties;\n";
5988 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5989 Result += "\tconst unsigned int flags; // = 0\n";
5990 Result += "\tconst char ** extendedMethodTypes;\n";
5991 Result += "};\n";
5992
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005993 Result += "\nstruct _ivar_t {\n";
5994 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005995 Result += "\tconst char *name;\n";
5996 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005997 Result += "\tunsigned int alignment;\n";
5998 Result += "\tunsigned int size;\n";
5999 Result += "};\n";
6000
6001 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006002 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006003 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006004 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006005 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6006 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006007 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006008 Result += "\tconst unsigned char *ivarLayout;\n";
6009 Result += "\tconst char *name;\n";
6010 Result += "\tconst struct _method_list_t *baseMethods;\n";
6011 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6012 Result += "\tconst struct _ivar_list_t *ivars;\n";
6013 Result += "\tconst unsigned char *weakIvarLayout;\n";
6014 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006015 Result += "};\n";
6016
6017 Result += "\nstruct _class_t {\n";
6018 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006019 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006020 Result += "\tvoid *cache;\n";
6021 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006022 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006023 Result += "};\n";
6024
6025 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006026 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006027 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006028 Result += "\tconst struct _method_list_t *instance_methods;\n";
6029 Result += "\tconst struct _method_list_t *class_methods;\n";
6030 Result += "\tconst struct _protocol_list_t *protocols;\n";
6031 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006032 Result += "};\n";
6033
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006034 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006035 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006036 meta_data_declared = true;
6037}
6038
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006039static void Write_protocol_list_t_TypeDecl(std::string &Result,
6040 long super_protocol_count) {
6041 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6042 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6043 Result += "\tstruct _protocol_t *super_protocols[";
6044 Result += utostr(super_protocol_count); Result += "];\n";
6045 Result += "}";
6046}
6047
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006048static void Write_method_list_t_TypeDecl(std::string &Result,
6049 unsigned int method_count) {
6050 Result += "struct /*_method_list_t*/"; Result += " {\n";
6051 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6052 Result += "\tunsigned int method_count;\n";
6053 Result += "\tstruct _objc_method method_list[";
6054 Result += utostr(method_count); Result += "];\n";
6055 Result += "}";
6056}
6057
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006058static void Write__prop_list_t_TypeDecl(std::string &Result,
6059 unsigned int property_count) {
6060 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6061 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6062 Result += "\tunsigned int count_of_properties;\n";
6063 Result += "\tstruct _prop_t prop_list[";
6064 Result += utostr(property_count); Result += "];\n";
6065 Result += "}";
6066}
6067
Fariborz Jahanianae932952012-02-10 20:47:10 +00006068static void Write__ivar_list_t_TypeDecl(std::string &Result,
6069 unsigned int ivar_count) {
6070 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6071 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6072 Result += "\tunsigned int count;\n";
6073 Result += "\tstruct _ivar_t ivar_list[";
6074 Result += utostr(ivar_count); Result += "];\n";
6075 Result += "}";
6076}
6077
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006078static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6079 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6080 StringRef VarName,
6081 StringRef ProtocolName) {
6082 if (SuperProtocols.size() > 0) {
6083 Result += "\nstatic ";
6084 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6085 Result += " "; Result += VarName;
6086 Result += ProtocolName;
6087 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6088 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6089 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6090 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6091 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6092 Result += SuperPD->getNameAsString();
6093 if (i == e-1)
6094 Result += "\n};\n";
6095 else
6096 Result += ",\n";
6097 }
6098 }
6099}
6100
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006101static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6102 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006103 ArrayRef<ObjCMethodDecl *> Methods,
6104 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006105 StringRef TopLevelDeclName,
6106 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006107 if (Methods.size() > 0) {
6108 Result += "\nstatic ";
6109 Write_method_list_t_TypeDecl(Result, Methods.size());
6110 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006111 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006112 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6113 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6114 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6115 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6116 ObjCMethodDecl *MD = Methods[i];
6117 if (i == 0)
6118 Result += "\t{{(struct objc_selector *)\"";
6119 else
6120 Result += "\t{(struct objc_selector *)\"";
6121 Result += (MD)->getSelector().getAsString(); Result += "\"";
6122 Result += ", ";
6123 std::string MethodTypeString;
6124 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6125 Result += "\""; Result += MethodTypeString; Result += "\"";
6126 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006127 if (!MethodImpl)
6128 Result += "0";
6129 else {
6130 Result += "(void *)";
6131 Result += RewriteObj.MethodInternalNames[MD];
6132 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006133 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006134 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006135 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006136 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006137 }
6138 Result += "};\n";
6139 }
6140}
6141
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006142static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006143 ASTContext *Context, std::string &Result,
6144 ArrayRef<ObjCPropertyDecl *> Properties,
6145 const Decl *Container,
6146 StringRef VarName,
6147 StringRef ProtocolName) {
6148 if (Properties.size() > 0) {
6149 Result += "\nstatic ";
6150 Write__prop_list_t_TypeDecl(Result, Properties.size());
6151 Result += " "; Result += VarName;
6152 Result += ProtocolName;
6153 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6154 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6155 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6156 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6157 ObjCPropertyDecl *PropDecl = Properties[i];
6158 if (i == 0)
6159 Result += "\t{{\"";
6160 else
6161 Result += "\t{\"";
6162 Result += PropDecl->getName(); Result += "\",";
6163 std::string PropertyTypeString, QuotePropertyTypeString;
6164 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6165 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6166 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6167 if (i == e-1)
6168 Result += "}}\n";
6169 else
6170 Result += "},\n";
6171 }
6172 Result += "};\n";
6173 }
6174}
6175
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006176// Metadata flags
6177enum MetaDataDlags {
6178 CLS = 0x0,
6179 CLS_META = 0x1,
6180 CLS_ROOT = 0x2,
6181 OBJC2_CLS_HIDDEN = 0x10,
6182 CLS_EXCEPTION = 0x20,
6183
6184 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6185 CLS_HAS_IVAR_RELEASER = 0x40,
6186 /// class was compiled with -fobjc-arr
6187 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6188};
6189
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006190static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6191 unsigned int flags,
6192 const std::string &InstanceStart,
6193 const std::string &InstanceSize,
6194 ArrayRef<ObjCMethodDecl *>baseMethods,
6195 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6196 ArrayRef<ObjCIvarDecl *>ivars,
6197 ArrayRef<ObjCPropertyDecl *>Properties,
6198 StringRef VarName,
6199 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006200 Result += "\nstatic struct _class_ro_t ";
6201 Result += VarName; Result += ClassName;
6202 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6203 Result += "\t";
6204 Result += llvm::utostr(flags); Result += ", ";
6205 Result += InstanceStart; Result += ", ";
6206 Result += InstanceSize; Result += ", \n";
6207 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006208 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6209 if (Triple.getArch() == llvm::Triple::x86_64)
6210 // uint32_t const reserved; // only when building for 64bit targets
6211 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006212 // const uint8_t * const ivarLayout;
6213 Result += "0, \n\t";
6214 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006215 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006216 if (baseMethods.size() > 0) {
6217 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006218 if (metaclass)
6219 Result += "_OBJC_$_CLASS_METHODS_";
6220 else
6221 Result += "_OBJC_$_INSTANCE_METHODS_";
6222 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006223 Result += ",\n\t";
6224 }
6225 else
6226 Result += "0, \n\t";
6227
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006228 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006229 Result += "(const struct _objc_protocol_list *)&";
6230 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6231 Result += ",\n\t";
6232 }
6233 else
6234 Result += "0, \n\t";
6235
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006236 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006237 Result += "(const struct _ivar_list_t *)&";
6238 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6239 Result += ",\n\t";
6240 }
6241 else
6242 Result += "0, \n\t";
6243
6244 // weakIvarLayout
6245 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006246 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006247 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006248 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006249 Result += ",\n";
6250 }
6251 else
6252 Result += "0, \n";
6253
6254 Result += "};\n";
6255}
6256
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006257static void Write_class_t(ASTContext *Context, std::string &Result,
6258 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006259 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6260 bool rootClass = (!CDecl->getSuperClass());
6261 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006262
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006263 if (!rootClass) {
6264 // Find the Root class
6265 RootClass = CDecl->getSuperClass();
6266 while (RootClass->getSuperClass()) {
6267 RootClass = RootClass->getSuperClass();
6268 }
6269 }
6270
6271 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006272 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006273 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006274 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006275 if (CDecl->getImplementation())
6276 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006277 else
6278 Result += "__declspec(dllimport) ";
6279
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006280 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006281 Result += CDecl->getNameAsString();
6282 Result += ";\n";
6283 }
6284 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006285 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006286 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006287 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006288 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006289 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006290 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006291 else
6292 Result += "__declspec(dllimport) ";
6293
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006294 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006295 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006296 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006297 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006298
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006299 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006300 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006301 if (RootClass->getImplementation())
6302 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006303 else
6304 Result += "__declspec(dllimport) ";
6305
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006306 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006307 Result += VarName;
6308 Result += RootClass->getNameAsString();
6309 Result += ";\n";
6310 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006311 }
6312
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006313 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6314 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006315 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6316 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006317 if (metaclass) {
6318 if (!rootClass) {
6319 Result += "0, // &"; Result += VarName;
6320 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006321 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006322 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006323 Result += CDecl->getSuperClass()->getNameAsString();
6324 Result += ",\n\t";
6325 }
6326 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006327 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006328 Result += CDecl->getNameAsString();
6329 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006330 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006331 Result += ",\n\t";
6332 }
6333 }
6334 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006335 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006336 Result += CDecl->getNameAsString();
6337 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006338 if (!rootClass) {
6339 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006340 Result += CDecl->getSuperClass()->getNameAsString();
6341 Result += ",\n\t";
6342 }
6343 else
6344 Result += "0,\n\t";
6345 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006346 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6347 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6348 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006349 Result += "&_OBJC_METACLASS_RO_$_";
6350 else
6351 Result += "&_OBJC_CLASS_RO_$_";
6352 Result += CDecl->getNameAsString();
6353 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006354
6355 // Add static function to initialize some of the meta-data fields.
6356 // avoid doing it twice.
6357 if (metaclass)
6358 return;
6359
6360 const ObjCInterfaceDecl *SuperClass =
6361 rootClass ? CDecl : CDecl->getSuperClass();
6362
6363 Result += "static void OBJC_CLASS_SETUP_$_";
6364 Result += CDecl->getNameAsString();
6365 Result += "(void ) {\n";
6366 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6367 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006368 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006369
6370 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006371 Result += ".superclass = ";
6372 if (rootClass)
6373 Result += "&OBJC_CLASS_$_";
6374 else
6375 Result += "&OBJC_METACLASS_$_";
6376
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006377 Result += SuperClass->getNameAsString(); Result += ";\n";
6378
6379 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6380 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6381
6382 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6383 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6384 Result += CDecl->getNameAsString(); Result += ";\n";
6385
6386 if (!rootClass) {
6387 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6388 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6389 Result += SuperClass->getNameAsString(); Result += ";\n";
6390 }
6391
6392 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6393 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6394 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006395}
6396
Fariborz Jahanian61186122012-02-17 18:40:41 +00006397static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6398 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006399 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006400 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006401 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6402 ArrayRef<ObjCMethodDecl *> ClassMethods,
6403 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6404 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006405 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006406 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006407 // must declare an extern class object in case this class is not implemented
6408 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006409 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006410 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006411 if (ClassDecl->getImplementation())
6412 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006413 else
6414 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006415
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006416 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006417 Result += "OBJC_CLASS_$_"; Result += ClassName;
6418 Result += ";\n";
6419
Fariborz Jahanian61186122012-02-17 18:40:41 +00006420 Result += "\nstatic struct _category_t ";
6421 Result += "_OBJC_$_CATEGORY_";
6422 Result += ClassName; Result += "_$_"; Result += CatName;
6423 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6424 Result += "{\n";
6425 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006426 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006427 Result += ",\n";
6428 if (InstanceMethods.size() > 0) {
6429 Result += "\t(const struct _method_list_t *)&";
6430 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6431 Result += ClassName; Result += "_$_"; Result += CatName;
6432 Result += ",\n";
6433 }
6434 else
6435 Result += "\t0,\n";
6436
6437 if (ClassMethods.size() > 0) {
6438 Result += "\t(const struct _method_list_t *)&";
6439 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6440 Result += ClassName; Result += "_$_"; Result += CatName;
6441 Result += ",\n";
6442 }
6443 else
6444 Result += "\t0,\n";
6445
6446 if (RefedProtocols.size() > 0) {
6447 Result += "\t(const struct _protocol_list_t *)&";
6448 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6449 Result += ClassName; Result += "_$_"; Result += CatName;
6450 Result += ",\n";
6451 }
6452 else
6453 Result += "\t0,\n";
6454
6455 if (ClassProperties.size() > 0) {
6456 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6457 Result += ClassName; Result += "_$_"; Result += CatName;
6458 Result += ",\n";
6459 }
6460 else
6461 Result += "\t0,\n";
6462
6463 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006464
6465 // Add static function to initialize the class pointer in the category structure.
6466 Result += "static void OBJC_CATEGORY_SETUP_$_";
6467 Result += ClassDecl->getNameAsString();
6468 Result += "_$_";
6469 Result += CatName;
6470 Result += "(void ) {\n";
6471 Result += "\t_OBJC_$_CATEGORY_";
6472 Result += ClassDecl->getNameAsString();
6473 Result += "_$_";
6474 Result += CatName;
6475 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6476 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006477}
6478
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006479static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6480 ASTContext *Context, std::string &Result,
6481 ArrayRef<ObjCMethodDecl *> Methods,
6482 StringRef VarName,
6483 StringRef ProtocolName) {
6484 if (Methods.size() == 0)
6485 return;
6486
6487 Result += "\nstatic const char *";
6488 Result += VarName; Result += ProtocolName;
6489 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6490 Result += "{\n";
6491 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6492 ObjCMethodDecl *MD = Methods[i];
6493 std::string MethodTypeString, QuoteMethodTypeString;
6494 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6495 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6496 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6497 if (i == e-1)
6498 Result += "\n};\n";
6499 else {
6500 Result += ",\n";
6501 }
6502 }
6503}
6504
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006505static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6506 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006507 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006508 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006509 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006510 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6511 // this is what happens:
6512 /**
6513 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6514 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6515 Class->getVisibility() == HiddenVisibility)
6516 Visibility shoud be: HiddenVisibility;
6517 else
6518 Visibility shoud be: DefaultVisibility;
6519 */
6520
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006521 Result += "\n";
6522 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6523 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006524 if (Context->getLangOpts().MicrosoftExt)
6525 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6526
6527 if (!Context->getLangOpts().MicrosoftExt ||
6528 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006529 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006530 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006531 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006532 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006533 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006534 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6535 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006536 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6537 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006538 }
6539}
6540
Fariborz Jahanianae932952012-02-10 20:47:10 +00006541static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6542 ASTContext *Context, std::string &Result,
6543 ArrayRef<ObjCIvarDecl *> Ivars,
6544 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006545 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006546 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006547 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006548
Fariborz Jahanianae932952012-02-10 20:47:10 +00006549 Result += "\nstatic ";
6550 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6551 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006552 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006553 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6554 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6555 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6556 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6557 ObjCIvarDecl *IvarDecl = Ivars[i];
6558 if (i == 0)
6559 Result += "\t{{";
6560 else
6561 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006562 Result += "(unsigned long int *)&";
6563 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006564 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006565
6566 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6567 std::string IvarTypeString, QuoteIvarTypeString;
6568 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6569 IvarDecl);
6570 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6571 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6572
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006573 // FIXME. this alignment represents the host alignment and need be changed to
6574 // represent the target alignment.
6575 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6576 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006577 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006578 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6579 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006580 if (i == e-1)
6581 Result += "}}\n";
6582 else
6583 Result += "},\n";
6584 }
6585 Result += "};\n";
6586 }
6587}
6588
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006589/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006590void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6591 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006592
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006593 // Do not synthesize the protocol more than once.
6594 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6595 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006596 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006597
6598 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6599 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006600 // Must write out all protocol definitions in current qualifier list,
6601 // and in their nested qualifiers before writing out current definition.
6602 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6603 E = PDecl->protocol_end(); I != E; ++I)
6604 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006605
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006606 // Construct method lists.
6607 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6608 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6609 for (ObjCProtocolDecl::instmeth_iterator
6610 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6611 I != E; ++I) {
6612 ObjCMethodDecl *MD = *I;
6613 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6614 OptInstanceMethods.push_back(MD);
6615 } else {
6616 InstanceMethods.push_back(MD);
6617 }
6618 }
6619
6620 for (ObjCProtocolDecl::classmeth_iterator
6621 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6622 I != E; ++I) {
6623 ObjCMethodDecl *MD = *I;
6624 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6625 OptClassMethods.push_back(MD);
6626 } else {
6627 ClassMethods.push_back(MD);
6628 }
6629 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006630 std::vector<ObjCMethodDecl *> AllMethods;
6631 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6632 AllMethods.push_back(InstanceMethods[i]);
6633 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6634 AllMethods.push_back(ClassMethods[i]);
6635 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6636 AllMethods.push_back(OptInstanceMethods[i]);
6637 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6638 AllMethods.push_back(OptClassMethods[i]);
6639
6640 Write__extendedMethodTypes_initializer(*this, Context, Result,
6641 AllMethods,
6642 "_OBJC_PROTOCOL_METHOD_TYPES_",
6643 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006644 // Protocol's super protocol list
6645 std::vector<ObjCProtocolDecl *> SuperProtocols;
6646 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6647 E = PDecl->protocol_end(); I != E; ++I)
6648 SuperProtocols.push_back(*I);
6649
6650 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6651 "_OBJC_PROTOCOL_REFS_",
6652 PDecl->getNameAsString());
6653
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006654 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006655 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006656 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006657
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006658 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006659 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006660 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006661
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006662 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006663 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006664 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006665
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006666 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006667 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006668 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006669
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006670 // Protocol's property metadata.
6671 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6672 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6673 E = PDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00006674 ProtocolProperties.push_back(&*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006675
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006676 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006677 /* Container */0,
6678 "_OBJC_PROTOCOL_PROPERTIES_",
6679 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006680
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006681 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006682 Result += "\n";
6683 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006684 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006685 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006686 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006687 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6688 Result += "\t0,\n"; // id is; is null
6689 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006690 if (SuperProtocols.size() > 0) {
6691 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6692 Result += PDecl->getNameAsString(); Result += ",\n";
6693 }
6694 else
6695 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006696 if (InstanceMethods.size() > 0) {
6697 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6698 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006699 }
6700 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006701 Result += "\t0,\n";
6702
6703 if (ClassMethods.size() > 0) {
6704 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6705 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006706 }
6707 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006708 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006709
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006710 if (OptInstanceMethods.size() > 0) {
6711 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6712 Result += PDecl->getNameAsString(); Result += ",\n";
6713 }
6714 else
6715 Result += "\t0,\n";
6716
6717 if (OptClassMethods.size() > 0) {
6718 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6719 Result += PDecl->getNameAsString(); Result += ",\n";
6720 }
6721 else
6722 Result += "\t0,\n";
6723
6724 if (ProtocolProperties.size() > 0) {
6725 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6726 Result += PDecl->getNameAsString(); Result += ",\n";
6727 }
6728 else
6729 Result += "\t0,\n";
6730
6731 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6732 Result += "\t0,\n";
6733
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006734 if (AllMethods.size() > 0) {
6735 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6736 Result += PDecl->getNameAsString();
6737 Result += "\n};\n";
6738 }
6739 else
6740 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006741
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006742 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006743 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006744 Result += "struct _protocol_t *";
6745 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6746 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6747 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006748
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006749 // Mark this protocol as having been generated.
6750 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6751 llvm_unreachable("protocol already synthesized");
6752
6753}
6754
6755void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6756 const ObjCList<ObjCProtocolDecl> &Protocols,
6757 StringRef prefix, StringRef ClassName,
6758 std::string &Result) {
6759 if (Protocols.empty()) return;
6760
6761 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006762 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006763
6764 // Output the top lovel protocol meta-data for the class.
6765 /* struct _objc_protocol_list {
6766 struct _objc_protocol_list *next;
6767 int protocol_count;
6768 struct _objc_protocol *class_protocols[];
6769 }
6770 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006771 Result += "\n";
6772 if (LangOpts.MicrosoftExt)
6773 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6774 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006775 Result += "\tstruct _objc_protocol_list *next;\n";
6776 Result += "\tint protocol_count;\n";
6777 Result += "\tstruct _objc_protocol *class_protocols[";
6778 Result += utostr(Protocols.size());
6779 Result += "];\n} _OBJC_";
6780 Result += prefix;
6781 Result += "_PROTOCOLS_";
6782 Result += ClassName;
6783 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6784 "{\n\t0, ";
6785 Result += utostr(Protocols.size());
6786 Result += "\n";
6787
6788 Result += "\t,{&_OBJC_PROTOCOL_";
6789 Result += Protocols[0]->getNameAsString();
6790 Result += " \n";
6791
6792 for (unsigned i = 1; i != Protocols.size(); i++) {
6793 Result += "\t ,&_OBJC_PROTOCOL_";
6794 Result += Protocols[i]->getNameAsString();
6795 Result += "\n";
6796 }
6797 Result += "\t }\n};\n";
6798}
6799
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006800/// hasObjCExceptionAttribute - Return true if this class or any super
6801/// class has the __objc_exception__ attribute.
6802/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6803static bool hasObjCExceptionAttribute(ASTContext &Context,
6804 const ObjCInterfaceDecl *OID) {
6805 if (OID->hasAttr<ObjCExceptionAttr>())
6806 return true;
6807 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6808 return hasObjCExceptionAttribute(Context, Super);
6809 return false;
6810}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006811
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006812void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6813 std::string &Result) {
6814 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6815
6816 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006817 if (CDecl->isImplicitInterfaceDecl())
6818 assert(false &&
6819 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006820
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006821 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006822 SmallVector<ObjCIvarDecl *, 8> IVars;
6823
6824 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6825 IVD; IVD = IVD->getNextIvar()) {
6826 // Ignore unnamed bit-fields.
6827 if (!IVD->getDeclName())
6828 continue;
6829 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006830 }
6831
Fariborz Jahanianae932952012-02-10 20:47:10 +00006832 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006833 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006834 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006835
6836 // Build _objc_method_list for class's instance methods if needed
6837 SmallVector<ObjCMethodDecl *, 32>
6838 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6839
6840 // If any of our property implementations have associated getters or
6841 // setters, produce metadata for them as well.
6842 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6843 PropEnd = IDecl->propimpl_end();
6844 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00006845 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006846 continue;
David Blaikie262bc182012-04-30 02:36:29 +00006847 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006848 continue;
David Blaikie262bc182012-04-30 02:36:29 +00006849 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006850 if (!PD)
6851 continue;
6852 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00006853 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006854 InstanceMethods.push_back(Getter);
6855 if (PD->isReadOnly())
6856 continue;
6857 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00006858 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006859 InstanceMethods.push_back(Setter);
6860 }
6861
6862 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6863 "_OBJC_$_INSTANCE_METHODS_",
6864 IDecl->getNameAsString(), true);
6865
6866 SmallVector<ObjCMethodDecl *, 32>
6867 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6868
6869 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6870 "_OBJC_$_CLASS_METHODS_",
6871 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006872
6873 // Protocols referenced in class declaration?
6874 // Protocol's super protocol list
6875 std::vector<ObjCProtocolDecl *> RefedProtocols;
6876 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6877 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6878 E = Protocols.end();
6879 I != E; ++I) {
6880 RefedProtocols.push_back(*I);
6881 // Must write out all protocol definitions in current qualifier list,
6882 // and in their nested qualifiers before writing out current definition.
6883 RewriteObjCProtocolMetaData(*I, Result);
6884 }
6885
6886 Write_protocol_list_initializer(Context, Result,
6887 RefedProtocols,
6888 "_OBJC_CLASS_PROTOCOLS_$_",
6889 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006890
6891 // Protocol's property metadata.
6892 std::vector<ObjCPropertyDecl *> ClassProperties;
6893 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6894 E = CDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00006895 ClassProperties.push_back(&*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006896
6897 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006898 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006899 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006900 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006901
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006902
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006903 // Data for initializing _class_ro_t metaclass meta-data
6904 uint32_t flags = CLS_META;
6905 std::string InstanceSize;
6906 std::string InstanceStart;
6907
6908
6909 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6910 if (classIsHidden)
6911 flags |= OBJC2_CLS_HIDDEN;
6912
6913 if (!CDecl->getSuperClass())
6914 // class is root
6915 flags |= CLS_ROOT;
6916 InstanceSize = "sizeof(struct _class_t)";
6917 InstanceStart = InstanceSize;
6918 Write__class_ro_t_initializer(Context, Result, flags,
6919 InstanceStart, InstanceSize,
6920 ClassMethods,
6921 0,
6922 0,
6923 0,
6924 "_OBJC_METACLASS_RO_$_",
6925 CDecl->getNameAsString());
6926
6927
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006928 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006929 flags = CLS;
6930 if (classIsHidden)
6931 flags |= OBJC2_CLS_HIDDEN;
6932
6933 if (hasObjCExceptionAttribute(*Context, CDecl))
6934 flags |= CLS_EXCEPTION;
6935
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006936 if (!CDecl->getSuperClass())
6937 // class is root
6938 flags |= CLS_ROOT;
6939
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006940 InstanceSize.clear();
6941 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006942 if (!ObjCSynthesizedStructs.count(CDecl)) {
6943 InstanceSize = "0";
6944 InstanceStart = "0";
6945 }
6946 else {
6947 InstanceSize = "sizeof(struct ";
6948 InstanceSize += CDecl->getNameAsString();
6949 InstanceSize += "_IMPL)";
6950
6951 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6952 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006953 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006954 }
6955 else
6956 InstanceStart = InstanceSize;
6957 }
6958 Write__class_ro_t_initializer(Context, Result, flags,
6959 InstanceStart, InstanceSize,
6960 InstanceMethods,
6961 RefedProtocols,
6962 IVars,
6963 ClassProperties,
6964 "_OBJC_CLASS_RO_$_",
6965 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006966
6967 Write_class_t(Context, Result,
6968 "OBJC_METACLASS_$_",
6969 CDecl, /*metaclass*/true);
6970
6971 Write_class_t(Context, Result,
6972 "OBJC_CLASS_$_",
6973 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006974
6975 if (ImplementationIsNonLazy(IDecl))
6976 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006977
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006978}
6979
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006980void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6981 int ClsDefCount = ClassImplementation.size();
6982 if (!ClsDefCount)
6983 return;
6984 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6985 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6986 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6987 for (int i = 0; i < ClsDefCount; i++) {
6988 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6989 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6990 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6991 Result += CDecl->getName(); Result += ",\n";
6992 }
6993 Result += "};\n";
6994}
6995
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006996void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6997 int ClsDefCount = ClassImplementation.size();
6998 int CatDefCount = CategoryImplementation.size();
6999
7000 // For each implemented class, write out all its meta data.
7001 for (int i = 0; i < ClsDefCount; i++)
7002 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7003
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007004 RewriteClassSetupInitHook(Result);
7005
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007006 // For each implemented category, write out all its meta data.
7007 for (int i = 0; i < CatDefCount; i++)
7008 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7009
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007010 RewriteCategorySetupInitHook(Result);
7011
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007012 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007013 if (LangOpts.MicrosoftExt)
7014 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007015 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7016 Result += llvm::utostr(ClsDefCount); Result += "]";
7017 Result +=
7018 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7019 "regular,no_dead_strip\")))= {\n";
7020 for (int i = 0; i < ClsDefCount; i++) {
7021 Result += "\t&OBJC_CLASS_$_";
7022 Result += ClassImplementation[i]->getNameAsString();
7023 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007024 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007025 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007026
7027 if (!DefinedNonLazyClasses.empty()) {
7028 if (LangOpts.MicrosoftExt)
7029 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7030 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7031 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7032 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7033 Result += ",\n";
7034 }
7035 Result += "};\n";
7036 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007037 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007038
7039 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007040 if (LangOpts.MicrosoftExt)
7041 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007042 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7043 Result += llvm::utostr(CatDefCount); Result += "]";
7044 Result +=
7045 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7046 "regular,no_dead_strip\")))= {\n";
7047 for (int i = 0; i < CatDefCount; i++) {
7048 Result += "\t&_OBJC_$_CATEGORY_";
7049 Result +=
7050 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7051 Result += "_$_";
7052 Result += CategoryImplementation[i]->getNameAsString();
7053 Result += ",\n";
7054 }
7055 Result += "};\n";
7056 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007057
7058 if (!DefinedNonLazyCategories.empty()) {
7059 if (LangOpts.MicrosoftExt)
7060 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7061 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7062 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7063 Result += "\t&_OBJC_$_CATEGORY_";
7064 Result +=
7065 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7066 Result += "_$_";
7067 Result += DefinedNonLazyCategories[i]->getNameAsString();
7068 Result += ",\n";
7069 }
7070 Result += "};\n";
7071 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007072}
7073
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007074void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7075 if (LangOpts.MicrosoftExt)
7076 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7077
7078 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7079 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007080 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007081}
7082
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007083/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7084/// implementation.
7085void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7086 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007087 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007088 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7089 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007090 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007091 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7092 CDecl = CDecl->getNextClassCategory())
7093 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7094 break;
7095
7096 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007097 FullCategoryName += "_$_";
7098 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007099
7100 // Build _objc_method_list for class's instance methods if needed
7101 SmallVector<ObjCMethodDecl *, 32>
7102 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7103
7104 // If any of our property implementations have associated getters or
7105 // setters, produce metadata for them as well.
7106 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7107 PropEnd = IDecl->propimpl_end();
7108 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007109 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007110 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007111 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007112 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007113 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007114 if (!PD)
7115 continue;
7116 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7117 InstanceMethods.push_back(Getter);
7118 if (PD->isReadOnly())
7119 continue;
7120 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7121 InstanceMethods.push_back(Setter);
7122 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007123
Fariborz Jahanian61186122012-02-17 18:40:41 +00007124 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7125 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7126 FullCategoryName, true);
7127
7128 SmallVector<ObjCMethodDecl *, 32>
7129 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7130
7131 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7132 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7133 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007134
7135 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007136 // Protocol's super protocol list
7137 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007138 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7139 E = CDecl->protocol_end();
7140
7141 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007142 RefedProtocols.push_back(*I);
7143 // Must write out all protocol definitions in current qualifier list,
7144 // and in their nested qualifiers before writing out current definition.
7145 RewriteObjCProtocolMetaData(*I, Result);
7146 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007147
Fariborz Jahanian61186122012-02-17 18:40:41 +00007148 Write_protocol_list_initializer(Context, Result,
7149 RefedProtocols,
7150 "_OBJC_CATEGORY_PROTOCOLS_$_",
7151 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007152
Fariborz Jahanian61186122012-02-17 18:40:41 +00007153 // Protocol's property metadata.
7154 std::vector<ObjCPropertyDecl *> ClassProperties;
7155 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7156 E = CDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00007157 ClassProperties.push_back(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007158
Fariborz Jahanian61186122012-02-17 18:40:41 +00007159 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007160 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007161 "_OBJC_$_PROP_LIST_",
7162 FullCategoryName);
7163
7164 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007165 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007166 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007167 InstanceMethods,
7168 ClassMethods,
7169 RefedProtocols,
7170 ClassProperties);
7171
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007172 // Determine if this category is also "non-lazy".
7173 if (ImplementationIsNonLazy(IDecl))
7174 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007175
7176}
7177
7178void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7179 int CatDefCount = CategoryImplementation.size();
7180 if (!CatDefCount)
7181 return;
7182 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7183 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7184 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7185 for (int i = 0; i < CatDefCount; i++) {
7186 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7187 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7188 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7189 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7190 Result += ClassDecl->getName();
7191 Result += "_$_";
7192 Result += CatDecl->getName();
7193 Result += ",\n";
7194 }
7195 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007196}
7197
7198// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7199/// class methods.
7200template<typename MethodIterator>
7201void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7202 MethodIterator MethodEnd,
7203 bool IsInstanceMethod,
7204 StringRef prefix,
7205 StringRef ClassName,
7206 std::string &Result) {
7207 if (MethodBegin == MethodEnd) return;
7208
7209 if (!objc_impl_method) {
7210 /* struct _objc_method {
7211 SEL _cmd;
7212 char *method_types;
7213 void *_imp;
7214 }
7215 */
7216 Result += "\nstruct _objc_method {\n";
7217 Result += "\tSEL _cmd;\n";
7218 Result += "\tchar *method_types;\n";
7219 Result += "\tvoid *_imp;\n";
7220 Result += "};\n";
7221
7222 objc_impl_method = true;
7223 }
7224
7225 // Build _objc_method_list for class's methods if needed
7226
7227 /* struct {
7228 struct _objc_method_list *next_method;
7229 int method_count;
7230 struct _objc_method method_list[];
7231 }
7232 */
7233 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007234 Result += "\n";
7235 if (LangOpts.MicrosoftExt) {
7236 if (IsInstanceMethod)
7237 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7238 else
7239 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7240 }
7241 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007242 Result += "\tstruct _objc_method_list *next_method;\n";
7243 Result += "\tint method_count;\n";
7244 Result += "\tstruct _objc_method method_list[";
7245 Result += utostr(NumMethods);
7246 Result += "];\n} _OBJC_";
7247 Result += prefix;
7248 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7249 Result += "_METHODS_";
7250 Result += ClassName;
7251 Result += " __attribute__ ((used, section (\"__OBJC, __";
7252 Result += IsInstanceMethod ? "inst" : "cls";
7253 Result += "_meth\")))= ";
7254 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7255
7256 Result += "\t,{{(SEL)\"";
7257 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7258 std::string MethodTypeString;
7259 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7260 Result += "\", \"";
7261 Result += MethodTypeString;
7262 Result += "\", (void *)";
7263 Result += MethodInternalNames[*MethodBegin];
7264 Result += "}\n";
7265 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7266 Result += "\t ,{(SEL)\"";
7267 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7268 std::string MethodTypeString;
7269 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7270 Result += "\", \"";
7271 Result += MethodTypeString;
7272 Result += "\", (void *)";
7273 Result += MethodInternalNames[*MethodBegin];
7274 Result += "}\n";
7275 }
7276 Result += "\t }\n};\n";
7277}
7278
7279Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7280 SourceRange OldRange = IV->getSourceRange();
7281 Expr *BaseExpr = IV->getBase();
7282
7283 // Rewrite the base, but without actually doing replaces.
7284 {
7285 DisableReplaceStmtScope S(*this);
7286 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7287 IV->setBase(BaseExpr);
7288 }
7289
7290 ObjCIvarDecl *D = IV->getDecl();
7291
7292 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007293
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007294 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7295 const ObjCInterfaceType *iFaceDecl =
7296 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7297 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7298 // lookup which class implements the instance variable.
7299 ObjCInterfaceDecl *clsDeclared = 0;
7300 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7301 clsDeclared);
7302 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7303
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007304 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007305 std::string IvarOffsetName;
7306 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7307
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007308 ReferencedIvars[clsDeclared].insert(D);
7309
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007310 // cast offset to "char *".
7311 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7312 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007313 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007314 BaseExpr);
7315 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7316 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7317 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007318 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7319 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007320 SourceLocation());
7321 BinaryOperator *addExpr =
7322 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7323 Context->getPointerType(Context->CharTy),
7324 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007325 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007326 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7327 SourceLocation(),
7328 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007329 QualType IvarT = D->getType();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007330
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007331 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007332 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007333 RD = RD->getDefinition();
7334 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007335 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007336 ObjCContainerDecl *CDecl =
7337 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7338 // ivar in class extensions requires special treatment.
7339 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7340 CDecl = CatDecl->getClassInterface();
7341 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007342 RecName += "_IMPL";
7343 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7344 SourceLocation(), SourceLocation(),
7345 &Context->Idents.get(RecName.c_str()));
7346 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7347 unsigned UnsignedIntSize =
7348 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7349 Expr *Zero = IntegerLiteral::Create(*Context,
7350 llvm::APInt(UnsignedIntSize, 0),
7351 Context->UnsignedIntTy, SourceLocation());
7352 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7353 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7354 Zero);
7355 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7356 SourceLocation(),
7357 &Context->Idents.get(D->getNameAsString()),
7358 IvarT, 0,
7359 /*BitWidth=*/0, /*Mutable=*/true,
7360 /*HasInit=*/false);
7361 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7362 FD->getType(), VK_LValue,
7363 OK_Ordinary);
7364 IvarT = Context->getDecltypeType(ME, ME->getType());
7365 }
7366 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007367 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007368 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007369
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007370 castExpr = NoTypeInfoCStyleCastExpr(Context,
7371 castT,
7372 CK_BitCast,
7373 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007374
7375
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007376 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007377 VK_LValue, OK_Ordinary,
7378 SourceLocation());
7379 PE = new (Context) ParenExpr(OldRange.getBegin(),
7380 OldRange.getEnd(),
7381 Exp);
7382
7383 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007384 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007385
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007386 ReplaceStmtWithRange(IV, Replacement, OldRange);
7387 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007388}