blob: 2edfe6cdcd87cd5e58ef298560f624d232fb0a6c [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);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000310
311 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000312
313 // Expression Rewriting.
314 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
315 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
316 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
317 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
318 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
319 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
320 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000321 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000322 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000323 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000324 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000325 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000326 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
327 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
328 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
329 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
330 SourceLocation OrigEnd);
331 Stmt *RewriteBreakStmt(BreakStmt *S);
332 Stmt *RewriteContinueStmt(ContinueStmt *S);
333 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000334 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000335 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000336
337 // Block rewriting.
338 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
339
340 // Block specific rewrite rules.
341 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000342 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000343 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000344 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
345 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
346
347 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
348 std::string &Result);
349
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000350 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000351 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000352 bool &IsNamedDefinition);
353 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
354 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000355
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000356 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
357
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000358 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
359 std::string &Result);
360
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000361 virtual void Initialize(ASTContext &context);
362
363 // Misc. AST transformation routines. Somtimes they end up calling
364 // rewriting routines on the new ASTs.
365 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
366 Expr **args, unsigned nargs,
367 SourceLocation StartLoc=SourceLocation(),
368 SourceLocation EndLoc=SourceLocation());
369
370 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
371 SourceLocation StartLoc=SourceLocation(),
372 SourceLocation EndLoc=SourceLocation());
373
374 void SynthCountByEnumWithState(std::string &buf);
375 void SynthMsgSendFunctionDecl();
376 void SynthMsgSendSuperFunctionDecl();
377 void SynthMsgSendStretFunctionDecl();
378 void SynthMsgSendFpretFunctionDecl();
379 void SynthMsgSendSuperStretFunctionDecl();
380 void SynthGetClassFunctionDecl();
381 void SynthGetMetaClassFunctionDecl();
382 void SynthGetSuperClassFunctionDecl();
383 void SynthSelGetUidFunctionDecl();
384 void SynthSuperContructorFunctionDecl();
385
386 // Rewriting metadata
387 template<typename MethodIterator>
388 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
389 MethodIterator MethodEnd,
390 bool IsInstanceMethod,
391 StringRef prefix,
392 StringRef ClassName,
393 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000394 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
395 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000396 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000397 const ObjCList<ObjCProtocolDecl> &Prots,
398 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000399 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000400 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000401 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000402
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000403 void RewriteMetaDataIntoBuffer(std::string &Result);
404 void WriteImageInfo(std::string &Result);
405 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000406 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000407 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000408
409 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000410 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000411 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000412 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000413
414
415 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
416 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
417 StringRef funcName, std::string Tag);
418 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
419 StringRef funcName, std::string Tag);
420 std::string SynthesizeBlockImpl(BlockExpr *CE,
421 std::string Tag, std::string Desc);
422 std::string SynthesizeBlockDescriptor(std::string DescTag,
423 std::string ImplTag,
424 int i, StringRef funcName,
425 unsigned hasCopy);
426 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
427 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
428 StringRef FunName);
429 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
430 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000431 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000432
433 // Misc. helper routines.
434 QualType getProtocolType();
435 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000436 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
437 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
438 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
439
440 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
441 void CollectBlockDeclRefInfo(BlockExpr *Exp);
442 void GetBlockDeclRefExprs(Stmt *S);
443 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000444 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000445 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
446
447 // We avoid calling Type::isBlockPointerType(), since it operates on the
448 // canonical type. We only care if the top-level type is a closure pointer.
449 bool isTopLevelBlockPointerType(QualType T) {
450 return isa<BlockPointerType>(T);
451 }
452
453 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
454 /// to a function pointer type and upon success, returns true; false
455 /// otherwise.
456 bool convertBlockPointerToFunctionPointer(QualType &T) {
457 if (isTopLevelBlockPointerType(T)) {
458 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
459 T = Context->getPointerType(BPT->getPointeeType());
460 return true;
461 }
462 return false;
463 }
464
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000465 bool convertObjCTypeToCStyleType(QualType &T);
466
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000467 bool needToScanForQualifiers(QualType T);
468 QualType getSuperStructType();
469 QualType getConstantStringStructType();
470 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
471 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
472
473 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000474 if (T->isObjCQualifiedIdType()) {
475 bool isConst = T.isConstQualified();
476 T = isConst ? Context->getObjCIdType().withConst()
477 : Context->getObjCIdType();
478 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000479 else if (T->isObjCQualifiedClassType())
480 T = Context->getObjCClassType();
481 else if (T->isObjCObjectPointerType() &&
482 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
483 if (const ObjCObjectPointerType * OBJPT =
484 T->getAsObjCInterfacePointerType()) {
485 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
486 T = QualType(IFaceT, 0);
487 T = Context->getPointerType(T);
488 }
489 }
490 }
491
492 // FIXME: This predicate seems like it would be useful to add to ASTContext.
493 bool isObjCType(QualType T) {
494 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
495 return false;
496
497 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
498
499 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
500 OCT == Context->getCanonicalType(Context->getObjCClassType()))
501 return true;
502
503 if (const PointerType *PT = OCT->getAs<PointerType>()) {
504 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
505 PT->getPointeeType()->isObjCQualifiedIdType())
506 return true;
507 }
508 return false;
509 }
510 bool PointerTypeTakesAnyBlockArguments(QualType QT);
511 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
512 void GetExtentOfArgList(const char *Name, const char *&LParen,
513 const char *&RParen);
514
515 void QuoteDoublequotes(std::string &From, std::string &To) {
516 for (unsigned i = 0; i < From.length(); i++) {
517 if (From[i] == '"')
518 To += "\\\"";
519 else
520 To += From[i];
521 }
522 }
523
524 QualType getSimpleFunctionType(QualType result,
525 const QualType *args,
526 unsigned numArgs,
527 bool variadic = false) {
528 if (result == Context->getObjCInstanceType())
529 result = Context->getObjCIdType();
530 FunctionProtoType::ExtProtoInfo fpi;
531 fpi.Variadic = variadic;
532 return Context->getFunctionType(result, args, numArgs, fpi);
533 }
534
535 // Helper function: create a CStyleCastExpr with trivial type source info.
536 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
537 CastKind Kind, Expr *E) {
538 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
539 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
540 SourceLocation(), SourceLocation());
541 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000542
543 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
544 IdentifierInfo* II = &Context->Idents.get("load");
545 Selector LoadSel = Context->Selectors.getSelector(0, &II);
546 return OD->getClassMethod(LoadSel) != 0;
547 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000548 };
549
550}
551
552void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
553 NamedDecl *D) {
554 if (const FunctionProtoType *fproto
555 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
556 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
557 E = fproto->arg_type_end(); I && (I != E); ++I)
558 if (isTopLevelBlockPointerType(*I)) {
559 // All the args are checked/rewritten. Don't call twice!
560 RewriteBlockPointerDecl(D);
561 break;
562 }
563 }
564}
565
566void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
567 const PointerType *PT = funcType->getAs<PointerType>();
568 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
569 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
570}
571
572static bool IsHeaderFile(const std::string &Filename) {
573 std::string::size_type DotPos = Filename.rfind('.');
574
575 if (DotPos == std::string::npos) {
576 // no file extension
577 return false;
578 }
579
580 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
581 // C header: .h
582 // C++ header: .hh or .H;
583 return Ext == "h" || Ext == "hh" || Ext == "H";
584}
585
586RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
587 DiagnosticsEngine &D, const LangOptions &LOpts,
588 bool silenceMacroWarn)
589 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
590 SilenceRewriteMacroWarning(silenceMacroWarn) {
591 IsHeader = IsHeaderFile(inFile);
592 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
593 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000594 // FIXME. This should be an error. But if block is not called, it is OK. And it
595 // may break including some headers.
596 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
597 "rewriting block literal declared in global scope is not implemented");
598
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000599 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
600 DiagnosticsEngine::Warning,
601 "rewriter doesn't support user-specified control flow semantics "
602 "for @try/@finally (code may not execute properly)");
603}
604
605ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
606 raw_ostream* OS,
607 DiagnosticsEngine &Diags,
608 const LangOptions &LOpts,
609 bool SilenceRewriteMacroWarning) {
610 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
611}
612
613void RewriteModernObjC::InitializeCommon(ASTContext &context) {
614 Context = &context;
615 SM = &Context->getSourceManager();
616 TUDecl = Context->getTranslationUnitDecl();
617 MsgSendFunctionDecl = 0;
618 MsgSendSuperFunctionDecl = 0;
619 MsgSendStretFunctionDecl = 0;
620 MsgSendSuperStretFunctionDecl = 0;
621 MsgSendFpretFunctionDecl = 0;
622 GetClassFunctionDecl = 0;
623 GetMetaClassFunctionDecl = 0;
624 GetSuperClassFunctionDecl = 0;
625 SelGetUidFunctionDecl = 0;
626 CFStringFunctionDecl = 0;
627 ConstantStringClassReference = 0;
628 NSStringRecord = 0;
629 CurMethodDef = 0;
630 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000631 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000632 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000633 SuperStructDecl = 0;
634 ProtocolTypeDecl = 0;
635 ConstantStringDecl = 0;
636 BcLabelCount = 0;
637 SuperContructorFunctionDecl = 0;
638 NumObjCStringLiterals = 0;
639 PropParentMap = 0;
640 CurrentBody = 0;
641 DisableReplaceStmt = false;
642 objc_impl_method = false;
643
644 // Get the ID and start/end of the main file.
645 MainFileID = SM->getMainFileID();
646 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
647 MainFileStart = MainBuf->getBufferStart();
648 MainFileEnd = MainBuf->getBufferEnd();
649
David Blaikie4e4d0842012-03-11 07:00:24 +0000650 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000651}
652
653//===----------------------------------------------------------------------===//
654// Top Level Driver Code
655//===----------------------------------------------------------------------===//
656
657void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
658 if (Diags.hasErrorOccurred())
659 return;
660
661 // Two cases: either the decl could be in the main file, or it could be in a
662 // #included file. If the former, rewrite it now. If the later, check to see
663 // if we rewrote the #include/#import.
664 SourceLocation Loc = D->getLocation();
665 Loc = SM->getExpansionLoc(Loc);
666
667 // If this is for a builtin, ignore it.
668 if (Loc.isInvalid()) return;
669
670 // Look for built-in declarations that we need to refer during the rewrite.
671 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
672 RewriteFunctionDecl(FD);
673 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
674 // declared in <Foundation/NSString.h>
675 if (FVD->getName() == "_NSConstantStringClassReference") {
676 ConstantStringClassReference = FVD;
677 return;
678 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000679 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
680 RewriteCategoryDecl(CD);
681 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
682 if (PD->isThisDeclarationADefinition())
683 RewriteProtocolDecl(PD);
684 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000685 // FIXME. This will not work in all situations and leaving it out
686 // is harmless.
687 // RewriteLinkageSpec(LSD);
688
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000689 // Recurse into linkage specifications
690 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
691 DIEnd = LSD->decls_end();
692 DI != DIEnd; ) {
693 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
694 if (!IFace->isThisDeclarationADefinition()) {
695 SmallVector<Decl *, 8> DG;
696 SourceLocation StartLoc = IFace->getLocStart();
697 do {
698 if (isa<ObjCInterfaceDecl>(*DI) &&
699 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
700 StartLoc == (*DI)->getLocStart())
701 DG.push_back(*DI);
702 else
703 break;
704
705 ++DI;
706 } while (DI != DIEnd);
707 RewriteForwardClassDecl(DG);
708 continue;
709 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000710 else {
711 // Keep track of all interface declarations seen.
712 ObjCInterfacesSeen.push_back(IFace);
713 ++DI;
714 continue;
715 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000716 }
717
718 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
719 if (!Proto->isThisDeclarationADefinition()) {
720 SmallVector<Decl *, 8> DG;
721 SourceLocation StartLoc = Proto->getLocStart();
722 do {
723 if (isa<ObjCProtocolDecl>(*DI) &&
724 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
725 StartLoc == (*DI)->getLocStart())
726 DG.push_back(*DI);
727 else
728 break;
729
730 ++DI;
731 } while (DI != DIEnd);
732 RewriteForwardProtocolDecl(DG);
733 continue;
734 }
735 }
736
737 HandleTopLevelSingleDecl(*DI);
738 ++DI;
739 }
740 }
741 // If we have a decl in the main file, see if we should rewrite it.
742 if (SM->isFromMainFile(Loc))
743 return HandleDeclInMainFile(D);
744}
745
746//===----------------------------------------------------------------------===//
747// Syntactic (non-AST) Rewriting Code
748//===----------------------------------------------------------------------===//
749
750void RewriteModernObjC::RewriteInclude() {
751 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
752 StringRef MainBuf = SM->getBufferData(MainFileID);
753 const char *MainBufStart = MainBuf.begin();
754 const char *MainBufEnd = MainBuf.end();
755 size_t ImportLen = strlen("import");
756
757 // Loop over the whole file, looking for includes.
758 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
759 if (*BufPtr == '#') {
760 if (++BufPtr == MainBufEnd)
761 return;
762 while (*BufPtr == ' ' || *BufPtr == '\t')
763 if (++BufPtr == MainBufEnd)
764 return;
765 if (!strncmp(BufPtr, "import", ImportLen)) {
766 // replace import with include
767 SourceLocation ImportLoc =
768 LocStart.getLocWithOffset(BufPtr-MainBufStart);
769 ReplaceText(ImportLoc, ImportLen, "include");
770 BufPtr += ImportLen;
771 }
772 }
773 }
774}
775
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000776static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
777 ObjCIvarDecl *IvarDecl, std::string &Result) {
778 Result += "OBJC_IVAR_$_";
779 Result += IDecl->getName();
780 Result += "$";
781 Result += IvarDecl->getName();
782}
783
784std::string
785RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
786 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
787
788 // Build name of symbol holding ivar offset.
789 std::string IvarOffsetName;
790 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
791
792
793 std::string S = "(*(";
794 QualType IvarT = D->getType();
795
796 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
797 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
798 RD = RD->getDefinition();
799 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
800 // decltype(((Foo_IMPL*)0)->bar) *
801 ObjCContainerDecl *CDecl =
802 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
803 // ivar in class extensions requires special treatment.
804 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
805 CDecl = CatDecl->getClassInterface();
806 std::string RecName = CDecl->getName();
807 RecName += "_IMPL";
808 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
809 SourceLocation(), SourceLocation(),
810 &Context->Idents.get(RecName.c_str()));
811 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
812 unsigned UnsignedIntSize =
813 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
814 Expr *Zero = IntegerLiteral::Create(*Context,
815 llvm::APInt(UnsignedIntSize, 0),
816 Context->UnsignedIntTy, SourceLocation());
817 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
818 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
819 Zero);
820 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
821 SourceLocation(),
822 &Context->Idents.get(D->getNameAsString()),
823 IvarT, 0,
824 /*BitWidth=*/0, /*Mutable=*/true,
825 /*HasInit=*/false);
826 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
827 FD->getType(), VK_LValue,
828 OK_Ordinary);
829 IvarT = Context->getDecltypeType(ME, ME->getType());
830 }
831 }
832 convertObjCTypeToCStyleType(IvarT);
833 QualType castT = Context->getPointerType(IvarT);
834 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
835 S += TypeString;
836 S += ")";
837
838 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
839 S += "((char *)self + ";
840 S += IvarOffsetName;
841 S += "))";
842 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000843 return S;
844}
845
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000846/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
847/// been found in the class implementation. In this case, it must be synthesized.
848static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
849 ObjCPropertyDecl *PD,
850 bool getter) {
851 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
852 : !IMP->getInstanceMethod(PD->getSetterName());
853
854}
855
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000856void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
857 ObjCImplementationDecl *IMD,
858 ObjCCategoryImplDecl *CID) {
859 static bool objcGetPropertyDefined = false;
860 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000861 SourceLocation startGetterSetterLoc;
862
863 if (PID->getLocStart().isValid()) {
864 SourceLocation startLoc = PID->getLocStart();
865 InsertText(startLoc, "// ");
866 const char *startBuf = SM->getCharacterData(startLoc);
867 assert((*startBuf == '@') && "bogus @synthesize location");
868 const char *semiBuf = strchr(startBuf, ';');
869 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
870 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
871 }
872 else
873 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000874
875 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
876 return; // FIXME: is this correct?
877
878 // Generate the 'getter' function.
879 ObjCPropertyDecl *PD = PID->getPropertyDecl();
880 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
881
882 if (!OID)
883 return;
884 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000885 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000886 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
887 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
888 ObjCPropertyDecl::OBJC_PR_copy));
889 std::string Getr;
890 if (GenGetProperty && !objcGetPropertyDefined) {
891 objcGetPropertyDefined = true;
892 // FIXME. Is this attribute correct in all cases?
893 Getr = "\nextern \"C\" __declspec(dllimport) "
894 "id objc_getProperty(id, SEL, long, bool);\n";
895 }
896 RewriteObjCMethodDecl(OID->getContainingInterface(),
897 PD->getGetterMethodDecl(), Getr);
898 Getr += "{ ";
899 // Synthesize an explicit cast to gain access to the ivar.
900 // See objc-act.c:objc_synthesize_new_getter() for details.
901 if (GenGetProperty) {
902 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
903 Getr += "typedef ";
904 const FunctionType *FPRetType = 0;
905 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
906 FPRetType);
907 Getr += " _TYPE";
908 if (FPRetType) {
909 Getr += ")"; // close the precedence "scope" for "*".
910
911 // Now, emit the argument types (if any).
912 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
913 Getr += "(";
914 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
915 if (i) Getr += ", ";
916 std::string ParamStr = FT->getArgType(i).getAsString(
917 Context->getPrintingPolicy());
918 Getr += ParamStr;
919 }
920 if (FT->isVariadic()) {
921 if (FT->getNumArgs()) Getr += ", ";
922 Getr += "...";
923 }
924 Getr += ")";
925 } else
926 Getr += "()";
927 }
928 Getr += ";\n";
929 Getr += "return (_TYPE)";
930 Getr += "objc_getProperty(self, _cmd, ";
931 RewriteIvarOffsetComputation(OID, Getr);
932 Getr += ", 1)";
933 }
934 else
935 Getr += "return " + getIvarAccessString(OID);
936 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000937 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000938 }
939
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000940 if (PD->isReadOnly() ||
941 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000942 return;
943
944 // Generate the 'setter' function.
945 std::string Setr;
946 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
947 ObjCPropertyDecl::OBJC_PR_copy);
948 if (GenSetProperty && !objcSetPropertyDefined) {
949 objcSetPropertyDefined = true;
950 // FIXME. Is this attribute correct in all cases?
951 Setr = "\nextern \"C\" __declspec(dllimport) "
952 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
953 }
954
955 RewriteObjCMethodDecl(OID->getContainingInterface(),
956 PD->getSetterMethodDecl(), Setr);
957 Setr += "{ ";
958 // Synthesize an explicit cast to initialize the ivar.
959 // See objc-act.c:objc_synthesize_new_setter() for details.
960 if (GenSetProperty) {
961 Setr += "objc_setProperty (self, _cmd, ";
962 RewriteIvarOffsetComputation(OID, Setr);
963 Setr += ", (id)";
964 Setr += PD->getName();
965 Setr += ", ";
966 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
967 Setr += "0, ";
968 else
969 Setr += "1, ";
970 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
971 Setr += "1)";
972 else
973 Setr += "0)";
974 }
975 else {
976 Setr += getIvarAccessString(OID) + " = ";
977 Setr += PD->getName();
978 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000979 Setr += "; }\n";
980 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000981}
982
983static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
984 std::string &typedefString) {
985 typedefString += "#ifndef _REWRITER_typedef_";
986 typedefString += ForwardDecl->getNameAsString();
987 typedefString += "\n";
988 typedefString += "#define _REWRITER_typedef_";
989 typedefString += ForwardDecl->getNameAsString();
990 typedefString += "\n";
991 typedefString += "typedef struct objc_object ";
992 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000993 // typedef struct { } _objc_exc_Classname;
994 typedefString += ";\ntypedef struct {} _objc_exc_";
995 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000996 typedefString += ";\n#endif\n";
997}
998
999void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1000 const std::string &typedefString) {
1001 SourceLocation startLoc = ClassDecl->getLocStart();
1002 const char *startBuf = SM->getCharacterData(startLoc);
1003 const char *semiPtr = strchr(startBuf, ';');
1004 // Replace the @class with typedefs corresponding to the classes.
1005 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1006}
1007
1008void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1009 std::string typedefString;
1010 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1011 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1012 if (I == D.begin()) {
1013 // Translate to typedef's that forward reference structs with the same name
1014 // as the class. As a convenience, we include the original declaration
1015 // as a comment.
1016 typedefString += "// @class ";
1017 typedefString += ForwardDecl->getNameAsString();
1018 typedefString += ";\n";
1019 }
1020 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1021 }
1022 DeclGroupRef::iterator I = D.begin();
1023 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1024}
1025
1026void RewriteModernObjC::RewriteForwardClassDecl(
1027 const llvm::SmallVector<Decl*, 8> &D) {
1028 std::string typedefString;
1029 for (unsigned i = 0; i < D.size(); i++) {
1030 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1031 if (i == 0) {
1032 typedefString += "// @class ";
1033 typedefString += ForwardDecl->getNameAsString();
1034 typedefString += ";\n";
1035 }
1036 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1037 }
1038 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1039}
1040
1041void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1042 // When method is a synthesized one, such as a getter/setter there is
1043 // nothing to rewrite.
1044 if (Method->isImplicit())
1045 return;
1046 SourceLocation LocStart = Method->getLocStart();
1047 SourceLocation LocEnd = Method->getLocEnd();
1048
1049 if (SM->getExpansionLineNumber(LocEnd) >
1050 SM->getExpansionLineNumber(LocStart)) {
1051 InsertText(LocStart, "#if 0\n");
1052 ReplaceText(LocEnd, 1, ";\n#endif\n");
1053 } else {
1054 InsertText(LocStart, "// ");
1055 }
1056}
1057
1058void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1059 SourceLocation Loc = prop->getAtLoc();
1060
1061 ReplaceText(Loc, 0, "// ");
1062 // FIXME: handle properties that are declared across multiple lines.
1063}
1064
1065void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1066 SourceLocation LocStart = CatDecl->getLocStart();
1067
1068 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001069 if (CatDecl->getIvarRBraceLoc().isValid()) {
1070 ReplaceText(LocStart, 1, "/** ");
1071 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1072 }
1073 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001074 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001075 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001076
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001077 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1078 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001079 RewriteProperty(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001080
1081 for (ObjCCategoryDecl::instmeth_iterator
1082 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1083 I != E; ++I)
1084 RewriteMethodDeclaration(*I);
1085 for (ObjCCategoryDecl::classmeth_iterator
1086 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1087 I != E; ++I)
1088 RewriteMethodDeclaration(*I);
1089
1090 // Lastly, comment out the @end.
1091 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1092 strlen("@end"), "/* @end */");
1093}
1094
1095void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1096 SourceLocation LocStart = PDecl->getLocStart();
1097 assert(PDecl->isThisDeclarationADefinition());
1098
1099 // FIXME: handle protocol headers that are declared across multiple lines.
1100 ReplaceText(LocStart, 0, "// ");
1101
1102 for (ObjCProtocolDecl::instmeth_iterator
1103 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1104 I != E; ++I)
1105 RewriteMethodDeclaration(*I);
1106 for (ObjCProtocolDecl::classmeth_iterator
1107 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1108 I != E; ++I)
1109 RewriteMethodDeclaration(*I);
1110
1111 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1112 E = PDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001113 RewriteProperty(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001114
1115 // Lastly, comment out the @end.
1116 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1117 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1118
1119 // Must comment out @optional/@required
1120 const char *startBuf = SM->getCharacterData(LocStart);
1121 const char *endBuf = SM->getCharacterData(LocEnd);
1122 for (const char *p = startBuf; p < endBuf; p++) {
1123 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1124 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1125 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1126
1127 }
1128 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1129 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1130 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1131
1132 }
1133 }
1134}
1135
1136void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1137 SourceLocation LocStart = (*D.begin())->getLocStart();
1138 if (LocStart.isInvalid())
1139 llvm_unreachable("Invalid SourceLocation");
1140 // FIXME: handle forward protocol that are declared across multiple lines.
1141 ReplaceText(LocStart, 0, "// ");
1142}
1143
1144void
1145RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1146 SourceLocation LocStart = DG[0]->getLocStart();
1147 if (LocStart.isInvalid())
1148 llvm_unreachable("Invalid SourceLocation");
1149 // FIXME: handle forward protocol that are declared across multiple lines.
1150 ReplaceText(LocStart, 0, "// ");
1151}
1152
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001153void
1154RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1155 SourceLocation LocStart = LSD->getExternLoc();
1156 if (LocStart.isInvalid())
1157 llvm_unreachable("Invalid extern SourceLocation");
1158
1159 ReplaceText(LocStart, 0, "// ");
1160 if (!LSD->hasBraces())
1161 return;
1162 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1163 SourceLocation LocRBrace = LSD->getRBraceLoc();
1164 if (LocRBrace.isInvalid())
1165 llvm_unreachable("Invalid rbrace SourceLocation");
1166 ReplaceText(LocRBrace, 0, "// ");
1167}
1168
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001169void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1170 const FunctionType *&FPRetType) {
1171 if (T->isObjCQualifiedIdType())
1172 ResultStr += "id";
1173 else if (T->isFunctionPointerType() ||
1174 T->isBlockPointerType()) {
1175 // needs special handling, since pointer-to-functions have special
1176 // syntax (where a decaration models use).
1177 QualType retType = T;
1178 QualType PointeeTy;
1179 if (const PointerType* PT = retType->getAs<PointerType>())
1180 PointeeTy = PT->getPointeeType();
1181 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1182 PointeeTy = BPT->getPointeeType();
1183 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1184 ResultStr += FPRetType->getResultType().getAsString(
1185 Context->getPrintingPolicy());
1186 ResultStr += "(*";
1187 }
1188 } else
1189 ResultStr += T.getAsString(Context->getPrintingPolicy());
1190}
1191
1192void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1193 ObjCMethodDecl *OMD,
1194 std::string &ResultStr) {
1195 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1196 const FunctionType *FPRetType = 0;
1197 ResultStr += "\nstatic ";
1198 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1199 ResultStr += " ";
1200
1201 // Unique method name
1202 std::string NameStr;
1203
1204 if (OMD->isInstanceMethod())
1205 NameStr += "_I_";
1206 else
1207 NameStr += "_C_";
1208
1209 NameStr += IDecl->getNameAsString();
1210 NameStr += "_";
1211
1212 if (ObjCCategoryImplDecl *CID =
1213 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1214 NameStr += CID->getNameAsString();
1215 NameStr += "_";
1216 }
1217 // Append selector names, replacing ':' with '_'
1218 {
1219 std::string selString = OMD->getSelector().getAsString();
1220 int len = selString.size();
1221 for (int i = 0; i < len; i++)
1222 if (selString[i] == ':')
1223 selString[i] = '_';
1224 NameStr += selString;
1225 }
1226 // Remember this name for metadata emission
1227 MethodInternalNames[OMD] = NameStr;
1228 ResultStr += NameStr;
1229
1230 // Rewrite arguments
1231 ResultStr += "(";
1232
1233 // invisible arguments
1234 if (OMD->isInstanceMethod()) {
1235 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1236 selfTy = Context->getPointerType(selfTy);
1237 if (!LangOpts.MicrosoftExt) {
1238 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1239 ResultStr += "struct ";
1240 }
1241 // When rewriting for Microsoft, explicitly omit the structure name.
1242 ResultStr += IDecl->getNameAsString();
1243 ResultStr += " *";
1244 }
1245 else
1246 ResultStr += Context->getObjCClassType().getAsString(
1247 Context->getPrintingPolicy());
1248
1249 ResultStr += " self, ";
1250 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1251 ResultStr += " _cmd";
1252
1253 // Method arguments.
1254 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1255 E = OMD->param_end(); PI != E; ++PI) {
1256 ParmVarDecl *PDecl = *PI;
1257 ResultStr += ", ";
1258 if (PDecl->getType()->isObjCQualifiedIdType()) {
1259 ResultStr += "id ";
1260 ResultStr += PDecl->getNameAsString();
1261 } else {
1262 std::string Name = PDecl->getNameAsString();
1263 QualType QT = PDecl->getType();
1264 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001265 (void)convertBlockPointerToFunctionPointer(QT);
1266 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001267 ResultStr += Name;
1268 }
1269 }
1270 if (OMD->isVariadic())
1271 ResultStr += ", ...";
1272 ResultStr += ") ";
1273
1274 if (FPRetType) {
1275 ResultStr += ")"; // close the precedence "scope" for "*".
1276
1277 // Now, emit the argument types (if any).
1278 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1279 ResultStr += "(";
1280 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1281 if (i) ResultStr += ", ";
1282 std::string ParamStr = FT->getArgType(i).getAsString(
1283 Context->getPrintingPolicy());
1284 ResultStr += ParamStr;
1285 }
1286 if (FT->isVariadic()) {
1287 if (FT->getNumArgs()) ResultStr += ", ";
1288 ResultStr += "...";
1289 }
1290 ResultStr += ")";
1291 } else {
1292 ResultStr += "()";
1293 }
1294 }
1295}
1296void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1297 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1298 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1299
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001300 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001301 if (IMD->getIvarRBraceLoc().isValid()) {
1302 ReplaceText(IMD->getLocStart(), 1, "/** ");
1303 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001304 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001305 else {
1306 InsertText(IMD->getLocStart(), "// ");
1307 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001308 }
1309 else
1310 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001311
1312 for (ObjCCategoryImplDecl::instmeth_iterator
1313 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1314 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1315 I != E; ++I) {
1316 std::string ResultStr;
1317 ObjCMethodDecl *OMD = *I;
1318 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1319 SourceLocation LocStart = OMD->getLocStart();
1320 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1321
1322 const char *startBuf = SM->getCharacterData(LocStart);
1323 const char *endBuf = SM->getCharacterData(LocEnd);
1324 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1325 }
1326
1327 for (ObjCCategoryImplDecl::classmeth_iterator
1328 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1329 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1330 I != E; ++I) {
1331 std::string ResultStr;
1332 ObjCMethodDecl *OMD = *I;
1333 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1334 SourceLocation LocStart = OMD->getLocStart();
1335 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1336
1337 const char *startBuf = SM->getCharacterData(LocStart);
1338 const char *endBuf = SM->getCharacterData(LocEnd);
1339 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1340 }
1341 for (ObjCCategoryImplDecl::propimpl_iterator
1342 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1343 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1344 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001345 RewritePropertyImplDecl(&*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001346 }
1347
1348 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1349}
1350
1351void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001352 // Do not synthesize more than once.
1353 if (ObjCSynthesizedStructs.count(ClassDecl))
1354 return;
1355 // Make sure super class's are written before current class is written.
1356 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1357 while (SuperClass) {
1358 RewriteInterfaceDecl(SuperClass);
1359 SuperClass = SuperClass->getSuperClass();
1360 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001361 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001362 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001363 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001364 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001365 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1366
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001367 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001368 // Mark this typedef as having been written into its c++ equivalent.
1369 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001370
1371 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001372 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001373 RewriteProperty(&*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001374 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001375 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001376 I != E; ++I)
1377 RewriteMethodDeclaration(*I);
1378 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001379 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001380 I != E; ++I)
1381 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001382
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001383 // Lastly, comment out the @end.
1384 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1385 "/* @end */");
1386 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001387}
1388
1389Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1390 SourceRange OldRange = PseudoOp->getSourceRange();
1391
1392 // We just magically know some things about the structure of this
1393 // expression.
1394 ObjCMessageExpr *OldMsg =
1395 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1396 PseudoOp->getNumSemanticExprs() - 1));
1397
1398 // Because the rewriter doesn't allow us to rewrite rewritten code,
1399 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001400 Expr *Base;
1401 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001402 {
1403 DisableReplaceStmtScope S(*this);
1404
1405 // Rebuild the base expression if we have one.
1406 Base = 0;
1407 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1408 Base = OldMsg->getInstanceReceiver();
1409 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1410 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1411 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001412
1413 unsigned numArgs = OldMsg->getNumArgs();
1414 for (unsigned i = 0; i < numArgs; i++) {
1415 Expr *Arg = OldMsg->getArg(i);
1416 if (isa<OpaqueValueExpr>(Arg))
1417 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1418 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1419 Args.push_back(Arg);
1420 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001421 }
1422
1423 // TODO: avoid this copy.
1424 SmallVector<SourceLocation, 1> SelLocs;
1425 OldMsg->getSelectorLocs(SelLocs);
1426
1427 ObjCMessageExpr *NewMsg = 0;
1428 switch (OldMsg->getReceiverKind()) {
1429 case ObjCMessageExpr::Class:
1430 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1431 OldMsg->getValueKind(),
1432 OldMsg->getLeftLoc(),
1433 OldMsg->getClassReceiverTypeInfo(),
1434 OldMsg->getSelector(),
1435 SelLocs,
1436 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001437 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001438 OldMsg->getRightLoc(),
1439 OldMsg->isImplicit());
1440 break;
1441
1442 case ObjCMessageExpr::Instance:
1443 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1444 OldMsg->getValueKind(),
1445 OldMsg->getLeftLoc(),
1446 Base,
1447 OldMsg->getSelector(),
1448 SelLocs,
1449 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001450 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001451 OldMsg->getRightLoc(),
1452 OldMsg->isImplicit());
1453 break;
1454
1455 case ObjCMessageExpr::SuperClass:
1456 case ObjCMessageExpr::SuperInstance:
1457 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1458 OldMsg->getValueKind(),
1459 OldMsg->getLeftLoc(),
1460 OldMsg->getSuperLoc(),
1461 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1462 OldMsg->getSuperType(),
1463 OldMsg->getSelector(),
1464 SelLocs,
1465 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001466 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001467 OldMsg->getRightLoc(),
1468 OldMsg->isImplicit());
1469 break;
1470 }
1471
1472 Stmt *Replacement = SynthMessageExpr(NewMsg);
1473 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1474 return Replacement;
1475}
1476
1477Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1478 SourceRange OldRange = PseudoOp->getSourceRange();
1479
1480 // We just magically know some things about the structure of this
1481 // expression.
1482 ObjCMessageExpr *OldMsg =
1483 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1484
1485 // Because the rewriter doesn't allow us to rewrite rewritten code,
1486 // we need to suppress rewriting the sub-statements.
1487 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001488 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001489 {
1490 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001491 // Rebuild the base expression if we have one.
1492 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1493 Base = OldMsg->getInstanceReceiver();
1494 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1495 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1496 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001497 unsigned numArgs = OldMsg->getNumArgs();
1498 for (unsigned i = 0; i < numArgs; i++) {
1499 Expr *Arg = OldMsg->getArg(i);
1500 if (isa<OpaqueValueExpr>(Arg))
1501 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1502 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1503 Args.push_back(Arg);
1504 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001505 }
1506
1507 // Intentionally empty.
1508 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001509
1510 ObjCMessageExpr *NewMsg = 0;
1511 switch (OldMsg->getReceiverKind()) {
1512 case ObjCMessageExpr::Class:
1513 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1514 OldMsg->getValueKind(),
1515 OldMsg->getLeftLoc(),
1516 OldMsg->getClassReceiverTypeInfo(),
1517 OldMsg->getSelector(),
1518 SelLocs,
1519 OldMsg->getMethodDecl(),
1520 Args,
1521 OldMsg->getRightLoc(),
1522 OldMsg->isImplicit());
1523 break;
1524
1525 case ObjCMessageExpr::Instance:
1526 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1527 OldMsg->getValueKind(),
1528 OldMsg->getLeftLoc(),
1529 Base,
1530 OldMsg->getSelector(),
1531 SelLocs,
1532 OldMsg->getMethodDecl(),
1533 Args,
1534 OldMsg->getRightLoc(),
1535 OldMsg->isImplicit());
1536 break;
1537
1538 case ObjCMessageExpr::SuperClass:
1539 case ObjCMessageExpr::SuperInstance:
1540 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1541 OldMsg->getValueKind(),
1542 OldMsg->getLeftLoc(),
1543 OldMsg->getSuperLoc(),
1544 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1545 OldMsg->getSuperType(),
1546 OldMsg->getSelector(),
1547 SelLocs,
1548 OldMsg->getMethodDecl(),
1549 Args,
1550 OldMsg->getRightLoc(),
1551 OldMsg->isImplicit());
1552 break;
1553 }
1554
1555 Stmt *Replacement = SynthMessageExpr(NewMsg);
1556 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1557 return Replacement;
1558}
1559
1560/// SynthCountByEnumWithState - To print:
1561/// ((unsigned int (*)
1562/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1563/// (void *)objc_msgSend)((id)l_collection,
1564/// sel_registerName(
1565/// "countByEnumeratingWithState:objects:count:"),
1566/// &enumState,
1567/// (id *)__rw_items, (unsigned int)16)
1568///
1569void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1570 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1571 "id *, unsigned int))(void *)objc_msgSend)";
1572 buf += "\n\t\t";
1573 buf += "((id)l_collection,\n\t\t";
1574 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1575 buf += "\n\t\t";
1576 buf += "&enumState, "
1577 "(id *)__rw_items, (unsigned int)16)";
1578}
1579
1580/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1581/// statement to exit to its outer synthesized loop.
1582///
1583Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1584 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1585 return S;
1586 // replace break with goto __break_label
1587 std::string buf;
1588
1589 SourceLocation startLoc = S->getLocStart();
1590 buf = "goto __break_label_";
1591 buf += utostr(ObjCBcLabelNo.back());
1592 ReplaceText(startLoc, strlen("break"), buf);
1593
1594 return 0;
1595}
1596
1597/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1598/// statement to continue with its inner synthesized loop.
1599///
1600Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1601 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1602 return S;
1603 // replace continue with goto __continue_label
1604 std::string buf;
1605
1606 SourceLocation startLoc = S->getLocStart();
1607 buf = "goto __continue_label_";
1608 buf += utostr(ObjCBcLabelNo.back());
1609 ReplaceText(startLoc, strlen("continue"), buf);
1610
1611 return 0;
1612}
1613
1614/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1615/// It rewrites:
1616/// for ( type elem in collection) { stmts; }
1617
1618/// Into:
1619/// {
1620/// type elem;
1621/// struct __objcFastEnumerationState enumState = { 0 };
1622/// id __rw_items[16];
1623/// id l_collection = (id)collection;
1624/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1625/// objects:__rw_items count:16];
1626/// if (limit) {
1627/// unsigned long startMutations = *enumState.mutationsPtr;
1628/// do {
1629/// unsigned long counter = 0;
1630/// do {
1631/// if (startMutations != *enumState.mutationsPtr)
1632/// objc_enumerationMutation(l_collection);
1633/// elem = (type)enumState.itemsPtr[counter++];
1634/// stmts;
1635/// __continue_label: ;
1636/// } while (counter < limit);
1637/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1638/// objects:__rw_items count:16]);
1639/// elem = nil;
1640/// __break_label: ;
1641/// }
1642/// else
1643/// elem = nil;
1644/// }
1645///
1646Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1647 SourceLocation OrigEnd) {
1648 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1649 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1650 "ObjCForCollectionStmt Statement stack mismatch");
1651 assert(!ObjCBcLabelNo.empty() &&
1652 "ObjCForCollectionStmt - Label No stack empty");
1653
1654 SourceLocation startLoc = S->getLocStart();
1655 const char *startBuf = SM->getCharacterData(startLoc);
1656 StringRef elementName;
1657 std::string elementTypeAsString;
1658 std::string buf;
1659 buf = "\n{\n\t";
1660 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1661 // type elem;
1662 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1663 QualType ElementType = cast<ValueDecl>(D)->getType();
1664 if (ElementType->isObjCQualifiedIdType() ||
1665 ElementType->isObjCQualifiedInterfaceType())
1666 // Simply use 'id' for all qualified types.
1667 elementTypeAsString = "id";
1668 else
1669 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1670 buf += elementTypeAsString;
1671 buf += " ";
1672 elementName = D->getName();
1673 buf += elementName;
1674 buf += ";\n\t";
1675 }
1676 else {
1677 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1678 elementName = DR->getDecl()->getName();
1679 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1680 if (VD->getType()->isObjCQualifiedIdType() ||
1681 VD->getType()->isObjCQualifiedInterfaceType())
1682 // Simply use 'id' for all qualified types.
1683 elementTypeAsString = "id";
1684 else
1685 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1686 }
1687
1688 // struct __objcFastEnumerationState enumState = { 0 };
1689 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1690 // id __rw_items[16];
1691 buf += "id __rw_items[16];\n\t";
1692 // id l_collection = (id)
1693 buf += "id l_collection = (id)";
1694 // Find start location of 'collection' the hard way!
1695 const char *startCollectionBuf = startBuf;
1696 startCollectionBuf += 3; // skip 'for'
1697 startCollectionBuf = strchr(startCollectionBuf, '(');
1698 startCollectionBuf++; // skip '('
1699 // find 'in' and skip it.
1700 while (*startCollectionBuf != ' ' ||
1701 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1702 (*(startCollectionBuf+3) != ' ' &&
1703 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1704 startCollectionBuf++;
1705 startCollectionBuf += 3;
1706
1707 // Replace: "for (type element in" with string constructed thus far.
1708 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1709 // Replace ')' in for '(' type elem in collection ')' with ';'
1710 SourceLocation rightParenLoc = S->getRParenLoc();
1711 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1712 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1713 buf = ";\n\t";
1714
1715 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1716 // objects:__rw_items count:16];
1717 // which is synthesized into:
1718 // unsigned int limit =
1719 // ((unsigned int (*)
1720 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1721 // (void *)objc_msgSend)((id)l_collection,
1722 // sel_registerName(
1723 // "countByEnumeratingWithState:objects:count:"),
1724 // (struct __objcFastEnumerationState *)&state,
1725 // (id *)__rw_items, (unsigned int)16);
1726 buf += "unsigned long limit =\n\t\t";
1727 SynthCountByEnumWithState(buf);
1728 buf += ";\n\t";
1729 /// if (limit) {
1730 /// unsigned long startMutations = *enumState.mutationsPtr;
1731 /// do {
1732 /// unsigned long counter = 0;
1733 /// do {
1734 /// if (startMutations != *enumState.mutationsPtr)
1735 /// objc_enumerationMutation(l_collection);
1736 /// elem = (type)enumState.itemsPtr[counter++];
1737 buf += "if (limit) {\n\t";
1738 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1739 buf += "do {\n\t\t";
1740 buf += "unsigned long counter = 0;\n\t\t";
1741 buf += "do {\n\t\t\t";
1742 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1743 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1744 buf += elementName;
1745 buf += " = (";
1746 buf += elementTypeAsString;
1747 buf += ")enumState.itemsPtr[counter++];";
1748 // Replace ')' in for '(' type elem in collection ')' with all of these.
1749 ReplaceText(lparenLoc, 1, buf);
1750
1751 /// __continue_label: ;
1752 /// } while (counter < limit);
1753 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1754 /// objects:__rw_items count:16]);
1755 /// elem = nil;
1756 /// __break_label: ;
1757 /// }
1758 /// else
1759 /// elem = nil;
1760 /// }
1761 ///
1762 buf = ";\n\t";
1763 buf += "__continue_label_";
1764 buf += utostr(ObjCBcLabelNo.back());
1765 buf += ": ;";
1766 buf += "\n\t\t";
1767 buf += "} while (counter < limit);\n\t";
1768 buf += "} while (limit = ";
1769 SynthCountByEnumWithState(buf);
1770 buf += ");\n\t";
1771 buf += elementName;
1772 buf += " = ((";
1773 buf += elementTypeAsString;
1774 buf += ")0);\n\t";
1775 buf += "__break_label_";
1776 buf += utostr(ObjCBcLabelNo.back());
1777 buf += ": ;\n\t";
1778 buf += "}\n\t";
1779 buf += "else\n\t\t";
1780 buf += elementName;
1781 buf += " = ((";
1782 buf += elementTypeAsString;
1783 buf += ")0);\n\t";
1784 buf += "}\n";
1785
1786 // Insert all these *after* the statement body.
1787 // FIXME: If this should support Obj-C++, support CXXTryStmt
1788 if (isa<CompoundStmt>(S->getBody())) {
1789 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1790 InsertText(endBodyLoc, buf);
1791 } else {
1792 /* Need to treat single statements specially. For example:
1793 *
1794 * for (A *a in b) if (stuff()) break;
1795 * for (A *a in b) xxxyy;
1796 *
1797 * The following code simply scans ahead to the semi to find the actual end.
1798 */
1799 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1800 const char *semiBuf = strchr(stmtBuf, ';');
1801 assert(semiBuf && "Can't find ';'");
1802 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1803 InsertText(endBodyLoc, buf);
1804 }
1805 Stmts.pop_back();
1806 ObjCBcLabelNo.pop_back();
1807 return 0;
1808}
1809
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001810static void Write_RethrowObject(std::string &buf) {
1811 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1812 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1813 buf += "\tid rethrow;\n";
1814 buf += "\t} _fin_force_rethow(_rethrow);";
1815}
1816
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001817/// RewriteObjCSynchronizedStmt -
1818/// This routine rewrites @synchronized(expr) stmt;
1819/// into:
1820/// objc_sync_enter(expr);
1821/// @try stmt @finally { objc_sync_exit(expr); }
1822///
1823Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1824 // Get the start location and compute the semi location.
1825 SourceLocation startLoc = S->getLocStart();
1826 const char *startBuf = SM->getCharacterData(startLoc);
1827
1828 assert((*startBuf == '@') && "bogus @synchronized location");
1829
1830 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001831 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001832
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001833 const char *lparenBuf = startBuf;
1834 while (*lparenBuf != '(') lparenBuf++;
1835 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001836
1837 buf = "; objc_sync_enter(_sync_obj);\n";
1838 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1839 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1840 buf += "\n\tid sync_exit;";
1841 buf += "\n\t} _sync_exit(_sync_obj);\n";
1842
1843 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1844 // the sync expression is typically a message expression that's already
1845 // been rewritten! (which implies the SourceLocation's are invalid).
1846 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1847 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1848 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1849 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1850
1851 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1852 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1853 assert (*LBraceLocBuf == '{');
1854 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001855
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001856 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001857 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1858 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001859
1860 buf = "} catch (id e) {_rethrow = e;}\n";
1861 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001862 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001863 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001864
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001865 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001866
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001867 return 0;
1868}
1869
1870void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1871{
1872 // Perform a bottom up traversal of all children.
1873 for (Stmt::child_range CI = S->children(); CI; ++CI)
1874 if (*CI)
1875 WarnAboutReturnGotoStmts(*CI);
1876
1877 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1878 Diags.Report(Context->getFullLoc(S->getLocStart()),
1879 TryFinallyContainsReturnDiag);
1880 }
1881 return;
1882}
1883
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001884Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001885 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001886 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001887 std::string buf;
1888
1889 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001890 if (noCatch)
1891 buf = "{ id volatile _rethrow = 0;\n";
1892 else {
1893 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1894 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001895 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001896 // Get the start location and compute the semi location.
1897 SourceLocation startLoc = S->getLocStart();
1898 const char *startBuf = SM->getCharacterData(startLoc);
1899
1900 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001901 if (finalStmt)
1902 ReplaceText(startLoc, 1, buf);
1903 else
1904 // @try -> try
1905 ReplaceText(startLoc, 1, "");
1906
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001907 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1908 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001909 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001910
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001911 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001912 bool AtRemoved = false;
1913 if (catchDecl) {
1914 QualType t = catchDecl->getType();
1915 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1916 // Should be a pointer to a class.
1917 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1918 if (IDecl) {
1919 std::string Result;
1920 startBuf = SM->getCharacterData(startLoc);
1921 assert((*startBuf == '@') && "bogus @catch location");
1922 SourceLocation rParenLoc = Catch->getRParenLoc();
1923 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1924
1925 // _objc_exc_Foo *_e as argument to catch.
1926 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1927 Result += " *_"; Result += catchDecl->getNameAsString();
1928 Result += ")";
1929 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1930 // Foo *e = (Foo *)_e;
1931 Result.clear();
1932 Result = "{ ";
1933 Result += IDecl->getNameAsString();
1934 Result += " *"; Result += catchDecl->getNameAsString();
1935 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1936 Result += "_"; Result += catchDecl->getNameAsString();
1937
1938 Result += "; ";
1939 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1940 ReplaceText(lBraceLoc, 1, Result);
1941 AtRemoved = true;
1942 }
1943 }
1944 }
1945 if (!AtRemoved)
1946 // @catch -> catch
1947 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001948
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001949 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001950 if (finalStmt) {
1951 buf.clear();
1952 if (noCatch)
1953 buf = "catch (id e) {_rethrow = e;}\n";
1954 else
1955 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1956
1957 SourceLocation startFinalLoc = finalStmt->getLocStart();
1958 ReplaceText(startFinalLoc, 8, buf);
1959 Stmt *body = finalStmt->getFinallyBody();
1960 SourceLocation startFinalBodyLoc = body->getLocStart();
1961 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001962 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001963 ReplaceText(startFinalBodyLoc, 1, buf);
1964
1965 SourceLocation endFinalBodyLoc = body->getLocEnd();
1966 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001967 // Now check for any return/continue/go statements within the @try.
1968 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001969 }
1970
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001971 return 0;
1972}
1973
1974// This can't be done with ReplaceStmt(S, ThrowExpr), since
1975// the throw expression is typically a message expression that's already
1976// been rewritten! (which implies the SourceLocation's are invalid).
1977Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1978 // Get the start location and compute the semi location.
1979 SourceLocation startLoc = S->getLocStart();
1980 const char *startBuf = SM->getCharacterData(startLoc);
1981
1982 assert((*startBuf == '@') && "bogus @throw location");
1983
1984 std::string buf;
1985 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1986 if (S->getThrowExpr())
1987 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001988 else
1989 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001990
1991 // handle "@ throw" correctly.
1992 const char *wBuf = strchr(startBuf, 'w');
1993 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1994 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1995
1996 const char *semiBuf = strchr(startBuf, ';');
1997 assert((*semiBuf == ';') && "@throw: can't find ';'");
1998 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001999 if (S->getThrowExpr())
2000 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002001 return 0;
2002}
2003
2004Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2005 // Create a new string expression.
2006 QualType StrType = Context->getPointerType(Context->CharTy);
2007 std::string StrEncoding;
2008 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2009 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2010 StringLiteral::Ascii, false,
2011 StrType, SourceLocation());
2012 ReplaceStmt(Exp, Replacement);
2013
2014 // Replace this subexpr in the parent.
2015 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2016 return Replacement;
2017}
2018
2019Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2020 if (!SelGetUidFunctionDecl)
2021 SynthSelGetUidFunctionDecl();
2022 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2023 // Create a call to sel_registerName("selName").
2024 SmallVector<Expr*, 8> SelExprs;
2025 QualType argType = Context->getPointerType(Context->CharTy);
2026 SelExprs.push_back(StringLiteral::Create(*Context,
2027 Exp->getSelector().getAsString(),
2028 StringLiteral::Ascii, false,
2029 argType, SourceLocation()));
2030 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2031 &SelExprs[0], SelExprs.size());
2032 ReplaceStmt(Exp, SelExp);
2033 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2034 return SelExp;
2035}
2036
2037CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2038 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2039 SourceLocation EndLoc) {
2040 // Get the type, we will need to reference it in a couple spots.
2041 QualType msgSendType = FD->getType();
2042
2043 // Create a reference to the objc_msgSend() declaration.
2044 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002045 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002046
2047 // Now, we cast the reference to a pointer to the objc_msgSend type.
2048 QualType pToFunc = Context->getPointerType(msgSendType);
2049 ImplicitCastExpr *ICE =
2050 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2051 DRE, 0, VK_RValue);
2052
2053 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2054
2055 CallExpr *Exp =
2056 new (Context) CallExpr(*Context, ICE, args, nargs,
2057 FT->getCallResultType(*Context),
2058 VK_RValue, EndLoc);
2059 return Exp;
2060}
2061
2062static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2063 const char *&startRef, const char *&endRef) {
2064 while (startBuf < endBuf) {
2065 if (*startBuf == '<')
2066 startRef = startBuf; // mark the start.
2067 if (*startBuf == '>') {
2068 if (startRef && *startRef == '<') {
2069 endRef = startBuf; // mark the end.
2070 return true;
2071 }
2072 return false;
2073 }
2074 startBuf++;
2075 }
2076 return false;
2077}
2078
2079static void scanToNextArgument(const char *&argRef) {
2080 int angle = 0;
2081 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2082 if (*argRef == '<')
2083 angle++;
2084 else if (*argRef == '>')
2085 angle--;
2086 argRef++;
2087 }
2088 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2089}
2090
2091bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2092 if (T->isObjCQualifiedIdType())
2093 return true;
2094 if (const PointerType *PT = T->getAs<PointerType>()) {
2095 if (PT->getPointeeType()->isObjCQualifiedIdType())
2096 return true;
2097 }
2098 if (T->isObjCObjectPointerType()) {
2099 T = T->getPointeeType();
2100 return T->isObjCQualifiedInterfaceType();
2101 }
2102 if (T->isArrayType()) {
2103 QualType ElemTy = Context->getBaseElementType(T);
2104 return needToScanForQualifiers(ElemTy);
2105 }
2106 return false;
2107}
2108
2109void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2110 QualType Type = E->getType();
2111 if (needToScanForQualifiers(Type)) {
2112 SourceLocation Loc, EndLoc;
2113
2114 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2115 Loc = ECE->getLParenLoc();
2116 EndLoc = ECE->getRParenLoc();
2117 } else {
2118 Loc = E->getLocStart();
2119 EndLoc = E->getLocEnd();
2120 }
2121 // This will defend against trying to rewrite synthesized expressions.
2122 if (Loc.isInvalid() || EndLoc.isInvalid())
2123 return;
2124
2125 const char *startBuf = SM->getCharacterData(Loc);
2126 const char *endBuf = SM->getCharacterData(EndLoc);
2127 const char *startRef = 0, *endRef = 0;
2128 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2129 // Get the locations of the startRef, endRef.
2130 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2131 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2132 // Comment out the protocol references.
2133 InsertText(LessLoc, "/*");
2134 InsertText(GreaterLoc, "*/");
2135 }
2136 }
2137}
2138
2139void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2140 SourceLocation Loc;
2141 QualType Type;
2142 const FunctionProtoType *proto = 0;
2143 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2144 Loc = VD->getLocation();
2145 Type = VD->getType();
2146 }
2147 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2148 Loc = FD->getLocation();
2149 // Check for ObjC 'id' and class types that have been adorned with protocol
2150 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2151 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2152 assert(funcType && "missing function type");
2153 proto = dyn_cast<FunctionProtoType>(funcType);
2154 if (!proto)
2155 return;
2156 Type = proto->getResultType();
2157 }
2158 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2159 Loc = FD->getLocation();
2160 Type = FD->getType();
2161 }
2162 else
2163 return;
2164
2165 if (needToScanForQualifiers(Type)) {
2166 // Since types are unique, we need to scan the buffer.
2167
2168 const char *endBuf = SM->getCharacterData(Loc);
2169 const char *startBuf = endBuf;
2170 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2171 startBuf--; // scan backward (from the decl location) for return type.
2172 const char *startRef = 0, *endRef = 0;
2173 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2174 // Get the locations of the startRef, endRef.
2175 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2176 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2177 // Comment out the protocol references.
2178 InsertText(LessLoc, "/*");
2179 InsertText(GreaterLoc, "*/");
2180 }
2181 }
2182 if (!proto)
2183 return; // most likely, was a variable
2184 // Now check arguments.
2185 const char *startBuf = SM->getCharacterData(Loc);
2186 const char *startFuncBuf = startBuf;
2187 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2188 if (needToScanForQualifiers(proto->getArgType(i))) {
2189 // Since types are unique, we need to scan the buffer.
2190
2191 const char *endBuf = startBuf;
2192 // scan forward (from the decl location) for argument types.
2193 scanToNextArgument(endBuf);
2194 const char *startRef = 0, *endRef = 0;
2195 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2196 // Get the locations of the startRef, endRef.
2197 SourceLocation LessLoc =
2198 Loc.getLocWithOffset(startRef-startFuncBuf);
2199 SourceLocation GreaterLoc =
2200 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2201 // Comment out the protocol references.
2202 InsertText(LessLoc, "/*");
2203 InsertText(GreaterLoc, "*/");
2204 }
2205 startBuf = ++endBuf;
2206 }
2207 else {
2208 // If the function name is derived from a macro expansion, then the
2209 // argument buffer will not follow the name. Need to speak with Chris.
2210 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2211 startBuf++; // scan forward (from the decl location) for argument types.
2212 startBuf++;
2213 }
2214 }
2215}
2216
2217void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2218 QualType QT = ND->getType();
2219 const Type* TypePtr = QT->getAs<Type>();
2220 if (!isa<TypeOfExprType>(TypePtr))
2221 return;
2222 while (isa<TypeOfExprType>(TypePtr)) {
2223 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2224 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2225 TypePtr = QT->getAs<Type>();
2226 }
2227 // FIXME. This will not work for multiple declarators; as in:
2228 // __typeof__(a) b,c,d;
2229 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2230 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2231 const char *startBuf = SM->getCharacterData(DeclLoc);
2232 if (ND->getInit()) {
2233 std::string Name(ND->getNameAsString());
2234 TypeAsString += " " + Name + " = ";
2235 Expr *E = ND->getInit();
2236 SourceLocation startLoc;
2237 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2238 startLoc = ECE->getLParenLoc();
2239 else
2240 startLoc = E->getLocStart();
2241 startLoc = SM->getExpansionLoc(startLoc);
2242 const char *endBuf = SM->getCharacterData(startLoc);
2243 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2244 }
2245 else {
2246 SourceLocation X = ND->getLocEnd();
2247 X = SM->getExpansionLoc(X);
2248 const char *endBuf = SM->getCharacterData(X);
2249 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2250 }
2251}
2252
2253// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2254void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2255 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2256 SmallVector<QualType, 16> ArgTys;
2257 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2258 QualType getFuncType =
2259 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2260 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2261 SourceLocation(),
2262 SourceLocation(),
2263 SelGetUidIdent, getFuncType, 0,
2264 SC_Extern,
2265 SC_None, false);
2266}
2267
2268void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2269 // declared in <objc/objc.h>
2270 if (FD->getIdentifier() &&
2271 FD->getName() == "sel_registerName") {
2272 SelGetUidFunctionDecl = FD;
2273 return;
2274 }
2275 RewriteObjCQualifiedInterfaceTypes(FD);
2276}
2277
2278void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2279 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2280 const char *argPtr = TypeString.c_str();
2281 if (!strchr(argPtr, '^')) {
2282 Str += TypeString;
2283 return;
2284 }
2285 while (*argPtr) {
2286 Str += (*argPtr == '^' ? '*' : *argPtr);
2287 argPtr++;
2288 }
2289}
2290
2291// FIXME. Consolidate this routine with RewriteBlockPointerType.
2292void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2293 ValueDecl *VD) {
2294 QualType Type = VD->getType();
2295 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2296 const char *argPtr = TypeString.c_str();
2297 int paren = 0;
2298 while (*argPtr) {
2299 switch (*argPtr) {
2300 case '(':
2301 Str += *argPtr;
2302 paren++;
2303 break;
2304 case ')':
2305 Str += *argPtr;
2306 paren--;
2307 break;
2308 case '^':
2309 Str += '*';
2310 if (paren == 1)
2311 Str += VD->getNameAsString();
2312 break;
2313 default:
2314 Str += *argPtr;
2315 break;
2316 }
2317 argPtr++;
2318 }
2319}
2320
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002321void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2322 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2323 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2324 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2325 if (!proto)
2326 return;
2327 QualType Type = proto->getResultType();
2328 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2329 FdStr += " ";
2330 FdStr += FD->getName();
2331 FdStr += "(";
2332 unsigned numArgs = proto->getNumArgs();
2333 for (unsigned i = 0; i < numArgs; i++) {
2334 QualType ArgType = proto->getArgType(i);
2335 RewriteBlockPointerType(FdStr, ArgType);
2336 if (i+1 < numArgs)
2337 FdStr += ", ";
2338 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002339 if (FD->isVariadic()) {
2340 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2341 }
2342 else
2343 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002344 InsertText(FunLocStart, FdStr);
2345}
2346
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002347// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002348void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2349 if (SuperContructorFunctionDecl)
2350 return;
2351 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2352 SmallVector<QualType, 16> ArgTys;
2353 QualType argT = Context->getObjCIdType();
2354 assert(!argT.isNull() && "Can't find 'id' type");
2355 ArgTys.push_back(argT);
2356 ArgTys.push_back(argT);
2357 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2358 &ArgTys[0], ArgTys.size());
2359 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2360 SourceLocation(),
2361 SourceLocation(),
2362 msgSendIdent, msgSendType, 0,
2363 SC_Extern,
2364 SC_None, false);
2365}
2366
2367// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2368void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2369 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2370 SmallVector<QualType, 16> ArgTys;
2371 QualType argT = Context->getObjCIdType();
2372 assert(!argT.isNull() && "Can't find 'id' type");
2373 ArgTys.push_back(argT);
2374 argT = Context->getObjCSelType();
2375 assert(!argT.isNull() && "Can't find 'SEL' type");
2376 ArgTys.push_back(argT);
2377 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2378 &ArgTys[0], ArgTys.size(),
2379 true /*isVariadic*/);
2380 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2381 SourceLocation(),
2382 SourceLocation(),
2383 msgSendIdent, msgSendType, 0,
2384 SC_Extern,
2385 SC_None, false);
2386}
2387
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002388// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002389void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2390 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002391 SmallVector<QualType, 2> ArgTys;
2392 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002393 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002394 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002395 true /*isVariadic*/);
2396 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2397 SourceLocation(),
2398 SourceLocation(),
2399 msgSendIdent, msgSendType, 0,
2400 SC_Extern,
2401 SC_None, false);
2402}
2403
2404// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2405void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2406 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2407 SmallVector<QualType, 16> ArgTys;
2408 QualType argT = Context->getObjCIdType();
2409 assert(!argT.isNull() && "Can't find 'id' type");
2410 ArgTys.push_back(argT);
2411 argT = Context->getObjCSelType();
2412 assert(!argT.isNull() && "Can't find 'SEL' type");
2413 ArgTys.push_back(argT);
2414 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2415 &ArgTys[0], ArgTys.size(),
2416 true /*isVariadic*/);
2417 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2418 SourceLocation(),
2419 SourceLocation(),
2420 msgSendIdent, msgSendType, 0,
2421 SC_Extern,
2422 SC_None, false);
2423}
2424
2425// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002426// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002427void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2428 IdentifierInfo *msgSendIdent =
2429 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002430 SmallVector<QualType, 2> ArgTys;
2431 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002432 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002433 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002434 true /*isVariadic*/);
2435 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2436 SourceLocation(),
2437 SourceLocation(),
2438 msgSendIdent, msgSendType, 0,
2439 SC_Extern,
2440 SC_None, false);
2441}
2442
2443// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2444void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2445 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2446 SmallVector<QualType, 16> ArgTys;
2447 QualType argT = Context->getObjCIdType();
2448 assert(!argT.isNull() && "Can't find 'id' type");
2449 ArgTys.push_back(argT);
2450 argT = Context->getObjCSelType();
2451 assert(!argT.isNull() && "Can't find 'SEL' type");
2452 ArgTys.push_back(argT);
2453 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2454 &ArgTys[0], ArgTys.size(),
2455 true /*isVariadic*/);
2456 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2457 SourceLocation(),
2458 SourceLocation(),
2459 msgSendIdent, msgSendType, 0,
2460 SC_Extern,
2461 SC_None, false);
2462}
2463
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002464// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002465void RewriteModernObjC::SynthGetClassFunctionDecl() {
2466 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2467 SmallVector<QualType, 16> ArgTys;
2468 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002469 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002470 &ArgTys[0], ArgTys.size());
2471 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2472 SourceLocation(),
2473 SourceLocation(),
2474 getClassIdent, getClassType, 0,
2475 SC_Extern,
2476 SC_None, false);
2477}
2478
2479// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2480void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2481 IdentifierInfo *getSuperClassIdent =
2482 &Context->Idents.get("class_getSuperclass");
2483 SmallVector<QualType, 16> ArgTys;
2484 ArgTys.push_back(Context->getObjCClassType());
2485 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2486 &ArgTys[0], ArgTys.size());
2487 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2488 SourceLocation(),
2489 SourceLocation(),
2490 getSuperClassIdent,
2491 getClassType, 0,
2492 SC_Extern,
2493 SC_None,
2494 false);
2495}
2496
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002497// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002498void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2499 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2500 SmallVector<QualType, 16> ArgTys;
2501 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002502 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002503 &ArgTys[0], ArgTys.size());
2504 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2505 SourceLocation(),
2506 SourceLocation(),
2507 getClassIdent, getClassType, 0,
2508 SC_Extern,
2509 SC_None, false);
2510}
2511
2512Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2513 QualType strType = getConstantStringStructType();
2514
2515 std::string S = "__NSConstantStringImpl_";
2516
2517 std::string tmpName = InFileName;
2518 unsigned i;
2519 for (i=0; i < tmpName.length(); i++) {
2520 char c = tmpName.at(i);
2521 // replace any non alphanumeric characters with '_'.
2522 if (!isalpha(c) && (c < '0' || c > '9'))
2523 tmpName[i] = '_';
2524 }
2525 S += tmpName;
2526 S += "_";
2527 S += utostr(NumObjCStringLiterals++);
2528
2529 Preamble += "static __NSConstantStringImpl " + S;
2530 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2531 Preamble += "0x000007c8,"; // utf8_str
2532 // The pretty printer for StringLiteral handles escape characters properly.
2533 std::string prettyBufS;
2534 llvm::raw_string_ostream prettyBuf(prettyBufS);
2535 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2536 PrintingPolicy(LangOpts));
2537 Preamble += prettyBuf.str();
2538 Preamble += ",";
2539 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2540
2541 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2542 SourceLocation(), &Context->Idents.get(S),
2543 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002544 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002545 SourceLocation());
2546 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2547 Context->getPointerType(DRE->getType()),
2548 VK_RValue, OK_Ordinary,
2549 SourceLocation());
2550 // cast to NSConstantString *
2551 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2552 CK_CPointerToObjCPointerCast, Unop);
2553 ReplaceStmt(Exp, cast);
2554 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2555 return cast;
2556}
2557
Fariborz Jahanian55947042012-03-27 20:17:30 +00002558Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2559 unsigned IntSize =
2560 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2561
2562 Expr *FlagExp = IntegerLiteral::Create(*Context,
2563 llvm::APInt(IntSize, Exp->getValue()),
2564 Context->IntTy, Exp->getLocation());
2565 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2566 CK_BitCast, FlagExp);
2567 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2568 cast);
2569 ReplaceStmt(Exp, PE);
2570 return PE;
2571}
2572
Patrick Beardeb382ec2012-04-19 00:25:12 +00002573Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002574 // synthesize declaration of helper functions needed in this routine.
2575 if (!SelGetUidFunctionDecl)
2576 SynthSelGetUidFunctionDecl();
2577 // use objc_msgSend() for all.
2578 if (!MsgSendFunctionDecl)
2579 SynthMsgSendFunctionDecl();
2580 if (!GetClassFunctionDecl)
2581 SynthGetClassFunctionDecl();
2582
2583 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2584 SourceLocation StartLoc = Exp->getLocStart();
2585 SourceLocation EndLoc = Exp->getLocEnd();
2586
2587 // Synthesize a call to objc_msgSend().
2588 SmallVector<Expr*, 4> MsgExprs;
2589 SmallVector<Expr*, 4> ClsExprs;
2590 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002591
Patrick Beardeb382ec2012-04-19 00:25:12 +00002592 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2593 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2594 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002595
Patrick Beardeb382ec2012-04-19 00:25:12 +00002596 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002597 ClsExprs.push_back(StringLiteral::Create(*Context,
2598 clsName->getName(),
2599 StringLiteral::Ascii, false,
2600 argType, SourceLocation()));
2601 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2602 &ClsExprs[0],
2603 ClsExprs.size(),
2604 StartLoc, EndLoc);
2605 MsgExprs.push_back(Cls);
2606
Patrick Beardeb382ec2012-04-19 00:25:12 +00002607 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002608 // it will be the 2nd argument.
2609 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002610 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002611 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002612 StringLiteral::Ascii, false,
2613 argType, SourceLocation()));
2614 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2615 &SelExprs[0], SelExprs.size(),
2616 StartLoc, EndLoc);
2617 MsgExprs.push_back(SelExp);
2618
Patrick Beardeb382ec2012-04-19 00:25:12 +00002619 // User provided sub-expression is the 3rd, and last, argument.
2620 Expr *subExpr = Exp->getSubExpr();
2621 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002622 QualType type = ICE->getType();
2623 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2624 CastKind CK = CK_BitCast;
2625 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2626 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002627 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002628 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002629 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002630
2631 SmallVector<QualType, 4> ArgTypes;
2632 ArgTypes.push_back(Context->getObjCIdType());
2633 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002634 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2635 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002636 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002637
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002638 QualType returnType = Exp->getType();
2639 // Get the type, we will need to reference it in a couple spots.
2640 QualType msgSendType = MsgSendFlavor->getType();
2641
2642 // Create a reference to the objc_msgSend() declaration.
2643 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2644 VK_LValue, SourceLocation());
2645
2646 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002647 Context->getPointerType(Context->VoidTy),
2648 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002649
2650 // Now do the "normal" pointer to function cast.
2651 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002652 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2653 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002654 castType = Context->getPointerType(castType);
2655 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2656 cast);
2657
2658 // Don't forget the parens to enforce the proper binding.
2659 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2660
2661 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2662 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2663 MsgExprs.size(),
2664 FT->getResultType(), VK_RValue,
2665 EndLoc);
2666 ReplaceStmt(Exp, CE);
2667 return CE;
2668}
2669
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002670Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2671 // synthesize declaration of helper functions needed in this routine.
2672 if (!SelGetUidFunctionDecl)
2673 SynthSelGetUidFunctionDecl();
2674 // use objc_msgSend() for all.
2675 if (!MsgSendFunctionDecl)
2676 SynthMsgSendFunctionDecl();
2677 if (!GetClassFunctionDecl)
2678 SynthGetClassFunctionDecl();
2679
2680 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2681 SourceLocation StartLoc = Exp->getLocStart();
2682 SourceLocation EndLoc = Exp->getLocEnd();
2683
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002684 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002685 QualType IntQT = Context->IntTy;
2686 QualType NSArrayFType =
2687 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002688 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002689 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2690 DeclRefExpr *NSArrayDRE =
2691 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2692 SourceLocation());
2693
2694 SmallVector<Expr*, 16> InitExprs;
2695 unsigned NumElements = Exp->getNumElements();
2696 unsigned UnsignedIntSize =
2697 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2698 Expr *count = IntegerLiteral::Create(*Context,
2699 llvm::APInt(UnsignedIntSize, NumElements),
2700 Context->UnsignedIntTy, SourceLocation());
2701 InitExprs.push_back(count);
2702 for (unsigned i = 0; i < NumElements; i++)
2703 InitExprs.push_back(Exp->getElement(i));
2704 Expr *NSArrayCallExpr =
2705 new (Context) CallExpr(*Context, NSArrayDRE, &InitExprs[0], InitExprs.size(),
2706 NSArrayFType, VK_LValue, SourceLocation());
2707
2708 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2709 SourceLocation(),
2710 &Context->Idents.get("arr"),
2711 Context->getPointerType(Context->VoidPtrTy), 0,
2712 /*BitWidth=*/0, /*Mutable=*/true,
2713 /*HasInit=*/false);
2714 MemberExpr *ArrayLiteralME =
2715 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2716 SourceLocation(),
2717 ARRFD->getType(), VK_LValue,
2718 OK_Ordinary);
2719 QualType ConstIdT = Context->getObjCIdType().withConst();
2720 CStyleCastExpr * ArrayLiteralObjects =
2721 NoTypeInfoCStyleCastExpr(Context,
2722 Context->getPointerType(ConstIdT),
2723 CK_BitCast,
2724 ArrayLiteralME);
2725
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002726 // Synthesize a call to objc_msgSend().
2727 SmallVector<Expr*, 32> MsgExprs;
2728 SmallVector<Expr*, 4> ClsExprs;
2729 QualType argType = Context->getPointerType(Context->CharTy);
2730 QualType expType = Exp->getType();
2731
2732 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2733 ObjCInterfaceDecl *Class =
2734 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2735
2736 IdentifierInfo *clsName = Class->getIdentifier();
2737 ClsExprs.push_back(StringLiteral::Create(*Context,
2738 clsName->getName(),
2739 StringLiteral::Ascii, false,
2740 argType, SourceLocation()));
2741 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2742 &ClsExprs[0],
2743 ClsExprs.size(),
2744 StartLoc, EndLoc);
2745 MsgExprs.push_back(Cls);
2746
2747 // Create a call to sel_registerName("arrayWithObjects:count:").
2748 // it will be the 2nd argument.
2749 SmallVector<Expr*, 4> SelExprs;
2750 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2751 SelExprs.push_back(StringLiteral::Create(*Context,
2752 ArrayMethod->getSelector().getAsString(),
2753 StringLiteral::Ascii, false,
2754 argType, SourceLocation()));
2755 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2756 &SelExprs[0], SelExprs.size(),
2757 StartLoc, EndLoc);
2758 MsgExprs.push_back(SelExp);
2759
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002760 // (const id [])objects
2761 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002762
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002763 // (NSUInteger)cnt
2764 Expr *cnt = IntegerLiteral::Create(*Context,
2765 llvm::APInt(UnsignedIntSize, NumElements),
2766 Context->UnsignedIntTy, SourceLocation());
2767 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002768
2769
2770 SmallVector<QualType, 4> ArgTypes;
2771 ArgTypes.push_back(Context->getObjCIdType());
2772 ArgTypes.push_back(Context->getObjCSelType());
2773 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2774 E = ArrayMethod->param_end(); PI != E; ++PI)
2775 ArgTypes.push_back((*PI)->getType());
2776
2777 QualType returnType = Exp->getType();
2778 // Get the type, we will need to reference it in a couple spots.
2779 QualType msgSendType = MsgSendFlavor->getType();
2780
2781 // Create a reference to the objc_msgSend() declaration.
2782 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2783 VK_LValue, SourceLocation());
2784
2785 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2786 Context->getPointerType(Context->VoidTy),
2787 CK_BitCast, DRE);
2788
2789 // Now do the "normal" pointer to function cast.
2790 QualType castType =
2791 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2792 ArrayMethod->isVariadic());
2793 castType = Context->getPointerType(castType);
2794 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2795 cast);
2796
2797 // Don't forget the parens to enforce the proper binding.
2798 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2799
2800 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2801 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2802 MsgExprs.size(),
2803 FT->getResultType(), VK_RValue,
2804 EndLoc);
2805 ReplaceStmt(Exp, CE);
2806 return CE;
2807}
2808
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002809Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2810 // synthesize declaration of helper functions needed in this routine.
2811 if (!SelGetUidFunctionDecl)
2812 SynthSelGetUidFunctionDecl();
2813 // use objc_msgSend() for all.
2814 if (!MsgSendFunctionDecl)
2815 SynthMsgSendFunctionDecl();
2816 if (!GetClassFunctionDecl)
2817 SynthGetClassFunctionDecl();
2818
2819 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2820 SourceLocation StartLoc = Exp->getLocStart();
2821 SourceLocation EndLoc = Exp->getLocEnd();
2822
2823 // Build the expression: __NSContainer_literal(int, ...).arr
2824 QualType IntQT = Context->IntTy;
2825 QualType NSDictFType =
2826 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2827 std::string NSDictFName("__NSContainer_literal");
2828 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2829 DeclRefExpr *NSDictDRE =
2830 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2831 SourceLocation());
2832
2833 SmallVector<Expr*, 16> KeyExprs;
2834 SmallVector<Expr*, 16> ValueExprs;
2835
2836 unsigned NumElements = Exp->getNumElements();
2837 unsigned UnsignedIntSize =
2838 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2839 Expr *count = IntegerLiteral::Create(*Context,
2840 llvm::APInt(UnsignedIntSize, NumElements),
2841 Context->UnsignedIntTy, SourceLocation());
2842 KeyExprs.push_back(count);
2843 ValueExprs.push_back(count);
2844 for (unsigned i = 0; i < NumElements; i++) {
2845 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2846 KeyExprs.push_back(Element.Key);
2847 ValueExprs.push_back(Element.Value);
2848 }
2849
2850 // (const id [])objects
2851 Expr *NSValueCallExpr =
2852 new (Context) CallExpr(*Context, NSDictDRE, &ValueExprs[0], ValueExprs.size(),
2853 NSDictFType, VK_LValue, SourceLocation());
2854
2855 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2856 SourceLocation(),
2857 &Context->Idents.get("arr"),
2858 Context->getPointerType(Context->VoidPtrTy), 0,
2859 /*BitWidth=*/0, /*Mutable=*/true,
2860 /*HasInit=*/false);
2861 MemberExpr *DictLiteralValueME =
2862 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2863 SourceLocation(),
2864 ARRFD->getType(), VK_LValue,
2865 OK_Ordinary);
2866 QualType ConstIdT = Context->getObjCIdType().withConst();
2867 CStyleCastExpr * DictValueObjects =
2868 NoTypeInfoCStyleCastExpr(Context,
2869 Context->getPointerType(ConstIdT),
2870 CK_BitCast,
2871 DictLiteralValueME);
2872 // (const id <NSCopying> [])keys
2873 Expr *NSKeyCallExpr =
2874 new (Context) CallExpr(*Context, NSDictDRE, &KeyExprs[0], KeyExprs.size(),
2875 NSDictFType, VK_LValue, SourceLocation());
2876
2877 MemberExpr *DictLiteralKeyME =
2878 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2879 SourceLocation(),
2880 ARRFD->getType(), VK_LValue,
2881 OK_Ordinary);
2882
2883 CStyleCastExpr * DictKeyObjects =
2884 NoTypeInfoCStyleCastExpr(Context,
2885 Context->getPointerType(ConstIdT),
2886 CK_BitCast,
2887 DictLiteralKeyME);
2888
2889
2890
2891 // Synthesize a call to objc_msgSend().
2892 SmallVector<Expr*, 32> MsgExprs;
2893 SmallVector<Expr*, 4> ClsExprs;
2894 QualType argType = Context->getPointerType(Context->CharTy);
2895 QualType expType = Exp->getType();
2896
2897 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2898 ObjCInterfaceDecl *Class =
2899 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2900
2901 IdentifierInfo *clsName = Class->getIdentifier();
2902 ClsExprs.push_back(StringLiteral::Create(*Context,
2903 clsName->getName(),
2904 StringLiteral::Ascii, false,
2905 argType, SourceLocation()));
2906 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2907 &ClsExprs[0],
2908 ClsExprs.size(),
2909 StartLoc, EndLoc);
2910 MsgExprs.push_back(Cls);
2911
2912 // Create a call to sel_registerName("arrayWithObjects:count:").
2913 // it will be the 2nd argument.
2914 SmallVector<Expr*, 4> SelExprs;
2915 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2916 SelExprs.push_back(StringLiteral::Create(*Context,
2917 DictMethod->getSelector().getAsString(),
2918 StringLiteral::Ascii, false,
2919 argType, SourceLocation()));
2920 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2921 &SelExprs[0], SelExprs.size(),
2922 StartLoc, EndLoc);
2923 MsgExprs.push_back(SelExp);
2924
2925 // (const id [])objects
2926 MsgExprs.push_back(DictValueObjects);
2927
2928 // (const id <NSCopying> [])keys
2929 MsgExprs.push_back(DictKeyObjects);
2930
2931 // (NSUInteger)cnt
2932 Expr *cnt = IntegerLiteral::Create(*Context,
2933 llvm::APInt(UnsignedIntSize, NumElements),
2934 Context->UnsignedIntTy, SourceLocation());
2935 MsgExprs.push_back(cnt);
2936
2937
2938 SmallVector<QualType, 8> ArgTypes;
2939 ArgTypes.push_back(Context->getObjCIdType());
2940 ArgTypes.push_back(Context->getObjCSelType());
2941 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2942 E = DictMethod->param_end(); PI != E; ++PI) {
2943 QualType T = (*PI)->getType();
2944 if (const PointerType* PT = T->getAs<PointerType>()) {
2945 QualType PointeeTy = PT->getPointeeType();
2946 convertToUnqualifiedObjCType(PointeeTy);
2947 T = Context->getPointerType(PointeeTy);
2948 }
2949 ArgTypes.push_back(T);
2950 }
2951
2952 QualType returnType = Exp->getType();
2953 // Get the type, we will need to reference it in a couple spots.
2954 QualType msgSendType = MsgSendFlavor->getType();
2955
2956 // Create a reference to the objc_msgSend() declaration.
2957 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2958 VK_LValue, SourceLocation());
2959
2960 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2961 Context->getPointerType(Context->VoidTy),
2962 CK_BitCast, DRE);
2963
2964 // Now do the "normal" pointer to function cast.
2965 QualType castType =
2966 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2967 DictMethod->isVariadic());
2968 castType = Context->getPointerType(castType);
2969 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2970 cast);
2971
2972 // Don't forget the parens to enforce the proper binding.
2973 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2974
2975 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2976 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2977 MsgExprs.size(),
2978 FT->getResultType(), VK_RValue,
2979 EndLoc);
2980 ReplaceStmt(Exp, CE);
2981 return CE;
2982}
2983
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002984// struct __rw_objc_super {
2985// struct objc_object *object; struct objc_object *superClass;
2986// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002987QualType RewriteModernObjC::getSuperStructType() {
2988 if (!SuperStructDecl) {
2989 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2990 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002991 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002992 QualType FieldTypes[2];
2993
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002994 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002995 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002996 // struct objc_object *superClass;
2997 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002998
2999 // Create fields
3000 for (unsigned i = 0; i < 2; ++i) {
3001 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3002 SourceLocation(),
3003 SourceLocation(), 0,
3004 FieldTypes[i], 0,
3005 /*BitWidth=*/0,
3006 /*Mutable=*/false,
3007 /*HasInit=*/false));
3008 }
3009
3010 SuperStructDecl->completeDefinition();
3011 }
3012 return Context->getTagDeclType(SuperStructDecl);
3013}
3014
3015QualType RewriteModernObjC::getConstantStringStructType() {
3016 if (!ConstantStringDecl) {
3017 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3018 SourceLocation(), SourceLocation(),
3019 &Context->Idents.get("__NSConstantStringImpl"));
3020 QualType FieldTypes[4];
3021
3022 // struct objc_object *receiver;
3023 FieldTypes[0] = Context->getObjCIdType();
3024 // int flags;
3025 FieldTypes[1] = Context->IntTy;
3026 // char *str;
3027 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3028 // long length;
3029 FieldTypes[3] = Context->LongTy;
3030
3031 // Create fields
3032 for (unsigned i = 0; i < 4; ++i) {
3033 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3034 ConstantStringDecl,
3035 SourceLocation(),
3036 SourceLocation(), 0,
3037 FieldTypes[i], 0,
3038 /*BitWidth=*/0,
3039 /*Mutable=*/true,
3040 /*HasInit=*/false));
3041 }
3042
3043 ConstantStringDecl->completeDefinition();
3044 }
3045 return Context->getTagDeclType(ConstantStringDecl);
3046}
3047
3048Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3049 SourceLocation StartLoc,
3050 SourceLocation EndLoc) {
3051 if (!SelGetUidFunctionDecl)
3052 SynthSelGetUidFunctionDecl();
3053 if (!MsgSendFunctionDecl)
3054 SynthMsgSendFunctionDecl();
3055 if (!MsgSendSuperFunctionDecl)
3056 SynthMsgSendSuperFunctionDecl();
3057 if (!MsgSendStretFunctionDecl)
3058 SynthMsgSendStretFunctionDecl();
3059 if (!MsgSendSuperStretFunctionDecl)
3060 SynthMsgSendSuperStretFunctionDecl();
3061 if (!MsgSendFpretFunctionDecl)
3062 SynthMsgSendFpretFunctionDecl();
3063 if (!GetClassFunctionDecl)
3064 SynthGetClassFunctionDecl();
3065 if (!GetSuperClassFunctionDecl)
3066 SynthGetSuperClassFunctionDecl();
3067 if (!GetMetaClassFunctionDecl)
3068 SynthGetMetaClassFunctionDecl();
3069
3070 // default to objc_msgSend().
3071 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3072 // May need to use objc_msgSend_stret() as well.
3073 FunctionDecl *MsgSendStretFlavor = 0;
3074 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3075 QualType resultType = mDecl->getResultType();
3076 if (resultType->isRecordType())
3077 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3078 else if (resultType->isRealFloatingType())
3079 MsgSendFlavor = MsgSendFpretFunctionDecl;
3080 }
3081
3082 // Synthesize a call to objc_msgSend().
3083 SmallVector<Expr*, 8> MsgExprs;
3084 switch (Exp->getReceiverKind()) {
3085 case ObjCMessageExpr::SuperClass: {
3086 MsgSendFlavor = MsgSendSuperFunctionDecl;
3087 if (MsgSendStretFlavor)
3088 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3089 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3090
3091 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3092
3093 SmallVector<Expr*, 4> InitExprs;
3094
3095 // set the receiver to self, the first argument to all methods.
3096 InitExprs.push_back(
3097 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3098 CK_BitCast,
3099 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003100 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003101 Context->getObjCIdType(),
3102 VK_RValue,
3103 SourceLocation()))
3104 ); // set the 'receiver'.
3105
3106 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3107 SmallVector<Expr*, 8> ClsExprs;
3108 QualType argType = Context->getPointerType(Context->CharTy);
3109 ClsExprs.push_back(StringLiteral::Create(*Context,
3110 ClassDecl->getIdentifier()->getName(),
3111 StringLiteral::Ascii, false,
3112 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003113 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003114 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3115 &ClsExprs[0],
3116 ClsExprs.size(),
3117 StartLoc,
3118 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003119 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003120 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003121 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3122 &ClsExprs[0], ClsExprs.size(),
3123 StartLoc, EndLoc);
3124
3125 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3126 // To turn off a warning, type-cast to 'id'
3127 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3128 NoTypeInfoCStyleCastExpr(Context,
3129 Context->getObjCIdType(),
3130 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003131 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003132 QualType superType = getSuperStructType();
3133 Expr *SuperRep;
3134
3135 if (LangOpts.MicrosoftExt) {
3136 SynthSuperContructorFunctionDecl();
3137 // Simulate a contructor call...
3138 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003139 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003140 SourceLocation());
3141 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3142 InitExprs.size(),
3143 superType, VK_LValue,
3144 SourceLocation());
3145 // The code for super is a little tricky to prevent collision with
3146 // the structure definition in the header. The rewriter has it's own
3147 // internal definition (__rw_objc_super) that is uses. This is why
3148 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003149 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003150 //
3151 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3152 Context->getPointerType(SuperRep->getType()),
3153 VK_RValue, OK_Ordinary,
3154 SourceLocation());
3155 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3156 Context->getPointerType(superType),
3157 CK_BitCast, SuperRep);
3158 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003159 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003160 InitListExpr *ILE =
3161 new (Context) InitListExpr(*Context, SourceLocation(),
3162 &InitExprs[0], InitExprs.size(),
3163 SourceLocation());
3164 TypeSourceInfo *superTInfo
3165 = Context->getTrivialTypeSourceInfo(superType);
3166 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3167 superType, VK_LValue,
3168 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003169 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003170 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3171 Context->getPointerType(SuperRep->getType()),
3172 VK_RValue, OK_Ordinary,
3173 SourceLocation());
3174 }
3175 MsgExprs.push_back(SuperRep);
3176 break;
3177 }
3178
3179 case ObjCMessageExpr::Class: {
3180 SmallVector<Expr*, 8> ClsExprs;
3181 QualType argType = Context->getPointerType(Context->CharTy);
3182 ObjCInterfaceDecl *Class
3183 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3184 IdentifierInfo *clsName = Class->getIdentifier();
3185 ClsExprs.push_back(StringLiteral::Create(*Context,
3186 clsName->getName(),
3187 StringLiteral::Ascii, false,
3188 argType, SourceLocation()));
3189 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3190 &ClsExprs[0],
3191 ClsExprs.size(),
3192 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003193 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3194 Context->getObjCIdType(),
3195 CK_BitCast, Cls);
3196 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003197 break;
3198 }
3199
3200 case ObjCMessageExpr::SuperInstance:{
3201 MsgSendFlavor = MsgSendSuperFunctionDecl;
3202 if (MsgSendStretFlavor)
3203 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3204 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3205 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3206 SmallVector<Expr*, 4> InitExprs;
3207
3208 InitExprs.push_back(
3209 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3210 CK_BitCast,
3211 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003212 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003213 Context->getObjCIdType(),
3214 VK_RValue, SourceLocation()))
3215 ); // set the 'receiver'.
3216
3217 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3218 SmallVector<Expr*, 8> ClsExprs;
3219 QualType argType = Context->getPointerType(Context->CharTy);
3220 ClsExprs.push_back(StringLiteral::Create(*Context,
3221 ClassDecl->getIdentifier()->getName(),
3222 StringLiteral::Ascii, false, argType,
3223 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003224 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003225 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3226 &ClsExprs[0],
3227 ClsExprs.size(),
3228 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003229 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003230 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003231 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3232 &ClsExprs[0], ClsExprs.size(),
3233 StartLoc, EndLoc);
3234
3235 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3236 // To turn off a warning, type-cast to 'id'
3237 InitExprs.push_back(
3238 // set 'super class', using class_getSuperclass().
3239 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3240 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003241 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003242 QualType superType = getSuperStructType();
3243 Expr *SuperRep;
3244
3245 if (LangOpts.MicrosoftExt) {
3246 SynthSuperContructorFunctionDecl();
3247 // Simulate a contructor call...
3248 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003249 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003250 SourceLocation());
3251 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3252 InitExprs.size(),
3253 superType, VK_LValue, SourceLocation());
3254 // The code for super is a little tricky to prevent collision with
3255 // the structure definition in the header. The rewriter has it's own
3256 // internal definition (__rw_objc_super) that is uses. This is why
3257 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003258 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003259 //
3260 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3261 Context->getPointerType(SuperRep->getType()),
3262 VK_RValue, OK_Ordinary,
3263 SourceLocation());
3264 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3265 Context->getPointerType(superType),
3266 CK_BitCast, SuperRep);
3267 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003268 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003269 InitListExpr *ILE =
3270 new (Context) InitListExpr(*Context, SourceLocation(),
3271 &InitExprs[0], InitExprs.size(),
3272 SourceLocation());
3273 TypeSourceInfo *superTInfo
3274 = Context->getTrivialTypeSourceInfo(superType);
3275 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3276 superType, VK_RValue, ILE,
3277 false);
3278 }
3279 MsgExprs.push_back(SuperRep);
3280 break;
3281 }
3282
3283 case ObjCMessageExpr::Instance: {
3284 // Remove all type-casts because it may contain objc-style types; e.g.
3285 // Foo<Proto> *.
3286 Expr *recExpr = Exp->getInstanceReceiver();
3287 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3288 recExpr = CE->getSubExpr();
3289 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3290 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3291 ? CK_BlockPointerToObjCPointerCast
3292 : CK_CPointerToObjCPointerCast;
3293
3294 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3295 CK, recExpr);
3296 MsgExprs.push_back(recExpr);
3297 break;
3298 }
3299 }
3300
3301 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3302 SmallVector<Expr*, 8> SelExprs;
3303 QualType argType = Context->getPointerType(Context->CharTy);
3304 SelExprs.push_back(StringLiteral::Create(*Context,
3305 Exp->getSelector().getAsString(),
3306 StringLiteral::Ascii, false,
3307 argType, SourceLocation()));
3308 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3309 &SelExprs[0], SelExprs.size(),
3310 StartLoc,
3311 EndLoc);
3312 MsgExprs.push_back(SelExp);
3313
3314 // Now push any user supplied arguments.
3315 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3316 Expr *userExpr = Exp->getArg(i);
3317 // Make all implicit casts explicit...ICE comes in handy:-)
3318 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3319 // Reuse the ICE type, it is exactly what the doctor ordered.
3320 QualType type = ICE->getType();
3321 if (needToScanForQualifiers(type))
3322 type = Context->getObjCIdType();
3323 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3324 (void)convertBlockPointerToFunctionPointer(type);
3325 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3326 CastKind CK;
3327 if (SubExpr->getType()->isIntegralType(*Context) &&
3328 type->isBooleanType()) {
3329 CK = CK_IntegralToBoolean;
3330 } else if (type->isObjCObjectPointerType()) {
3331 if (SubExpr->getType()->isBlockPointerType()) {
3332 CK = CK_BlockPointerToObjCPointerCast;
3333 } else if (SubExpr->getType()->isPointerType()) {
3334 CK = CK_CPointerToObjCPointerCast;
3335 } else {
3336 CK = CK_BitCast;
3337 }
3338 } else {
3339 CK = CK_BitCast;
3340 }
3341
3342 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3343 }
3344 // Make id<P...> cast into an 'id' cast.
3345 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3346 if (CE->getType()->isObjCQualifiedIdType()) {
3347 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3348 userExpr = CE->getSubExpr();
3349 CastKind CK;
3350 if (userExpr->getType()->isIntegralType(*Context)) {
3351 CK = CK_IntegralToPointer;
3352 } else if (userExpr->getType()->isBlockPointerType()) {
3353 CK = CK_BlockPointerToObjCPointerCast;
3354 } else if (userExpr->getType()->isPointerType()) {
3355 CK = CK_CPointerToObjCPointerCast;
3356 } else {
3357 CK = CK_BitCast;
3358 }
3359 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3360 CK, userExpr);
3361 }
3362 }
3363 MsgExprs.push_back(userExpr);
3364 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3365 // out the argument in the original expression (since we aren't deleting
3366 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3367 //Exp->setArg(i, 0);
3368 }
3369 // Generate the funky cast.
3370 CastExpr *cast;
3371 SmallVector<QualType, 8> ArgTypes;
3372 QualType returnType;
3373
3374 // Push 'id' and 'SEL', the 2 implicit arguments.
3375 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3376 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3377 else
3378 ArgTypes.push_back(Context->getObjCIdType());
3379 ArgTypes.push_back(Context->getObjCSelType());
3380 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3381 // Push any user argument types.
3382 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3383 E = OMD->param_end(); PI != E; ++PI) {
3384 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3385 ? Context->getObjCIdType()
3386 : (*PI)->getType();
3387 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3388 (void)convertBlockPointerToFunctionPointer(t);
3389 ArgTypes.push_back(t);
3390 }
3391 returnType = Exp->getType();
3392 convertToUnqualifiedObjCType(returnType);
3393 (void)convertBlockPointerToFunctionPointer(returnType);
3394 } else {
3395 returnType = Context->getObjCIdType();
3396 }
3397 // Get the type, we will need to reference it in a couple spots.
3398 QualType msgSendType = MsgSendFlavor->getType();
3399
3400 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003401 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003402 VK_LValue, SourceLocation());
3403
3404 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3405 // If we don't do this cast, we get the following bizarre warning/note:
3406 // xx.m:13: warning: function called through a non-compatible type
3407 // xx.m:13: note: if this code is reached, the program will abort
3408 cast = NoTypeInfoCStyleCastExpr(Context,
3409 Context->getPointerType(Context->VoidTy),
3410 CK_BitCast, DRE);
3411
3412 // Now do the "normal" pointer to function cast.
3413 QualType castType =
3414 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3415 // If we don't have a method decl, force a variadic cast.
3416 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3417 castType = Context->getPointerType(castType);
3418 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3419 cast);
3420
3421 // Don't forget the parens to enforce the proper binding.
3422 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3423
3424 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3425 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3426 MsgExprs.size(),
3427 FT->getResultType(), VK_RValue,
3428 EndLoc);
3429 Stmt *ReplacingStmt = CE;
3430 if (MsgSendStretFlavor) {
3431 // We have the method which returns a struct/union. Must also generate
3432 // call to objc_msgSend_stret and hang both varieties on a conditional
3433 // expression which dictate which one to envoke depending on size of
3434 // method's return type.
3435
3436 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003437 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3438 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003439 VK_LValue, SourceLocation());
3440 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3441 cast = NoTypeInfoCStyleCastExpr(Context,
3442 Context->getPointerType(Context->VoidTy),
3443 CK_BitCast, STDRE);
3444 // Now do the "normal" pointer to function cast.
3445 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3446 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3447 castType = Context->getPointerType(castType);
3448 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3449 cast);
3450
3451 // Don't forget the parens to enforce the proper binding.
3452 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3453
3454 FT = msgSendType->getAs<FunctionType>();
3455 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3456 MsgExprs.size(),
3457 FT->getResultType(), VK_RValue,
3458 SourceLocation());
3459
3460 // Build sizeof(returnType)
3461 UnaryExprOrTypeTraitExpr *sizeofExpr =
3462 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3463 Context->getTrivialTypeSourceInfo(returnType),
3464 Context->getSizeType(), SourceLocation(),
3465 SourceLocation());
3466 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3467 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3468 // For X86 it is more complicated and some kind of target specific routine
3469 // is needed to decide what to do.
3470 unsigned IntSize =
3471 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3472 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3473 llvm::APInt(IntSize, 8),
3474 Context->IntTy,
3475 SourceLocation());
3476 BinaryOperator *lessThanExpr =
3477 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3478 VK_RValue, OK_Ordinary, SourceLocation());
3479 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3480 ConditionalOperator *CondExpr =
3481 new (Context) ConditionalOperator(lessThanExpr,
3482 SourceLocation(), CE,
3483 SourceLocation(), STCE,
3484 returnType, VK_RValue, OK_Ordinary);
3485 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3486 CondExpr);
3487 }
3488 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3489 return ReplacingStmt;
3490}
3491
3492Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3493 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3494 Exp->getLocEnd());
3495
3496 // Now do the actual rewrite.
3497 ReplaceStmt(Exp, ReplacingStmt);
3498
3499 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3500 return ReplacingStmt;
3501}
3502
3503// typedef struct objc_object Protocol;
3504QualType RewriteModernObjC::getProtocolType() {
3505 if (!ProtocolTypeDecl) {
3506 TypeSourceInfo *TInfo
3507 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3508 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3509 SourceLocation(), SourceLocation(),
3510 &Context->Idents.get("Protocol"),
3511 TInfo);
3512 }
3513 return Context->getTypeDeclType(ProtocolTypeDecl);
3514}
3515
3516/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3517/// a synthesized/forward data reference (to the protocol's metadata).
3518/// The forward references (and metadata) are generated in
3519/// RewriteModernObjC::HandleTranslationUnit().
3520Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003521 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3522 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003523 IdentifierInfo *ID = &Context->Idents.get(Name);
3524 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3525 SourceLocation(), ID, getProtocolType(), 0,
3526 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003527 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3528 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003529 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3530 Context->getPointerType(DRE->getType()),
3531 VK_RValue, OK_Ordinary, SourceLocation());
3532 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3533 CK_BitCast,
3534 DerefExpr);
3535 ReplaceStmt(Exp, castExpr);
3536 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3537 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3538 return castExpr;
3539
3540}
3541
3542bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3543 const char *endBuf) {
3544 while (startBuf < endBuf) {
3545 if (*startBuf == '#') {
3546 // Skip whitespace.
3547 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3548 ;
3549 if (!strncmp(startBuf, "if", strlen("if")) ||
3550 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3551 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3552 !strncmp(startBuf, "define", strlen("define")) ||
3553 !strncmp(startBuf, "undef", strlen("undef")) ||
3554 !strncmp(startBuf, "else", strlen("else")) ||
3555 !strncmp(startBuf, "elif", strlen("elif")) ||
3556 !strncmp(startBuf, "endif", strlen("endif")) ||
3557 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3558 !strncmp(startBuf, "include", strlen("include")) ||
3559 !strncmp(startBuf, "import", strlen("import")) ||
3560 !strncmp(startBuf, "include_next", strlen("include_next")))
3561 return true;
3562 }
3563 startBuf++;
3564 }
3565 return false;
3566}
3567
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003568/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3569/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003570bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003571 TagDecl *Tag,
3572 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003573 if (!IDecl)
3574 return false;
3575 SourceLocation TagLocation;
3576 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3577 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003578 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003579 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003580 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003581 TagLocation = RD->getLocation();
3582 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003583 IDecl->getLocation(), TagLocation);
3584 }
3585 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3586 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3587 return false;
3588 IsNamedDefinition = true;
3589 TagLocation = ED->getLocation();
3590 return Context->getSourceManager().isBeforeInTranslationUnit(
3591 IDecl->getLocation(), TagLocation);
3592
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003593 }
3594 return false;
3595}
3596
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003597/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003598/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003599bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3600 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003601 if (isa<TypedefType>(Type)) {
3602 Result += "\t";
3603 return false;
3604 }
3605
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003606 if (Type->isArrayType()) {
3607 QualType ElemTy = Context->getBaseElementType(Type);
3608 return RewriteObjCFieldDeclType(ElemTy, Result);
3609 }
3610 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003611 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3612 if (RD->isCompleteDefinition()) {
3613 if (RD->isStruct())
3614 Result += "\n\tstruct ";
3615 else if (RD->isUnion())
3616 Result += "\n\tunion ";
3617 else
3618 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003619
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003620 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003621 if (GlobalDefinedTags.count(RD)) {
3622 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003623 Result += " ";
3624 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003625 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003626 Result += " {\n";
3627 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003628 e = RD->field_end(); i != e; ++i) {
David Blaikie262bc182012-04-30 02:36:29 +00003629 FieldDecl *FD = &*i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003630 RewriteObjCFieldDecl(FD, Result);
3631 }
3632 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003633 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003634 }
3635 }
3636 else if (Type->isEnumeralType()) {
3637 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3638 if (ED->isCompleteDefinition()) {
3639 Result += "\n\tenum ";
3640 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003641 if (GlobalDefinedTags.count(ED)) {
3642 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003643 Result += " ";
3644 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003645 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003646
3647 Result += " {\n";
3648 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3649 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3650 Result += "\t"; Result += EC->getName(); Result += " = ";
3651 llvm::APSInt Val = EC->getInitVal();
3652 Result += Val.toString(10);
3653 Result += ",\n";
3654 }
3655 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003656 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003657 }
3658 }
3659
3660 Result += "\t";
3661 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003662 return false;
3663}
3664
3665
3666/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3667/// It handles elaborated types, as well as enum types in the process.
3668void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3669 std::string &Result) {
3670 QualType Type = fieldDecl->getType();
3671 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003672
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003673 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3674 if (!EleboratedType)
3675 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003676 Result += Name;
3677 if (fieldDecl->isBitField()) {
3678 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3679 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003680 else if (EleboratedType && Type->isArrayType()) {
3681 CanQualType CType = Context->getCanonicalType(Type);
3682 while (isa<ArrayType>(CType)) {
3683 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3684 Result += "[";
3685 llvm::APInt Dim = CAT->getSize();
3686 Result += utostr(Dim.getZExtValue());
3687 Result += "]";
3688 }
3689 CType = CType->getAs<ArrayType>()->getElementType();
3690 }
3691 }
3692
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003693 Result += ";\n";
3694}
3695
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003696/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3697/// named aggregate types into the input buffer.
3698void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3699 std::string &Result) {
3700 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003701 if (isa<TypedefType>(Type))
3702 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003703 if (Type->isArrayType())
3704 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003705 ObjCContainerDecl *IDecl =
3706 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003707
3708 TagDecl *TD = 0;
3709 if (Type->isRecordType()) {
3710 TD = Type->getAs<RecordType>()->getDecl();
3711 }
3712 else if (Type->isEnumeralType()) {
3713 TD = Type->getAs<EnumType>()->getDecl();
3714 }
3715
3716 if (TD) {
3717 if (GlobalDefinedTags.count(TD))
3718 return;
3719
3720 bool IsNamedDefinition = false;
3721 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3722 RewriteObjCFieldDeclType(Type, Result);
3723 Result += ";";
3724 }
3725 if (IsNamedDefinition)
3726 GlobalDefinedTags.insert(TD);
3727 }
3728
3729}
3730
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003731/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3732/// an objective-c class with ivars.
3733void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3734 std::string &Result) {
3735 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3736 assert(CDecl->getName() != "" &&
3737 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003738 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003739 SmallVector<ObjCIvarDecl *, 8> IVars;
3740 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003741 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003742 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003743
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003744 SourceLocation LocStart = CDecl->getLocStart();
3745 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003746
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003747 const char *startBuf = SM->getCharacterData(LocStart);
3748 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003749
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003750 // If no ivars and no root or if its root, directly or indirectly,
3751 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003752 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003753 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3754 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3755 ReplaceText(LocStart, endBuf-startBuf, Result);
3756 return;
3757 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003758
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003759 // Insert named struct/union definitions inside class to
3760 // outer scope. This follows semantics of locally defined
3761 // struct/unions in objective-c classes.
3762 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3763 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3764
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003765 Result += "\nstruct ";
3766 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003767 Result += "_IMPL {\n";
3768
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003769 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003770 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3771 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3772 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003773 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003774
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003775 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3776 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003777
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003778 Result += "};\n";
3779 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3780 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003781 // Mark this struct as having been generated.
3782 if (!ObjCSynthesizedStructs.insert(CDecl))
3783 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003784}
3785
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003786/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3787/// have been referenced in an ivar access expression.
3788void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3789 std::string &Result) {
3790 // write out ivar offset symbols which have been referenced in an ivar
3791 // access expression.
3792 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3793 if (Ivars.empty())
3794 return;
3795 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3796 e = Ivars.end(); i != e; i++) {
3797 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003798 Result += "\n";
3799 if (LangOpts.MicrosoftExt)
3800 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003801 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003802 if (LangOpts.MicrosoftExt &&
3803 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003804 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3805 Result += "__declspec(dllimport) ";
3806
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003807 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003808 WriteInternalIvarName(CDecl, IvarDecl, Result);
3809 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003810 }
3811}
3812
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003813//===----------------------------------------------------------------------===//
3814// Meta Data Emission
3815//===----------------------------------------------------------------------===//
3816
3817
3818/// RewriteImplementations - This routine rewrites all method implementations
3819/// and emits meta-data.
3820
3821void RewriteModernObjC::RewriteImplementations() {
3822 int ClsDefCount = ClassImplementation.size();
3823 int CatDefCount = CategoryImplementation.size();
3824
3825 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003826 for (int i = 0; i < ClsDefCount; i++) {
3827 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3828 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3829 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003830 assert(false &&
3831 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003832 RewriteImplementationDecl(OIMP);
3833 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003834
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003835 for (int i = 0; i < CatDefCount; i++) {
3836 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3837 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3838 if (CDecl->isImplicitInterfaceDecl())
3839 assert(false &&
3840 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003841 RewriteImplementationDecl(CIMP);
3842 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003843}
3844
3845void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3846 const std::string &Name,
3847 ValueDecl *VD, bool def) {
3848 assert(BlockByRefDeclNo.count(VD) &&
3849 "RewriteByRefString: ByRef decl missing");
3850 if (def)
3851 ResultStr += "struct ";
3852 ResultStr += "__Block_byref_" + Name +
3853 "_" + utostr(BlockByRefDeclNo[VD]) ;
3854}
3855
3856static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3857 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3858 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3859 return false;
3860}
3861
3862std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3863 StringRef funcName,
3864 std::string Tag) {
3865 const FunctionType *AFT = CE->getFunctionType();
3866 QualType RT = AFT->getResultType();
3867 std::string StructRef = "struct " + Tag;
3868 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003869 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003870
3871 BlockDecl *BD = CE->getBlockDecl();
3872
3873 if (isa<FunctionNoProtoType>(AFT)) {
3874 // No user-supplied arguments. Still need to pass in a pointer to the
3875 // block (to reference imported block decl refs).
3876 S += "(" + StructRef + " *__cself)";
3877 } else if (BD->param_empty()) {
3878 S += "(" + StructRef + " *__cself)";
3879 } else {
3880 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3881 assert(FT && "SynthesizeBlockFunc: No function proto");
3882 S += '(';
3883 // first add the implicit argument.
3884 S += StructRef + " *__cself, ";
3885 std::string ParamStr;
3886 for (BlockDecl::param_iterator AI = BD->param_begin(),
3887 E = BD->param_end(); AI != E; ++AI) {
3888 if (AI != BD->param_begin()) S += ", ";
3889 ParamStr = (*AI)->getNameAsString();
3890 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003891 (void)convertBlockPointerToFunctionPointer(QT);
3892 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003893 S += ParamStr;
3894 }
3895 if (FT->isVariadic()) {
3896 if (!BD->param_empty()) S += ", ";
3897 S += "...";
3898 }
3899 S += ')';
3900 }
3901 S += " {\n";
3902
3903 // Create local declarations to avoid rewriting all closure decl ref exprs.
3904 // First, emit a declaration for all "by ref" decls.
3905 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3906 E = BlockByRefDecls.end(); I != E; ++I) {
3907 S += " ";
3908 std::string Name = (*I)->getNameAsString();
3909 std::string TypeString;
3910 RewriteByRefString(TypeString, Name, (*I));
3911 TypeString += " *";
3912 Name = TypeString + Name;
3913 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3914 }
3915 // Next, emit a declaration for all "by copy" declarations.
3916 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3917 E = BlockByCopyDecls.end(); I != E; ++I) {
3918 S += " ";
3919 // Handle nested closure invocation. For example:
3920 //
3921 // void (^myImportedClosure)(void);
3922 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3923 //
3924 // void (^anotherClosure)(void);
3925 // anotherClosure = ^(void) {
3926 // myImportedClosure(); // import and invoke the closure
3927 // };
3928 //
3929 if (isTopLevelBlockPointerType((*I)->getType())) {
3930 RewriteBlockPointerTypeVariable(S, (*I));
3931 S += " = (";
3932 RewriteBlockPointerType(S, (*I)->getType());
3933 S += ")";
3934 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3935 }
3936 else {
3937 std::string Name = (*I)->getNameAsString();
3938 QualType QT = (*I)->getType();
3939 if (HasLocalVariableExternalStorage(*I))
3940 QT = Context->getPointerType(QT);
3941 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3942 S += Name + " = __cself->" +
3943 (*I)->getNameAsString() + "; // bound by copy\n";
3944 }
3945 }
3946 std::string RewrittenStr = RewrittenBlockExprs[CE];
3947 const char *cstr = RewrittenStr.c_str();
3948 while (*cstr++ != '{') ;
3949 S += cstr;
3950 S += "\n";
3951 return S;
3952}
3953
3954std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3955 StringRef funcName,
3956 std::string Tag) {
3957 std::string StructRef = "struct " + Tag;
3958 std::string S = "static void __";
3959
3960 S += funcName;
3961 S += "_block_copy_" + utostr(i);
3962 S += "(" + StructRef;
3963 S += "*dst, " + StructRef;
3964 S += "*src) {";
3965 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3966 E = ImportedBlockDecls.end(); I != E; ++I) {
3967 ValueDecl *VD = (*I);
3968 S += "_Block_object_assign((void*)&dst->";
3969 S += (*I)->getNameAsString();
3970 S += ", (void*)src->";
3971 S += (*I)->getNameAsString();
3972 if (BlockByRefDeclsPtrSet.count((*I)))
3973 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3974 else if (VD->getType()->isBlockPointerType())
3975 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3976 else
3977 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3978 }
3979 S += "}\n";
3980
3981 S += "\nstatic void __";
3982 S += funcName;
3983 S += "_block_dispose_" + utostr(i);
3984 S += "(" + StructRef;
3985 S += "*src) {";
3986 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3987 E = ImportedBlockDecls.end(); I != E; ++I) {
3988 ValueDecl *VD = (*I);
3989 S += "_Block_object_dispose((void*)src->";
3990 S += (*I)->getNameAsString();
3991 if (BlockByRefDeclsPtrSet.count((*I)))
3992 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3993 else if (VD->getType()->isBlockPointerType())
3994 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3995 else
3996 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3997 }
3998 S += "}\n";
3999 return S;
4000}
4001
4002std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4003 std::string Desc) {
4004 std::string S = "\nstruct " + Tag;
4005 std::string Constructor = " " + Tag;
4006
4007 S += " {\n struct __block_impl impl;\n";
4008 S += " struct " + Desc;
4009 S += "* Desc;\n";
4010
4011 Constructor += "(void *fp, "; // Invoke function pointer.
4012 Constructor += "struct " + Desc; // Descriptor pointer.
4013 Constructor += " *desc";
4014
4015 if (BlockDeclRefs.size()) {
4016 // Output all "by copy" declarations.
4017 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4018 E = BlockByCopyDecls.end(); I != E; ++I) {
4019 S += " ";
4020 std::string FieldName = (*I)->getNameAsString();
4021 std::string ArgName = "_" + FieldName;
4022 // Handle nested closure invocation. For example:
4023 //
4024 // void (^myImportedBlock)(void);
4025 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4026 //
4027 // void (^anotherBlock)(void);
4028 // anotherBlock = ^(void) {
4029 // myImportedBlock(); // import and invoke the closure
4030 // };
4031 //
4032 if (isTopLevelBlockPointerType((*I)->getType())) {
4033 S += "struct __block_impl *";
4034 Constructor += ", void *" + ArgName;
4035 } else {
4036 QualType QT = (*I)->getType();
4037 if (HasLocalVariableExternalStorage(*I))
4038 QT = Context->getPointerType(QT);
4039 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4040 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4041 Constructor += ", " + ArgName;
4042 }
4043 S += FieldName + ";\n";
4044 }
4045 // Output all "by ref" declarations.
4046 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4047 E = BlockByRefDecls.end(); I != E; ++I) {
4048 S += " ";
4049 std::string FieldName = (*I)->getNameAsString();
4050 std::string ArgName = "_" + FieldName;
4051 {
4052 std::string TypeString;
4053 RewriteByRefString(TypeString, FieldName, (*I));
4054 TypeString += " *";
4055 FieldName = TypeString + FieldName;
4056 ArgName = TypeString + ArgName;
4057 Constructor += ", " + ArgName;
4058 }
4059 S += FieldName + "; // by ref\n";
4060 }
4061 // Finish writing the constructor.
4062 Constructor += ", int flags=0)";
4063 // Initialize all "by copy" arguments.
4064 bool firsTime = true;
4065 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4066 E = BlockByCopyDecls.end(); I != E; ++I) {
4067 std::string Name = (*I)->getNameAsString();
4068 if (firsTime) {
4069 Constructor += " : ";
4070 firsTime = false;
4071 }
4072 else
4073 Constructor += ", ";
4074 if (isTopLevelBlockPointerType((*I)->getType()))
4075 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4076 else
4077 Constructor += Name + "(_" + Name + ")";
4078 }
4079 // Initialize all "by ref" arguments.
4080 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4081 E = BlockByRefDecls.end(); I != E; ++I) {
4082 std::string Name = (*I)->getNameAsString();
4083 if (firsTime) {
4084 Constructor += " : ";
4085 firsTime = false;
4086 }
4087 else
4088 Constructor += ", ";
4089 Constructor += Name + "(_" + Name + "->__forwarding)";
4090 }
4091
4092 Constructor += " {\n";
4093 if (GlobalVarDecl)
4094 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4095 else
4096 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4097 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4098
4099 Constructor += " Desc = desc;\n";
4100 } else {
4101 // Finish writing the constructor.
4102 Constructor += ", int flags=0) {\n";
4103 if (GlobalVarDecl)
4104 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4105 else
4106 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4107 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4108 Constructor += " Desc = desc;\n";
4109 }
4110 Constructor += " ";
4111 Constructor += "}\n";
4112 S += Constructor;
4113 S += "};\n";
4114 return S;
4115}
4116
4117std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4118 std::string ImplTag, int i,
4119 StringRef FunName,
4120 unsigned hasCopy) {
4121 std::string S = "\nstatic struct " + DescTag;
4122
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004123 S += " {\n size_t reserved;\n";
4124 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004125 if (hasCopy) {
4126 S += " void (*copy)(struct ";
4127 S += ImplTag; S += "*, struct ";
4128 S += ImplTag; S += "*);\n";
4129
4130 S += " void (*dispose)(struct ";
4131 S += ImplTag; S += "*);\n";
4132 }
4133 S += "} ";
4134
4135 S += DescTag + "_DATA = { 0, sizeof(struct ";
4136 S += ImplTag + ")";
4137 if (hasCopy) {
4138 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4139 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4140 }
4141 S += "};\n";
4142 return S;
4143}
4144
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004145/// getFunctionSourceLocation - returns start location of a function
4146/// definition. Complication arises when function has declared as
4147/// extern "C" or extern "C" {...}
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004148static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
4149 FunctionDecl *FD) {
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00004150 if (FD->isExternC() && !FD->isMain()) {
4151 const DeclContext *DC = FD->getDeclContext();
4152 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
4153 // if it is extern "C" {...}, return function decl's own location.
4154 if (!LSD->getRBraceLoc().isValid())
4155 return LSD->getExternLoc();
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004156 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00004157 if (FD->getStorageClassAsWritten() != SC_None)
4158 R.RewriteBlockLiteralFunctionDecl(FD);
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004159 return FD->getTypeSpecStartLoc();
4160}
4161
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004162void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4163 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004164 bool RewriteSC = (GlobalVarDecl &&
4165 !Blocks.empty() &&
4166 GlobalVarDecl->getStorageClass() == SC_Static &&
4167 GlobalVarDecl->getType().getCVRQualifiers());
4168 if (RewriteSC) {
4169 std::string SC(" void __");
4170 SC += GlobalVarDecl->getNameAsString();
4171 SC += "() {}";
4172 InsertText(FunLocStart, SC);
4173 }
4174
4175 // Insert closures that were part of the function.
4176 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4177 CollectBlockDeclRefInfo(Blocks[i]);
4178 // Need to copy-in the inner copied-in variables not actually used in this
4179 // block.
4180 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004181 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004182 ValueDecl *VD = Exp->getDecl();
4183 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004184 if (!VD->hasAttr<BlocksAttr>()) {
4185 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4186 BlockByCopyDeclsPtrSet.insert(VD);
4187 BlockByCopyDecls.push_back(VD);
4188 }
4189 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004190 }
John McCallf4b88a42012-03-10 09:33:50 +00004191
4192 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004193 BlockByRefDeclsPtrSet.insert(VD);
4194 BlockByRefDecls.push_back(VD);
4195 }
John McCallf4b88a42012-03-10 09:33:50 +00004196
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004197 // imported objects in the inner blocks not used in the outer
4198 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004199 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004200 VD->getType()->isBlockPointerType())
4201 ImportedBlockDecls.insert(VD);
4202 }
4203
4204 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4205 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4206
4207 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4208
4209 InsertText(FunLocStart, CI);
4210
4211 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4212
4213 InsertText(FunLocStart, CF);
4214
4215 if (ImportedBlockDecls.size()) {
4216 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4217 InsertText(FunLocStart, HF);
4218 }
4219 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4220 ImportedBlockDecls.size() > 0);
4221 InsertText(FunLocStart, BD);
4222
4223 BlockDeclRefs.clear();
4224 BlockByRefDecls.clear();
4225 BlockByRefDeclsPtrSet.clear();
4226 BlockByCopyDecls.clear();
4227 BlockByCopyDeclsPtrSet.clear();
4228 ImportedBlockDecls.clear();
4229 }
4230 if (RewriteSC) {
4231 // Must insert any 'const/volatile/static here. Since it has been
4232 // removed as result of rewriting of block literals.
4233 std::string SC;
4234 if (GlobalVarDecl->getStorageClass() == SC_Static)
4235 SC = "static ";
4236 if (GlobalVarDecl->getType().isConstQualified())
4237 SC += "const ";
4238 if (GlobalVarDecl->getType().isVolatileQualified())
4239 SC += "volatile ";
4240 if (GlobalVarDecl->getType().isRestrictQualified())
4241 SC += "restrict ";
4242 InsertText(FunLocStart, SC);
4243 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004244 if (GlobalConstructionExp) {
4245 // extra fancy dance for global literal expression.
4246
4247 // Always the latest block expression on the block stack.
4248 std::string Tag = "__";
4249 Tag += FunName;
4250 Tag += "_block_impl_";
4251 Tag += utostr(Blocks.size()-1);
4252 std::string globalBuf = "static ";
4253 globalBuf += Tag; globalBuf += " ";
4254 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004255
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004256 llvm::raw_string_ostream constructorExprBuf(SStr);
4257 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
4258 PrintingPolicy(LangOpts));
4259 globalBuf += constructorExprBuf.str();
4260 globalBuf += ";\n";
4261 InsertText(FunLocStart, globalBuf);
4262 GlobalConstructionExp = 0;
4263 }
4264
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004265 Blocks.clear();
4266 InnerDeclRefsCount.clear();
4267 InnerDeclRefs.clear();
4268 RewrittenBlockExprs.clear();
4269}
4270
4271void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004272 SourceLocation FunLocStart =
4273 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4274 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004275 StringRef FuncName = FD->getName();
4276
4277 SynthesizeBlockLiterals(FunLocStart, FuncName);
4278}
4279
4280static void BuildUniqueMethodName(std::string &Name,
4281 ObjCMethodDecl *MD) {
4282 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4283 Name = IFace->getName();
4284 Name += "__" + MD->getSelector().getAsString();
4285 // Convert colons to underscores.
4286 std::string::size_type loc = 0;
4287 while ((loc = Name.find(":", loc)) != std::string::npos)
4288 Name.replace(loc, 1, "_");
4289}
4290
4291void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4292 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4293 //SourceLocation FunLocStart = MD->getLocStart();
4294 SourceLocation FunLocStart = MD->getLocStart();
4295 std::string FuncName;
4296 BuildUniqueMethodName(FuncName, MD);
4297 SynthesizeBlockLiterals(FunLocStart, FuncName);
4298}
4299
4300void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4301 for (Stmt::child_range CI = S->children(); CI; ++CI)
4302 if (*CI) {
4303 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4304 GetBlockDeclRefExprs(CBE->getBody());
4305 else
4306 GetBlockDeclRefExprs(*CI);
4307 }
4308 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004309 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4310 if (DRE->refersToEnclosingLocal()) {
4311 // FIXME: Handle enums.
4312 if (!isa<FunctionDecl>(DRE->getDecl()))
4313 BlockDeclRefs.push_back(DRE);
4314 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4315 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004316 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004317 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004318
4319 return;
4320}
4321
4322void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004323 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004324 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4325 for (Stmt::child_range CI = S->children(); CI; ++CI)
4326 if (*CI) {
4327 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4328 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4329 GetInnerBlockDeclRefExprs(CBE->getBody(),
4330 InnerBlockDeclRefs,
4331 InnerContexts);
4332 }
4333 else
4334 GetInnerBlockDeclRefExprs(*CI,
4335 InnerBlockDeclRefs,
4336 InnerContexts);
4337
4338 }
4339 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004340 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4341 if (DRE->refersToEnclosingLocal()) {
4342 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4343 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4344 InnerBlockDeclRefs.push_back(DRE);
4345 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4346 if (Var->isFunctionOrMethodVarDecl())
4347 ImportedLocalExternalDecls.insert(Var);
4348 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004349 }
4350
4351 return;
4352}
4353
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004354/// convertObjCTypeToCStyleType - This routine converts such objc types
4355/// as qualified objects, and blocks to their closest c/c++ types that
4356/// it can. It returns true if input type was modified.
4357bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4358 QualType oldT = T;
4359 convertBlockPointerToFunctionPointer(T);
4360 if (T->isFunctionPointerType()) {
4361 QualType PointeeTy;
4362 if (const PointerType* PT = T->getAs<PointerType>()) {
4363 PointeeTy = PT->getPointeeType();
4364 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4365 T = convertFunctionTypeOfBlocks(FT);
4366 T = Context->getPointerType(T);
4367 }
4368 }
4369 }
4370
4371 convertToUnqualifiedObjCType(T);
4372 return T != oldT;
4373}
4374
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004375/// convertFunctionTypeOfBlocks - This routine converts a function type
4376/// whose result type may be a block pointer or whose argument type(s)
4377/// might be block pointers to an equivalent function type replacing
4378/// all block pointers to function pointers.
4379QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4380 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4381 // FTP will be null for closures that don't take arguments.
4382 // Generate a funky cast.
4383 SmallVector<QualType, 8> ArgTypes;
4384 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004385 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004386
4387 if (FTP) {
4388 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4389 E = FTP->arg_type_end(); I && (I != E); ++I) {
4390 QualType t = *I;
4391 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004392 if (convertObjCTypeToCStyleType(t))
4393 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004394 ArgTypes.push_back(t);
4395 }
4396 }
4397 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004398 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004399 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4400 else FuncType = QualType(FT, 0);
4401 return FuncType;
4402}
4403
4404Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4405 // Navigate to relevant type information.
4406 const BlockPointerType *CPT = 0;
4407
4408 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4409 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004410 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4411 CPT = MExpr->getType()->getAs<BlockPointerType>();
4412 }
4413 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4414 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4415 }
4416 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4417 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4418 else if (const ConditionalOperator *CEXPR =
4419 dyn_cast<ConditionalOperator>(BlockExp)) {
4420 Expr *LHSExp = CEXPR->getLHS();
4421 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4422 Expr *RHSExp = CEXPR->getRHS();
4423 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4424 Expr *CONDExp = CEXPR->getCond();
4425 ConditionalOperator *CondExpr =
4426 new (Context) ConditionalOperator(CONDExp,
4427 SourceLocation(), cast<Expr>(LHSStmt),
4428 SourceLocation(), cast<Expr>(RHSStmt),
4429 Exp->getType(), VK_RValue, OK_Ordinary);
4430 return CondExpr;
4431 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4432 CPT = IRE->getType()->getAs<BlockPointerType>();
4433 } else if (const PseudoObjectExpr *POE
4434 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4435 CPT = POE->getType()->castAs<BlockPointerType>();
4436 } else {
4437 assert(1 && "RewriteBlockClass: Bad type");
4438 }
4439 assert(CPT && "RewriteBlockClass: Bad type");
4440 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4441 assert(FT && "RewriteBlockClass: Bad type");
4442 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4443 // FTP will be null for closures that don't take arguments.
4444
4445 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4446 SourceLocation(), SourceLocation(),
4447 &Context->Idents.get("__block_impl"));
4448 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4449
4450 // Generate a funky cast.
4451 SmallVector<QualType, 8> ArgTypes;
4452
4453 // Push the block argument type.
4454 ArgTypes.push_back(PtrBlock);
4455 if (FTP) {
4456 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4457 E = FTP->arg_type_end(); I && (I != E); ++I) {
4458 QualType t = *I;
4459 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4460 if (!convertBlockPointerToFunctionPointer(t))
4461 convertToUnqualifiedObjCType(t);
4462 ArgTypes.push_back(t);
4463 }
4464 }
4465 // Now do the pointer to function cast.
4466 QualType PtrToFuncCastType
4467 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4468
4469 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4470
4471 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4472 CK_BitCast,
4473 const_cast<Expr*>(BlockExp));
4474 // Don't forget the parens to enforce the proper binding.
4475 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4476 BlkCast);
4477 //PE->dump();
4478
4479 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4480 SourceLocation(),
4481 &Context->Idents.get("FuncPtr"),
4482 Context->VoidPtrTy, 0,
4483 /*BitWidth=*/0, /*Mutable=*/true,
4484 /*HasInit=*/false);
4485 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4486 FD->getType(), VK_LValue,
4487 OK_Ordinary);
4488
4489
4490 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4491 CK_BitCast, ME);
4492 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4493
4494 SmallVector<Expr*, 8> BlkExprs;
4495 // Add the implicit argument.
4496 BlkExprs.push_back(BlkCast);
4497 // Add the user arguments.
4498 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4499 E = Exp->arg_end(); I != E; ++I) {
4500 BlkExprs.push_back(*I);
4501 }
4502 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4503 BlkExprs.size(),
4504 Exp->getType(), VK_RValue,
4505 SourceLocation());
4506 return CE;
4507}
4508
4509// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004510// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004511// For example:
4512//
4513// int main() {
4514// __block Foo *f;
4515// __block int i;
4516//
4517// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004518// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004519// i = 77;
4520// };
4521//}
John McCallf4b88a42012-03-10 09:33:50 +00004522Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004523 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4524 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004525 ValueDecl *VD = DeclRefExp->getDecl();
4526 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004527
4528 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4529 SourceLocation(),
4530 &Context->Idents.get("__forwarding"),
4531 Context->VoidPtrTy, 0,
4532 /*BitWidth=*/0, /*Mutable=*/true,
4533 /*HasInit=*/false);
4534 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4535 FD, SourceLocation(),
4536 FD->getType(), VK_LValue,
4537 OK_Ordinary);
4538
4539 StringRef Name = VD->getName();
4540 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4541 &Context->Idents.get(Name),
4542 Context->VoidPtrTy, 0,
4543 /*BitWidth=*/0, /*Mutable=*/true,
4544 /*HasInit=*/false);
4545 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4546 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4547
4548
4549
4550 // Need parens to enforce precedence.
4551 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4552 DeclRefExp->getExprLoc(),
4553 ME);
4554 ReplaceStmt(DeclRefExp, PE);
4555 return PE;
4556}
4557
4558// Rewrites the imported local variable V with external storage
4559// (static, extern, etc.) as *V
4560//
4561Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4562 ValueDecl *VD = DRE->getDecl();
4563 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4564 if (!ImportedLocalExternalDecls.count(Var))
4565 return DRE;
4566 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4567 VK_LValue, OK_Ordinary,
4568 DRE->getLocation());
4569 // Need parens to enforce precedence.
4570 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4571 Exp);
4572 ReplaceStmt(DRE, PE);
4573 return PE;
4574}
4575
4576void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4577 SourceLocation LocStart = CE->getLParenLoc();
4578 SourceLocation LocEnd = CE->getRParenLoc();
4579
4580 // Need to avoid trying to rewrite synthesized casts.
4581 if (LocStart.isInvalid())
4582 return;
4583 // Need to avoid trying to rewrite casts contained in macros.
4584 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4585 return;
4586
4587 const char *startBuf = SM->getCharacterData(LocStart);
4588 const char *endBuf = SM->getCharacterData(LocEnd);
4589 QualType QT = CE->getType();
4590 const Type* TypePtr = QT->getAs<Type>();
4591 if (isa<TypeOfExprType>(TypePtr)) {
4592 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4593 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4594 std::string TypeAsString = "(";
4595 RewriteBlockPointerType(TypeAsString, QT);
4596 TypeAsString += ")";
4597 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4598 return;
4599 }
4600 // advance the location to startArgList.
4601 const char *argPtr = startBuf;
4602
4603 while (*argPtr++ && (argPtr < endBuf)) {
4604 switch (*argPtr) {
4605 case '^':
4606 // Replace the '^' with '*'.
4607 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4608 ReplaceText(LocStart, 1, "*");
4609 break;
4610 }
4611 }
4612 return;
4613}
4614
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004615void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4616 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004617 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4618 CastKind != CK_AnyPointerToBlockPointerCast)
4619 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004620
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004621 QualType QT = IC->getType();
4622 (void)convertBlockPointerToFunctionPointer(QT);
4623 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4624 std::string Str = "(";
4625 Str += TypeString;
4626 Str += ")";
4627 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4628
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004629 return;
4630}
4631
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004632void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4633 SourceLocation DeclLoc = FD->getLocation();
4634 unsigned parenCount = 0;
4635
4636 // We have 1 or more arguments that have closure pointers.
4637 const char *startBuf = SM->getCharacterData(DeclLoc);
4638 const char *startArgList = strchr(startBuf, '(');
4639
4640 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4641
4642 parenCount++;
4643 // advance the location to startArgList.
4644 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4645 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4646
4647 const char *argPtr = startArgList;
4648
4649 while (*argPtr++ && parenCount) {
4650 switch (*argPtr) {
4651 case '^':
4652 // Replace the '^' with '*'.
4653 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4654 ReplaceText(DeclLoc, 1, "*");
4655 break;
4656 case '(':
4657 parenCount++;
4658 break;
4659 case ')':
4660 parenCount--;
4661 break;
4662 }
4663 }
4664 return;
4665}
4666
4667bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4668 const FunctionProtoType *FTP;
4669 const PointerType *PT = QT->getAs<PointerType>();
4670 if (PT) {
4671 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4672 } else {
4673 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4674 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4675 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4676 }
4677 if (FTP) {
4678 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4679 E = FTP->arg_type_end(); I != E; ++I)
4680 if (isTopLevelBlockPointerType(*I))
4681 return true;
4682 }
4683 return false;
4684}
4685
4686bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4687 const FunctionProtoType *FTP;
4688 const PointerType *PT = QT->getAs<PointerType>();
4689 if (PT) {
4690 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4691 } else {
4692 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4693 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4694 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4695 }
4696 if (FTP) {
4697 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4698 E = FTP->arg_type_end(); I != E; ++I) {
4699 if ((*I)->isObjCQualifiedIdType())
4700 return true;
4701 if ((*I)->isObjCObjectPointerType() &&
4702 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4703 return true;
4704 }
4705
4706 }
4707 return false;
4708}
4709
4710void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4711 const char *&RParen) {
4712 const char *argPtr = strchr(Name, '(');
4713 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4714
4715 LParen = argPtr; // output the start.
4716 argPtr++; // skip past the left paren.
4717 unsigned parenCount = 1;
4718
4719 while (*argPtr && parenCount) {
4720 switch (*argPtr) {
4721 case '(': parenCount++; break;
4722 case ')': parenCount--; break;
4723 default: break;
4724 }
4725 if (parenCount) argPtr++;
4726 }
4727 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4728 RParen = argPtr; // output the end
4729}
4730
4731void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4732 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4733 RewriteBlockPointerFunctionArgs(FD);
4734 return;
4735 }
4736 // Handle Variables and Typedefs.
4737 SourceLocation DeclLoc = ND->getLocation();
4738 QualType DeclT;
4739 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4740 DeclT = VD->getType();
4741 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4742 DeclT = TDD->getUnderlyingType();
4743 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4744 DeclT = FD->getType();
4745 else
4746 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4747
4748 const char *startBuf = SM->getCharacterData(DeclLoc);
4749 const char *endBuf = startBuf;
4750 // scan backward (from the decl location) for the end of the previous decl.
4751 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4752 startBuf--;
4753 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4754 std::string buf;
4755 unsigned OrigLength=0;
4756 // *startBuf != '^' if we are dealing with a pointer to function that
4757 // may take block argument types (which will be handled below).
4758 if (*startBuf == '^') {
4759 // Replace the '^' with '*', computing a negative offset.
4760 buf = '*';
4761 startBuf++;
4762 OrigLength++;
4763 }
4764 while (*startBuf != ')') {
4765 buf += *startBuf;
4766 startBuf++;
4767 OrigLength++;
4768 }
4769 buf += ')';
4770 OrigLength++;
4771
4772 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4773 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4774 // Replace the '^' with '*' for arguments.
4775 // Replace id<P> with id/*<>*/
4776 DeclLoc = ND->getLocation();
4777 startBuf = SM->getCharacterData(DeclLoc);
4778 const char *argListBegin, *argListEnd;
4779 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4780 while (argListBegin < argListEnd) {
4781 if (*argListBegin == '^')
4782 buf += '*';
4783 else if (*argListBegin == '<') {
4784 buf += "/*";
4785 buf += *argListBegin++;
4786 OrigLength++;;
4787 while (*argListBegin != '>') {
4788 buf += *argListBegin++;
4789 OrigLength++;
4790 }
4791 buf += *argListBegin;
4792 buf += "*/";
4793 }
4794 else
4795 buf += *argListBegin;
4796 argListBegin++;
4797 OrigLength++;
4798 }
4799 buf += ')';
4800 OrigLength++;
4801 }
4802 ReplaceText(Start, OrigLength, buf);
4803
4804 return;
4805}
4806
4807
4808/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4809/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4810/// struct Block_byref_id_object *src) {
4811/// _Block_object_assign (&_dest->object, _src->object,
4812/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4813/// [|BLOCK_FIELD_IS_WEAK]) // object
4814/// _Block_object_assign(&_dest->object, _src->object,
4815/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4816/// [|BLOCK_FIELD_IS_WEAK]) // block
4817/// }
4818/// And:
4819/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4820/// _Block_object_dispose(_src->object,
4821/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4822/// [|BLOCK_FIELD_IS_WEAK]) // object
4823/// _Block_object_dispose(_src->object,
4824/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4825/// [|BLOCK_FIELD_IS_WEAK]) // block
4826/// }
4827
4828std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4829 int flag) {
4830 std::string S;
4831 if (CopyDestroyCache.count(flag))
4832 return S;
4833 CopyDestroyCache.insert(flag);
4834 S = "static void __Block_byref_id_object_copy_";
4835 S += utostr(flag);
4836 S += "(void *dst, void *src) {\n";
4837
4838 // offset into the object pointer is computed as:
4839 // void * + void* + int + int + void* + void *
4840 unsigned IntSize =
4841 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4842 unsigned VoidPtrSize =
4843 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4844
4845 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4846 S += " _Block_object_assign((char*)dst + ";
4847 S += utostr(offset);
4848 S += ", *(void * *) ((char*)src + ";
4849 S += utostr(offset);
4850 S += "), ";
4851 S += utostr(flag);
4852 S += ");\n}\n";
4853
4854 S += "static void __Block_byref_id_object_dispose_";
4855 S += utostr(flag);
4856 S += "(void *src) {\n";
4857 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4858 S += utostr(offset);
4859 S += "), ";
4860 S += utostr(flag);
4861 S += ");\n}\n";
4862 return S;
4863}
4864
4865/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4866/// the declaration into:
4867/// struct __Block_byref_ND {
4868/// void *__isa; // NULL for everything except __weak pointers
4869/// struct __Block_byref_ND *__forwarding;
4870/// int32_t __flags;
4871/// int32_t __size;
4872/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4873/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4874/// typex ND;
4875/// };
4876///
4877/// It then replaces declaration of ND variable with:
4878/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4879/// __size=sizeof(struct __Block_byref_ND),
4880/// ND=initializer-if-any};
4881///
4882///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004883void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
4884 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004885 int flag = 0;
4886 int isa = 0;
4887 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4888 if (DeclLoc.isInvalid())
4889 // If type location is missing, it is because of missing type (a warning).
4890 // Use variable's location which is good for this case.
4891 DeclLoc = ND->getLocation();
4892 const char *startBuf = SM->getCharacterData(DeclLoc);
4893 SourceLocation X = ND->getLocEnd();
4894 X = SM->getExpansionLoc(X);
4895 const char *endBuf = SM->getCharacterData(X);
4896 std::string Name(ND->getNameAsString());
4897 std::string ByrefType;
4898 RewriteByRefString(ByrefType, Name, ND, true);
4899 ByrefType += " {\n";
4900 ByrefType += " void *__isa;\n";
4901 RewriteByRefString(ByrefType, Name, ND);
4902 ByrefType += " *__forwarding;\n";
4903 ByrefType += " int __flags;\n";
4904 ByrefType += " int __size;\n";
4905 // Add void *__Block_byref_id_object_copy;
4906 // void *__Block_byref_id_object_dispose; if needed.
4907 QualType Ty = ND->getType();
4908 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4909 if (HasCopyAndDispose) {
4910 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4911 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4912 }
4913
4914 QualType T = Ty;
4915 (void)convertBlockPointerToFunctionPointer(T);
4916 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4917
4918 ByrefType += " " + Name + ";\n";
4919 ByrefType += "};\n";
4920 // Insert this type in global scope. It is needed by helper function.
4921 SourceLocation FunLocStart;
4922 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004923 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004924 else {
4925 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4926 FunLocStart = CurMethodDef->getLocStart();
4927 }
4928 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004929
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004930 if (Ty.isObjCGCWeak()) {
4931 flag |= BLOCK_FIELD_IS_WEAK;
4932 isa = 1;
4933 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004934 if (HasCopyAndDispose) {
4935 flag = BLOCK_BYREF_CALLER;
4936 QualType Ty = ND->getType();
4937 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4938 if (Ty->isBlockPointerType())
4939 flag |= BLOCK_FIELD_IS_BLOCK;
4940 else
4941 flag |= BLOCK_FIELD_IS_OBJECT;
4942 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4943 if (!HF.empty())
4944 InsertText(FunLocStart, HF);
4945 }
4946
4947 // struct __Block_byref_ND ND =
4948 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4949 // initializer-if-any};
4950 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00004951 // FIXME. rewriter does not support __block c++ objects which
4952 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00004953 if (hasInit)
4954 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
4955 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
4956 if (CXXDecl && CXXDecl->isDefaultConstructor())
4957 hasInit = false;
4958 }
4959
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004960 unsigned flags = 0;
4961 if (HasCopyAndDispose)
4962 flags |= BLOCK_HAS_COPY_DISPOSE;
4963 Name = ND->getNameAsString();
4964 ByrefType.clear();
4965 RewriteByRefString(ByrefType, Name, ND);
4966 std::string ForwardingCastType("(");
4967 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004968 ByrefType += " " + Name + " = {(void*)";
4969 ByrefType += utostr(isa);
4970 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4971 ByrefType += utostr(flags);
4972 ByrefType += ", ";
4973 ByrefType += "sizeof(";
4974 RewriteByRefString(ByrefType, Name, ND);
4975 ByrefType += ")";
4976 if (HasCopyAndDispose) {
4977 ByrefType += ", __Block_byref_id_object_copy_";
4978 ByrefType += utostr(flag);
4979 ByrefType += ", __Block_byref_id_object_dispose_";
4980 ByrefType += utostr(flag);
4981 }
4982
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004983 if (!firstDecl) {
4984 // In multiple __block declarations, and for all but 1st declaration,
4985 // find location of the separating comma. This would be start location
4986 // where new text is to be inserted.
4987 DeclLoc = ND->getLocation();
4988 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
4989 const char *commaBuf = startDeclBuf;
4990 while (*commaBuf != ',')
4991 commaBuf--;
4992 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
4993 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
4994 startBuf = commaBuf;
4995 }
4996
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004997 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004998 ByrefType += "};\n";
4999 unsigned nameSize = Name.size();
5000 // for block or function pointer declaration. Name is aleady
5001 // part of the declaration.
5002 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5003 nameSize = 1;
5004 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5005 }
5006 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005007 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005008 SourceLocation startLoc;
5009 Expr *E = ND->getInit();
5010 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5011 startLoc = ECE->getLParenLoc();
5012 else
5013 startLoc = E->getLocStart();
5014 startLoc = SM->getExpansionLoc(startLoc);
5015 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005016 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005017
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005018 const char separator = lastDecl ? ';' : ',';
5019 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5020 const char *separatorBuf = strchr(startInitializerBuf, separator);
5021 assert((*separatorBuf == separator) &&
5022 "RewriteByRefVar: can't find ';' or ','");
5023 SourceLocation separatorLoc =
5024 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5025
5026 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005027 }
5028 return;
5029}
5030
5031void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5032 // Add initializers for any closure decl refs.
5033 GetBlockDeclRefExprs(Exp->getBody());
5034 if (BlockDeclRefs.size()) {
5035 // Unique all "by copy" declarations.
5036 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005037 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005038 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5039 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5040 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5041 }
5042 }
5043 // Unique all "by ref" declarations.
5044 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005045 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005046 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5047 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5048 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5049 }
5050 }
5051 // Find any imported blocks...they will need special attention.
5052 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005053 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005054 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5055 BlockDeclRefs[i]->getType()->isBlockPointerType())
5056 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5057 }
5058}
5059
5060FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5061 IdentifierInfo *ID = &Context->Idents.get(name);
5062 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5063 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5064 SourceLocation(), ID, FType, 0, SC_Extern,
5065 SC_None, false, false);
5066}
5067
5068Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005069 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005070
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005071 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005072
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005073 Blocks.push_back(Exp);
5074
5075 CollectBlockDeclRefInfo(Exp);
5076
5077 // Add inner imported variables now used in current block.
5078 int countOfInnerDecls = 0;
5079 if (!InnerBlockDeclRefs.empty()) {
5080 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005081 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005082 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005083 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005084 // We need to save the copied-in variables in nested
5085 // blocks because it is needed at the end for some of the API generations.
5086 // See SynthesizeBlockLiterals routine.
5087 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5088 BlockDeclRefs.push_back(Exp);
5089 BlockByCopyDeclsPtrSet.insert(VD);
5090 BlockByCopyDecls.push_back(VD);
5091 }
John McCallf4b88a42012-03-10 09:33:50 +00005092 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005093 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5094 BlockDeclRefs.push_back(Exp);
5095 BlockByRefDeclsPtrSet.insert(VD);
5096 BlockByRefDecls.push_back(VD);
5097 }
5098 }
5099 // Find any imported blocks...they will need special attention.
5100 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005101 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005102 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5103 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5104 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5105 }
5106 InnerDeclRefsCount.push_back(countOfInnerDecls);
5107
5108 std::string FuncName;
5109
5110 if (CurFunctionDef)
5111 FuncName = CurFunctionDef->getNameAsString();
5112 else if (CurMethodDef)
5113 BuildUniqueMethodName(FuncName, CurMethodDef);
5114 else if (GlobalVarDecl)
5115 FuncName = std::string(GlobalVarDecl->getNameAsString());
5116
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005117 bool GlobalBlockExpr =
5118 block->getDeclContext()->getRedeclContext()->isFileContext();
5119
5120 if (GlobalBlockExpr && !GlobalVarDecl) {
5121 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5122 GlobalBlockExpr = false;
5123 }
5124
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005125 std::string BlockNumber = utostr(Blocks.size()-1);
5126
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005127 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5128
5129 // Get a pointer to the function type so we can cast appropriately.
5130 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5131 QualType FType = Context->getPointerType(BFT);
5132
5133 FunctionDecl *FD;
5134 Expr *NewRep;
5135
5136 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005137 std::string Tag;
5138
5139 if (GlobalBlockExpr)
5140 Tag = "__global_";
5141 else
5142 Tag = "__";
5143 Tag += FuncName + "_block_impl_" + BlockNumber;
5144
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005145 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005146 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005147 SourceLocation());
5148
5149 SmallVector<Expr*, 4> InitExprs;
5150
5151 // Initialize the block function.
5152 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005153 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5154 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005155 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5156 CK_BitCast, Arg);
5157 InitExprs.push_back(castExpr);
5158
5159 // Initialize the block descriptor.
5160 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5161
5162 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5163 SourceLocation(), SourceLocation(),
5164 &Context->Idents.get(DescData.c_str()),
5165 Context->VoidPtrTy, 0,
5166 SC_Static, SC_None);
5167 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005168 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005169 Context->VoidPtrTy,
5170 VK_LValue,
5171 SourceLocation()),
5172 UO_AddrOf,
5173 Context->getPointerType(Context->VoidPtrTy),
5174 VK_RValue, OK_Ordinary,
5175 SourceLocation());
5176 InitExprs.push_back(DescRefExpr);
5177
5178 // Add initializers for any closure decl refs.
5179 if (BlockDeclRefs.size()) {
5180 Expr *Exp;
5181 // Output all "by copy" declarations.
5182 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5183 E = BlockByCopyDecls.end(); I != E; ++I) {
5184 if (isObjCType((*I)->getType())) {
5185 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5186 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005187 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5188 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005189 if (HasLocalVariableExternalStorage(*I)) {
5190 QualType QT = (*I)->getType();
5191 QT = Context->getPointerType(QT);
5192 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5193 OK_Ordinary, SourceLocation());
5194 }
5195 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5196 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005197 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5198 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005199 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5200 CK_BitCast, Arg);
5201 } else {
5202 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005203 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5204 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005205 if (HasLocalVariableExternalStorage(*I)) {
5206 QualType QT = (*I)->getType();
5207 QT = Context->getPointerType(QT);
5208 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5209 OK_Ordinary, SourceLocation());
5210 }
5211
5212 }
5213 InitExprs.push_back(Exp);
5214 }
5215 // Output all "by ref" declarations.
5216 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5217 E = BlockByRefDecls.end(); I != E; ++I) {
5218 ValueDecl *ND = (*I);
5219 std::string Name(ND->getNameAsString());
5220 std::string RecName;
5221 RewriteByRefString(RecName, Name, ND, true);
5222 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5223 + sizeof("struct"));
5224 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5225 SourceLocation(), SourceLocation(),
5226 II);
5227 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5228 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5229
5230 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005231 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005232 SourceLocation());
5233 bool isNestedCapturedVar = false;
5234 if (block)
5235 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5236 ce = block->capture_end(); ci != ce; ++ci) {
5237 const VarDecl *variable = ci->getVariable();
5238 if (variable == ND && ci->isNested()) {
5239 assert (ci->isByRef() &&
5240 "SynthBlockInitExpr - captured block variable is not byref");
5241 isNestedCapturedVar = true;
5242 break;
5243 }
5244 }
5245 // captured nested byref variable has its address passed. Do not take
5246 // its address again.
5247 if (!isNestedCapturedVar)
5248 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5249 Context->getPointerType(Exp->getType()),
5250 VK_RValue, OK_Ordinary, SourceLocation());
5251 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5252 InitExprs.push_back(Exp);
5253 }
5254 }
5255 if (ImportedBlockDecls.size()) {
5256 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5257 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5258 unsigned IntSize =
5259 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5260 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5261 Context->IntTy, SourceLocation());
5262 InitExprs.push_back(FlagExp);
5263 }
5264 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5265 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005266
5267 if (GlobalBlockExpr) {
5268 assert (GlobalConstructionExp == 0 &&
5269 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5270 GlobalConstructionExp = NewRep;
5271 NewRep = DRE;
5272 }
5273
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005274 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5275 Context->getPointerType(NewRep->getType()),
5276 VK_RValue, OK_Ordinary, SourceLocation());
5277 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5278 NewRep);
5279 BlockDeclRefs.clear();
5280 BlockByRefDecls.clear();
5281 BlockByRefDeclsPtrSet.clear();
5282 BlockByCopyDecls.clear();
5283 BlockByCopyDeclsPtrSet.clear();
5284 ImportedBlockDecls.clear();
5285 return NewRep;
5286}
5287
5288bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5289 if (const ObjCForCollectionStmt * CS =
5290 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5291 return CS->getElement() == DS;
5292 return false;
5293}
5294
5295//===----------------------------------------------------------------------===//
5296// Function Body / Expression rewriting
5297//===----------------------------------------------------------------------===//
5298
5299Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5300 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5301 isa<DoStmt>(S) || isa<ForStmt>(S))
5302 Stmts.push_back(S);
5303 else if (isa<ObjCForCollectionStmt>(S)) {
5304 Stmts.push_back(S);
5305 ObjCBcLabelNo.push_back(++BcLabelCount);
5306 }
5307
5308 // Pseudo-object operations and ivar references need special
5309 // treatment because we're going to recursively rewrite them.
5310 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5311 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5312 return RewritePropertyOrImplicitSetter(PseudoOp);
5313 } else {
5314 return RewritePropertyOrImplicitGetter(PseudoOp);
5315 }
5316 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5317 return RewriteObjCIvarRefExpr(IvarRefExpr);
5318 }
5319
5320 SourceRange OrigStmtRange = S->getSourceRange();
5321
5322 // Perform a bottom up rewrite of all children.
5323 for (Stmt::child_range CI = S->children(); CI; ++CI)
5324 if (*CI) {
5325 Stmt *childStmt = (*CI);
5326 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5327 if (newStmt) {
5328 *CI = newStmt;
5329 }
5330 }
5331
5332 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005333 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005334 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5335 InnerContexts.insert(BE->getBlockDecl());
5336 ImportedLocalExternalDecls.clear();
5337 GetInnerBlockDeclRefExprs(BE->getBody(),
5338 InnerBlockDeclRefs, InnerContexts);
5339 // Rewrite the block body in place.
5340 Stmt *SaveCurrentBody = CurrentBody;
5341 CurrentBody = BE->getBody();
5342 PropParentMap = 0;
5343 // block literal on rhs of a property-dot-sytax assignment
5344 // must be replaced by its synthesize ast so getRewrittenText
5345 // works as expected. In this case, what actually ends up on RHS
5346 // is the blockTranscribed which is the helper function for the
5347 // block literal; as in: self.c = ^() {[ace ARR];};
5348 bool saveDisableReplaceStmt = DisableReplaceStmt;
5349 DisableReplaceStmt = false;
5350 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5351 DisableReplaceStmt = saveDisableReplaceStmt;
5352 CurrentBody = SaveCurrentBody;
5353 PropParentMap = 0;
5354 ImportedLocalExternalDecls.clear();
5355 // Now we snarf the rewritten text and stash it away for later use.
5356 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5357 RewrittenBlockExprs[BE] = Str;
5358
5359 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5360
5361 //blockTranscribed->dump();
5362 ReplaceStmt(S, blockTranscribed);
5363 return blockTranscribed;
5364 }
5365 // Handle specific things.
5366 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5367 return RewriteAtEncode(AtEncode);
5368
5369 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5370 return RewriteAtSelector(AtSelector);
5371
5372 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5373 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005374
5375 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5376 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005377
Patrick Beardeb382ec2012-04-19 00:25:12 +00005378 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5379 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005380
5381 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5382 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005383
5384 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5385 dyn_cast<ObjCDictionaryLiteral>(S))
5386 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005387
5388 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5389#if 0
5390 // Before we rewrite it, put the original message expression in a comment.
5391 SourceLocation startLoc = MessExpr->getLocStart();
5392 SourceLocation endLoc = MessExpr->getLocEnd();
5393
5394 const char *startBuf = SM->getCharacterData(startLoc);
5395 const char *endBuf = SM->getCharacterData(endLoc);
5396
5397 std::string messString;
5398 messString += "// ";
5399 messString.append(startBuf, endBuf-startBuf+1);
5400 messString += "\n";
5401
5402 // FIXME: Missing definition of
5403 // InsertText(clang::SourceLocation, char const*, unsigned int).
5404 // InsertText(startLoc, messString.c_str(), messString.size());
5405 // Tried this, but it didn't work either...
5406 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5407#endif
5408 return RewriteMessageExpr(MessExpr);
5409 }
5410
5411 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5412 return RewriteObjCTryStmt(StmtTry);
5413
5414 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5415 return RewriteObjCSynchronizedStmt(StmtTry);
5416
5417 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5418 return RewriteObjCThrowStmt(StmtThrow);
5419
5420 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5421 return RewriteObjCProtocolExpr(ProtocolExp);
5422
5423 if (ObjCForCollectionStmt *StmtForCollection =
5424 dyn_cast<ObjCForCollectionStmt>(S))
5425 return RewriteObjCForCollectionStmt(StmtForCollection,
5426 OrigStmtRange.getEnd());
5427 if (BreakStmt *StmtBreakStmt =
5428 dyn_cast<BreakStmt>(S))
5429 return RewriteBreakStmt(StmtBreakStmt);
5430 if (ContinueStmt *StmtContinueStmt =
5431 dyn_cast<ContinueStmt>(S))
5432 return RewriteContinueStmt(StmtContinueStmt);
5433
5434 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5435 // and cast exprs.
5436 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5437 // FIXME: What we're doing here is modifying the type-specifier that
5438 // precedes the first Decl. In the future the DeclGroup should have
5439 // a separate type-specifier that we can rewrite.
5440 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5441 // the context of an ObjCForCollectionStmt. For example:
5442 // NSArray *someArray;
5443 // for (id <FooProtocol> index in someArray) ;
5444 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5445 // and it depends on the original text locations/positions.
5446 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5447 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5448
5449 // Blocks rewrite rules.
5450 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5451 DI != DE; ++DI) {
5452 Decl *SD = *DI;
5453 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5454 if (isTopLevelBlockPointerType(ND->getType()))
5455 RewriteBlockPointerDecl(ND);
5456 else if (ND->getType()->isFunctionPointerType())
5457 CheckFunctionPointerDecl(ND->getType(), ND);
5458 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5459 if (VD->hasAttr<BlocksAttr>()) {
5460 static unsigned uniqueByrefDeclCount = 0;
5461 assert(!BlockByRefDeclNo.count(ND) &&
5462 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5463 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005464 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005465 }
5466 else
5467 RewriteTypeOfDecl(VD);
5468 }
5469 }
5470 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5471 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5472 RewriteBlockPointerDecl(TD);
5473 else if (TD->getUnderlyingType()->isFunctionPointerType())
5474 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5475 }
5476 }
5477 }
5478
5479 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5480 RewriteObjCQualifiedInterfaceTypes(CE);
5481
5482 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5483 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5484 assert(!Stmts.empty() && "Statement stack is empty");
5485 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5486 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5487 && "Statement stack mismatch");
5488 Stmts.pop_back();
5489 }
5490 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005491 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5492 ValueDecl *VD = DRE->getDecl();
5493 if (VD->hasAttr<BlocksAttr>())
5494 return RewriteBlockDeclRefExpr(DRE);
5495 if (HasLocalVariableExternalStorage(VD))
5496 return RewriteLocalVariableExternalStorage(DRE);
5497 }
5498
5499 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5500 if (CE->getCallee()->getType()->isBlockPointerType()) {
5501 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5502 ReplaceStmt(S, BlockCall);
5503 return BlockCall;
5504 }
5505 }
5506 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5507 RewriteCastExpr(CE);
5508 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005509 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5510 RewriteImplicitCastObjCExpr(ICE);
5511 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005512#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005513
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005514 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5515 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5516 ICE->getSubExpr(),
5517 SourceLocation());
5518 // Get the new text.
5519 std::string SStr;
5520 llvm::raw_string_ostream Buf(SStr);
5521 Replacement->printPretty(Buf, *Context);
5522 const std::string &Str = Buf.str();
5523
5524 printf("CAST = %s\n", &Str[0]);
5525 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5526 delete S;
5527 return Replacement;
5528 }
5529#endif
5530 // Return this stmt unmodified.
5531 return S;
5532}
5533
5534void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5535 for (RecordDecl::field_iterator i = RD->field_begin(),
5536 e = RD->field_end(); i != e; ++i) {
David Blaikie262bc182012-04-30 02:36:29 +00005537 FieldDecl *FD = &*i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005538 if (isTopLevelBlockPointerType(FD->getType()))
5539 RewriteBlockPointerDecl(FD);
5540 if (FD->getType()->isObjCQualifiedIdType() ||
5541 FD->getType()->isObjCQualifiedInterfaceType())
5542 RewriteObjCQualifiedInterfaceTypes(FD);
5543 }
5544}
5545
5546/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5547/// main file of the input.
5548void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5549 switch (D->getKind()) {
5550 case Decl::Function: {
5551 FunctionDecl *FD = cast<FunctionDecl>(D);
5552 if (FD->isOverloadedOperator())
5553 return;
5554
5555 // Since function prototypes don't have ParmDecl's, we check the function
5556 // prototype. This enables us to rewrite function declarations and
5557 // definitions using the same code.
5558 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5559
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005560 if (!FD->isThisDeclarationADefinition())
5561 break;
5562
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005563 // FIXME: If this should support Obj-C++, support CXXTryStmt
5564 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5565 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005566 CurrentBody = Body;
5567 Body =
5568 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5569 FD->setBody(Body);
5570 CurrentBody = 0;
5571 if (PropParentMap) {
5572 delete PropParentMap;
5573 PropParentMap = 0;
5574 }
5575 // This synthesizes and inserts the block "impl" struct, invoke function,
5576 // and any copy/dispose helper functions.
5577 InsertBlockLiteralsWithinFunction(FD);
5578 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005579 }
5580 break;
5581 }
5582 case Decl::ObjCMethod: {
5583 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5584 if (CompoundStmt *Body = MD->getCompoundBody()) {
5585 CurMethodDef = MD;
5586 CurrentBody = Body;
5587 Body =
5588 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5589 MD->setBody(Body);
5590 CurrentBody = 0;
5591 if (PropParentMap) {
5592 delete PropParentMap;
5593 PropParentMap = 0;
5594 }
5595 InsertBlockLiteralsWithinMethod(MD);
5596 CurMethodDef = 0;
5597 }
5598 break;
5599 }
5600 case Decl::ObjCImplementation: {
5601 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5602 ClassImplementation.push_back(CI);
5603 break;
5604 }
5605 case Decl::ObjCCategoryImpl: {
5606 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5607 CategoryImplementation.push_back(CI);
5608 break;
5609 }
5610 case Decl::Var: {
5611 VarDecl *VD = cast<VarDecl>(D);
5612 RewriteObjCQualifiedInterfaceTypes(VD);
5613 if (isTopLevelBlockPointerType(VD->getType()))
5614 RewriteBlockPointerDecl(VD);
5615 else if (VD->getType()->isFunctionPointerType()) {
5616 CheckFunctionPointerDecl(VD->getType(), VD);
5617 if (VD->getInit()) {
5618 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5619 RewriteCastExpr(CE);
5620 }
5621 }
5622 } else if (VD->getType()->isRecordType()) {
5623 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5624 if (RD->isCompleteDefinition())
5625 RewriteRecordBody(RD);
5626 }
5627 if (VD->getInit()) {
5628 GlobalVarDecl = VD;
5629 CurrentBody = VD->getInit();
5630 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5631 CurrentBody = 0;
5632 if (PropParentMap) {
5633 delete PropParentMap;
5634 PropParentMap = 0;
5635 }
5636 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5637 GlobalVarDecl = 0;
5638
5639 // This is needed for blocks.
5640 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5641 RewriteCastExpr(CE);
5642 }
5643 }
5644 break;
5645 }
5646 case Decl::TypeAlias:
5647 case Decl::Typedef: {
5648 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5649 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5650 RewriteBlockPointerDecl(TD);
5651 else if (TD->getUnderlyingType()->isFunctionPointerType())
5652 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5653 }
5654 break;
5655 }
5656 case Decl::CXXRecord:
5657 case Decl::Record: {
5658 RecordDecl *RD = cast<RecordDecl>(D);
5659 if (RD->isCompleteDefinition())
5660 RewriteRecordBody(RD);
5661 break;
5662 }
5663 default:
5664 break;
5665 }
5666 // Nothing yet.
5667}
5668
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005669/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5670/// protocol reference symbols in the for of:
5671/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5672static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5673 ObjCProtocolDecl *PDecl,
5674 std::string &Result) {
5675 // Also output .objc_protorefs$B section and its meta-data.
5676 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00005677 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005678 Result += "struct _protocol_t *";
5679 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5680 Result += PDecl->getNameAsString();
5681 Result += " = &";
5682 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5683 Result += ";\n";
5684}
5685
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005686void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5687 if (Diags.hasErrorOccurred())
5688 return;
5689
5690 RewriteInclude();
5691
5692 // Here's a great place to add any extra declarations that may be needed.
5693 // Write out meta data for each @protocol(<expr>).
5694 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005695 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005696 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005697 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5698 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005699
5700 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00005701
5702 if (ClassImplementation.size() || CategoryImplementation.size())
5703 RewriteImplementations();
5704
Fariborz Jahanian57317782012-02-21 23:58:41 +00005705 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5706 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5707 // Write struct declaration for the class matching its ivar declarations.
5708 // Note that for modern abi, this is postponed until the end of TU
5709 // because class extensions and the implementation might declare their own
5710 // private ivars.
5711 RewriteInterfaceDecl(CDecl);
5712 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005713
5714 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5715 // we are done.
5716 if (const RewriteBuffer *RewriteBuf =
5717 Rewrite.getRewriteBufferFor(MainFileID)) {
5718 //printf("Changed:\n");
5719 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5720 } else {
5721 llvm::errs() << "No changes\n";
5722 }
5723
5724 if (ClassImplementation.size() || CategoryImplementation.size() ||
5725 ProtocolExprDecls.size()) {
5726 // Rewrite Objective-c meta data*
5727 std::string ResultStr;
5728 RewriteMetaDataIntoBuffer(ResultStr);
5729 // Emit metadata.
5730 *OutFile << ResultStr;
5731 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005732 // Emit ImageInfo;
5733 {
5734 std::string ResultStr;
5735 WriteImageInfo(ResultStr);
5736 *OutFile << ResultStr;
5737 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005738 OutFile->flush();
5739}
5740
5741void RewriteModernObjC::Initialize(ASTContext &context) {
5742 InitializeCommon(context);
5743
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005744 Preamble += "#ifndef __OBJC2__\n";
5745 Preamble += "#define __OBJC2__\n";
5746 Preamble += "#endif\n";
5747
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005748 // declaring objc_selector outside the parameter list removes a silly
5749 // scope related warning...
5750 if (IsHeader)
5751 Preamble = "#pragma once\n";
5752 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005753 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5754 Preamble += "\n\tstruct objc_object *superClass; ";
5755 // Add a constructor for creating temporary objects.
5756 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5757 Preamble += ": object(o), superClass(s) {} ";
5758 Preamble += "\n};\n";
5759
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005760 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005761 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005762 // These are currently generated.
5763 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005764 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005765 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005766 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5767 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005768 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005769 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005770 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5771 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005772 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005773
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005774 // These need be generated for performance. Currently they are not,
5775 // using API calls instead.
5776 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5777 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5778 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5779
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005780 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005781 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5782 Preamble += "typedef struct objc_object Protocol;\n";
5783 Preamble += "#define _REWRITER_typedef_Protocol\n";
5784 Preamble += "#endif\n";
5785 if (LangOpts.MicrosoftExt) {
5786 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5787 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005788 }
5789 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005790 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005791
5792 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5793 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5794 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5795 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5796 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5797
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005798 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005799 Preamble += "(const char *);\n";
5800 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5801 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005802 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005803 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005804 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005805 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005806 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5807 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005808 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5809 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5810 Preamble += "struct __objcFastEnumerationState {\n\t";
5811 Preamble += "unsigned long state;\n\t";
5812 Preamble += "void **itemsPtr;\n\t";
5813 Preamble += "unsigned long *mutationsPtr;\n\t";
5814 Preamble += "unsigned long extra[5];\n};\n";
5815 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5816 Preamble += "#define __FASTENUMERATIONSTATE\n";
5817 Preamble += "#endif\n";
5818 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5819 Preamble += "struct __NSConstantStringImpl {\n";
5820 Preamble += " int *isa;\n";
5821 Preamble += " int flags;\n";
5822 Preamble += " char *str;\n";
5823 Preamble += " long length;\n";
5824 Preamble += "};\n";
5825 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5826 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5827 Preamble += "#else\n";
5828 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5829 Preamble += "#endif\n";
5830 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5831 Preamble += "#endif\n";
5832 // Blocks preamble.
5833 Preamble += "#ifndef BLOCK_IMPL\n";
5834 Preamble += "#define BLOCK_IMPL\n";
5835 Preamble += "struct __block_impl {\n";
5836 Preamble += " void *isa;\n";
5837 Preamble += " int Flags;\n";
5838 Preamble += " int Reserved;\n";
5839 Preamble += " void *FuncPtr;\n";
5840 Preamble += "};\n";
5841 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5842 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5843 Preamble += "extern \"C\" __declspec(dllexport) "
5844 "void _Block_object_assign(void *, const void *, const int);\n";
5845 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5846 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5847 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5848 Preamble += "#else\n";
5849 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5850 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5851 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5852 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5853 Preamble += "#endif\n";
5854 Preamble += "#endif\n";
5855 if (LangOpts.MicrosoftExt) {
5856 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5857 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5858 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5859 Preamble += "#define __attribute__(X)\n";
5860 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005861 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005862 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005863 Preamble += "#endif\n";
5864 Preamble += "#ifndef __block\n";
5865 Preamble += "#define __block\n";
5866 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005867 }
5868 else {
5869 Preamble += "#define __block\n";
5870 Preamble += "#define __weak\n";
5871 }
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005872
5873 // Declarations required for modern objective-c array and dictionary literals.
5874 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005875 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005876 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005877 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005878 Preamble += "\tva_list marker;\n";
5879 Preamble += "\tva_start(marker, count);\n";
5880 Preamble += "\tarr = new void *[count];\n";
5881 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5882 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5883 Preamble += "\tva_end( marker );\n";
5884 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00005885 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005886 Preamble += "\tdelete[] arr;\n";
5887 Preamble += " }\n";
5888 Preamble += "};\n";
5889
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005890 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5891 // as this avoids warning in any 64bit/32bit compilation model.
5892 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5893}
5894
5895/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5896/// ivar offset.
5897void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5898 std::string &Result) {
5899 if (ivar->isBitField()) {
5900 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5901 // place all bitfields at offset 0.
5902 Result += "0";
5903 } else {
5904 Result += "__OFFSETOFIVAR__(struct ";
5905 Result += ivar->getContainingInterface()->getNameAsString();
5906 if (LangOpts.MicrosoftExt)
5907 Result += "_IMPL";
5908 Result += ", ";
5909 Result += ivar->getNameAsString();
5910 Result += ")";
5911 }
5912}
5913
5914/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5915/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005916/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005917/// char *attributes;
5918/// }
5919
5920/// struct _prop_list_t {
5921/// uint32_t entsize; // sizeof(struct _prop_t)
5922/// uint32_t count_of_properties;
5923/// struct _prop_t prop_list[count_of_properties];
5924/// }
5925
5926/// struct _protocol_t;
5927
5928/// struct _protocol_list_t {
5929/// long protocol_count; // Note, this is 32/64 bit
5930/// struct _protocol_t * protocol_list[protocol_count];
5931/// }
5932
5933/// struct _objc_method {
5934/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005935/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005936/// char *_imp;
5937/// }
5938
5939/// struct _method_list_t {
5940/// uint32_t entsize; // sizeof(struct _objc_method)
5941/// uint32_t method_count;
5942/// struct _objc_method method_list[method_count];
5943/// }
5944
5945/// struct _protocol_t {
5946/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005947/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005948/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005949/// const struct method_list_t *instance_methods;
5950/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005951/// const struct method_list_t *optionalInstanceMethods;
5952/// const struct method_list_t *optionalClassMethods;
5953/// const struct _prop_list_t * properties;
5954/// const uint32_t size; // sizeof(struct _protocol_t)
5955/// const uint32_t flags; // = 0
5956/// const char ** extendedMethodTypes;
5957/// }
5958
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005959/// struct _ivar_t {
5960/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005961/// const char *name;
5962/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005963/// uint32_t alignment;
5964/// uint32_t size;
5965/// }
5966
5967/// struct _ivar_list_t {
5968/// uint32 entsize; // sizeof(struct _ivar_t)
5969/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005970/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005971/// }
5972
5973/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005974/// uint32_t flags;
5975/// uint32_t instanceStart;
5976/// uint32_t instanceSize;
5977/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005978/// const uint8_t *ivarLayout;
5979/// const char *name;
5980/// const struct _method_list_t *baseMethods;
5981/// const struct _protocol_list_t *baseProtocols;
5982/// const struct _ivar_list_t *ivars;
5983/// const uint8_t *weakIvarLayout;
5984/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005985/// }
5986
5987/// struct _class_t {
5988/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005989/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005990/// void *cache;
5991/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005992/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005993/// }
5994
5995/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005996/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005997/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005998/// const struct _method_list_t *instance_methods;
5999/// const struct _method_list_t *class_methods;
6000/// const struct _protocol_list_t *protocols;
6001/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006002/// }
6003
6004/// MessageRefTy - LLVM for:
6005/// struct _message_ref_t {
6006/// IMP messenger;
6007/// SEL name;
6008/// };
6009
6010/// SuperMessageRefTy - LLVM for:
6011/// struct _super_message_ref_t {
6012/// SUPER_IMP messenger;
6013/// SEL name;
6014/// };
6015
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006016static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006017 static bool meta_data_declared = false;
6018 if (meta_data_declared)
6019 return;
6020
6021 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006022 Result += "\tconst char *name;\n";
6023 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006024 Result += "};\n";
6025
6026 Result += "\nstruct _protocol_t;\n";
6027
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006028 Result += "\nstruct _objc_method {\n";
6029 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006030 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006031 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006032 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006033
6034 Result += "\nstruct _protocol_t {\n";
6035 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006036 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006037 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006038 Result += "\tconst struct method_list_t *instance_methods;\n";
6039 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006040 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6041 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6042 Result += "\tconst struct _prop_list_t * properties;\n";
6043 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6044 Result += "\tconst unsigned int flags; // = 0\n";
6045 Result += "\tconst char ** extendedMethodTypes;\n";
6046 Result += "};\n";
6047
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006048 Result += "\nstruct _ivar_t {\n";
6049 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006050 Result += "\tconst char *name;\n";
6051 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006052 Result += "\tunsigned int alignment;\n";
6053 Result += "\tunsigned int size;\n";
6054 Result += "};\n";
6055
6056 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006057 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006058 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006059 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006060 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6061 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006062 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006063 Result += "\tconst unsigned char *ivarLayout;\n";
6064 Result += "\tconst char *name;\n";
6065 Result += "\tconst struct _method_list_t *baseMethods;\n";
6066 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6067 Result += "\tconst struct _ivar_list_t *ivars;\n";
6068 Result += "\tconst unsigned char *weakIvarLayout;\n";
6069 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006070 Result += "};\n";
6071
6072 Result += "\nstruct _class_t {\n";
6073 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006074 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006075 Result += "\tvoid *cache;\n";
6076 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006077 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006078 Result += "};\n";
6079
6080 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006081 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006082 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006083 Result += "\tconst struct _method_list_t *instance_methods;\n";
6084 Result += "\tconst struct _method_list_t *class_methods;\n";
6085 Result += "\tconst struct _protocol_list_t *protocols;\n";
6086 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006087 Result += "};\n";
6088
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006089 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006090 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006091 meta_data_declared = true;
6092}
6093
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006094static void Write_protocol_list_t_TypeDecl(std::string &Result,
6095 long super_protocol_count) {
6096 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6097 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6098 Result += "\tstruct _protocol_t *super_protocols[";
6099 Result += utostr(super_protocol_count); Result += "];\n";
6100 Result += "}";
6101}
6102
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006103static void Write_method_list_t_TypeDecl(std::string &Result,
6104 unsigned int method_count) {
6105 Result += "struct /*_method_list_t*/"; Result += " {\n";
6106 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6107 Result += "\tunsigned int method_count;\n";
6108 Result += "\tstruct _objc_method method_list[";
6109 Result += utostr(method_count); Result += "];\n";
6110 Result += "}";
6111}
6112
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006113static void Write__prop_list_t_TypeDecl(std::string &Result,
6114 unsigned int property_count) {
6115 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6116 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6117 Result += "\tunsigned int count_of_properties;\n";
6118 Result += "\tstruct _prop_t prop_list[";
6119 Result += utostr(property_count); Result += "];\n";
6120 Result += "}";
6121}
6122
Fariborz Jahanianae932952012-02-10 20:47:10 +00006123static void Write__ivar_list_t_TypeDecl(std::string &Result,
6124 unsigned int ivar_count) {
6125 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6126 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6127 Result += "\tunsigned int count;\n";
6128 Result += "\tstruct _ivar_t ivar_list[";
6129 Result += utostr(ivar_count); Result += "];\n";
6130 Result += "}";
6131}
6132
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006133static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6134 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6135 StringRef VarName,
6136 StringRef ProtocolName) {
6137 if (SuperProtocols.size() > 0) {
6138 Result += "\nstatic ";
6139 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6140 Result += " "; Result += VarName;
6141 Result += ProtocolName;
6142 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6143 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6144 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6145 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6146 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6147 Result += SuperPD->getNameAsString();
6148 if (i == e-1)
6149 Result += "\n};\n";
6150 else
6151 Result += ",\n";
6152 }
6153 }
6154}
6155
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006156static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6157 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006158 ArrayRef<ObjCMethodDecl *> Methods,
6159 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006160 StringRef TopLevelDeclName,
6161 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006162 if (Methods.size() > 0) {
6163 Result += "\nstatic ";
6164 Write_method_list_t_TypeDecl(Result, Methods.size());
6165 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006166 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006167 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6168 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6169 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6170 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6171 ObjCMethodDecl *MD = Methods[i];
6172 if (i == 0)
6173 Result += "\t{{(struct objc_selector *)\"";
6174 else
6175 Result += "\t{(struct objc_selector *)\"";
6176 Result += (MD)->getSelector().getAsString(); Result += "\"";
6177 Result += ", ";
6178 std::string MethodTypeString;
6179 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6180 Result += "\""; Result += MethodTypeString; Result += "\"";
6181 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006182 if (!MethodImpl)
6183 Result += "0";
6184 else {
6185 Result += "(void *)";
6186 Result += RewriteObj.MethodInternalNames[MD];
6187 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006188 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006189 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006190 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006191 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006192 }
6193 Result += "};\n";
6194 }
6195}
6196
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006197static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006198 ASTContext *Context, std::string &Result,
6199 ArrayRef<ObjCPropertyDecl *> Properties,
6200 const Decl *Container,
6201 StringRef VarName,
6202 StringRef ProtocolName) {
6203 if (Properties.size() > 0) {
6204 Result += "\nstatic ";
6205 Write__prop_list_t_TypeDecl(Result, Properties.size());
6206 Result += " "; Result += VarName;
6207 Result += ProtocolName;
6208 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6209 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6210 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6211 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6212 ObjCPropertyDecl *PropDecl = Properties[i];
6213 if (i == 0)
6214 Result += "\t{{\"";
6215 else
6216 Result += "\t{\"";
6217 Result += PropDecl->getName(); Result += "\",";
6218 std::string PropertyTypeString, QuotePropertyTypeString;
6219 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6220 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6221 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6222 if (i == e-1)
6223 Result += "}}\n";
6224 else
6225 Result += "},\n";
6226 }
6227 Result += "};\n";
6228 }
6229}
6230
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006231// Metadata flags
6232enum MetaDataDlags {
6233 CLS = 0x0,
6234 CLS_META = 0x1,
6235 CLS_ROOT = 0x2,
6236 OBJC2_CLS_HIDDEN = 0x10,
6237 CLS_EXCEPTION = 0x20,
6238
6239 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6240 CLS_HAS_IVAR_RELEASER = 0x40,
6241 /// class was compiled with -fobjc-arr
6242 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6243};
6244
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006245static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6246 unsigned int flags,
6247 const std::string &InstanceStart,
6248 const std::string &InstanceSize,
6249 ArrayRef<ObjCMethodDecl *>baseMethods,
6250 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6251 ArrayRef<ObjCIvarDecl *>ivars,
6252 ArrayRef<ObjCPropertyDecl *>Properties,
6253 StringRef VarName,
6254 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006255 Result += "\nstatic struct _class_ro_t ";
6256 Result += VarName; Result += ClassName;
6257 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6258 Result += "\t";
6259 Result += llvm::utostr(flags); Result += ", ";
6260 Result += InstanceStart; Result += ", ";
6261 Result += InstanceSize; Result += ", \n";
6262 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006263 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6264 if (Triple.getArch() == llvm::Triple::x86_64)
6265 // uint32_t const reserved; // only when building for 64bit targets
6266 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006267 // const uint8_t * const ivarLayout;
6268 Result += "0, \n\t";
6269 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006270 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006271 if (baseMethods.size() > 0) {
6272 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006273 if (metaclass)
6274 Result += "_OBJC_$_CLASS_METHODS_";
6275 else
6276 Result += "_OBJC_$_INSTANCE_METHODS_";
6277 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006278 Result += ",\n\t";
6279 }
6280 else
6281 Result += "0, \n\t";
6282
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006283 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006284 Result += "(const struct _objc_protocol_list *)&";
6285 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6286 Result += ",\n\t";
6287 }
6288 else
6289 Result += "0, \n\t";
6290
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006291 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006292 Result += "(const struct _ivar_list_t *)&";
6293 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6294 Result += ",\n\t";
6295 }
6296 else
6297 Result += "0, \n\t";
6298
6299 // weakIvarLayout
6300 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006301 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006302 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006303 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006304 Result += ",\n";
6305 }
6306 else
6307 Result += "0, \n";
6308
6309 Result += "};\n";
6310}
6311
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006312static void Write_class_t(ASTContext *Context, std::string &Result,
6313 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006314 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6315 bool rootClass = (!CDecl->getSuperClass());
6316 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006317
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006318 if (!rootClass) {
6319 // Find the Root class
6320 RootClass = CDecl->getSuperClass();
6321 while (RootClass->getSuperClass()) {
6322 RootClass = RootClass->getSuperClass();
6323 }
6324 }
6325
6326 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006327 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006328 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006329 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006330 if (CDecl->getImplementation())
6331 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006332 else
6333 Result += "__declspec(dllimport) ";
6334
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006335 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006336 Result += CDecl->getNameAsString();
6337 Result += ";\n";
6338 }
6339 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006340 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006341 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006342 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006343 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006344 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006345 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006346 else
6347 Result += "__declspec(dllimport) ";
6348
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006349 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006350 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006351 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006352 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006353
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006354 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006355 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006356 if (RootClass->getImplementation())
6357 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006358 else
6359 Result += "__declspec(dllimport) ";
6360
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006361 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006362 Result += VarName;
6363 Result += RootClass->getNameAsString();
6364 Result += ";\n";
6365 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006366 }
6367
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006368 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6369 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006370 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6371 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006372 if (metaclass) {
6373 if (!rootClass) {
6374 Result += "0, // &"; Result += VarName;
6375 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006376 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006377 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006378 Result += CDecl->getSuperClass()->getNameAsString();
6379 Result += ",\n\t";
6380 }
6381 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006382 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006383 Result += CDecl->getNameAsString();
6384 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006385 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006386 Result += ",\n\t";
6387 }
6388 }
6389 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006390 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006391 Result += CDecl->getNameAsString();
6392 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006393 if (!rootClass) {
6394 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006395 Result += CDecl->getSuperClass()->getNameAsString();
6396 Result += ",\n\t";
6397 }
6398 else
6399 Result += "0,\n\t";
6400 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006401 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6402 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6403 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006404 Result += "&_OBJC_METACLASS_RO_$_";
6405 else
6406 Result += "&_OBJC_CLASS_RO_$_";
6407 Result += CDecl->getNameAsString();
6408 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006409
6410 // Add static function to initialize some of the meta-data fields.
6411 // avoid doing it twice.
6412 if (metaclass)
6413 return;
6414
6415 const ObjCInterfaceDecl *SuperClass =
6416 rootClass ? CDecl : CDecl->getSuperClass();
6417
6418 Result += "static void OBJC_CLASS_SETUP_$_";
6419 Result += CDecl->getNameAsString();
6420 Result += "(void ) {\n";
6421 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6422 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006423 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006424
6425 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006426 Result += ".superclass = ";
6427 if (rootClass)
6428 Result += "&OBJC_CLASS_$_";
6429 else
6430 Result += "&OBJC_METACLASS_$_";
6431
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006432 Result += SuperClass->getNameAsString(); Result += ";\n";
6433
6434 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6435 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6436
6437 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6438 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6439 Result += CDecl->getNameAsString(); Result += ";\n";
6440
6441 if (!rootClass) {
6442 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6443 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6444 Result += SuperClass->getNameAsString(); Result += ";\n";
6445 }
6446
6447 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6448 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6449 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006450}
6451
Fariborz Jahanian61186122012-02-17 18:40:41 +00006452static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6453 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006454 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006455 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006456 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6457 ArrayRef<ObjCMethodDecl *> ClassMethods,
6458 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6459 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006460 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006461 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006462 // must declare an extern class object in case this class is not implemented
6463 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006464 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006465 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006466 if (ClassDecl->getImplementation())
6467 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006468 else
6469 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006470
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006471 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006472 Result += "OBJC_CLASS_$_"; Result += ClassName;
6473 Result += ";\n";
6474
Fariborz Jahanian61186122012-02-17 18:40:41 +00006475 Result += "\nstatic struct _category_t ";
6476 Result += "_OBJC_$_CATEGORY_";
6477 Result += ClassName; Result += "_$_"; Result += CatName;
6478 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6479 Result += "{\n";
6480 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006481 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006482 Result += ",\n";
6483 if (InstanceMethods.size() > 0) {
6484 Result += "\t(const struct _method_list_t *)&";
6485 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6486 Result += ClassName; Result += "_$_"; Result += CatName;
6487 Result += ",\n";
6488 }
6489 else
6490 Result += "\t0,\n";
6491
6492 if (ClassMethods.size() > 0) {
6493 Result += "\t(const struct _method_list_t *)&";
6494 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6495 Result += ClassName; Result += "_$_"; Result += CatName;
6496 Result += ",\n";
6497 }
6498 else
6499 Result += "\t0,\n";
6500
6501 if (RefedProtocols.size() > 0) {
6502 Result += "\t(const struct _protocol_list_t *)&";
6503 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6504 Result += ClassName; Result += "_$_"; Result += CatName;
6505 Result += ",\n";
6506 }
6507 else
6508 Result += "\t0,\n";
6509
6510 if (ClassProperties.size() > 0) {
6511 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6512 Result += ClassName; Result += "_$_"; Result += CatName;
6513 Result += ",\n";
6514 }
6515 else
6516 Result += "\t0,\n";
6517
6518 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006519
6520 // Add static function to initialize the class pointer in the category structure.
6521 Result += "static void OBJC_CATEGORY_SETUP_$_";
6522 Result += ClassDecl->getNameAsString();
6523 Result += "_$_";
6524 Result += CatName;
6525 Result += "(void ) {\n";
6526 Result += "\t_OBJC_$_CATEGORY_";
6527 Result += ClassDecl->getNameAsString();
6528 Result += "_$_";
6529 Result += CatName;
6530 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6531 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006532}
6533
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006534static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6535 ASTContext *Context, std::string &Result,
6536 ArrayRef<ObjCMethodDecl *> Methods,
6537 StringRef VarName,
6538 StringRef ProtocolName) {
6539 if (Methods.size() == 0)
6540 return;
6541
6542 Result += "\nstatic const char *";
6543 Result += VarName; Result += ProtocolName;
6544 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6545 Result += "{\n";
6546 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6547 ObjCMethodDecl *MD = Methods[i];
6548 std::string MethodTypeString, QuoteMethodTypeString;
6549 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6550 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6551 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6552 if (i == e-1)
6553 Result += "\n};\n";
6554 else {
6555 Result += ",\n";
6556 }
6557 }
6558}
6559
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006560static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6561 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006562 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006563 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006564 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006565 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6566 // this is what happens:
6567 /**
6568 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6569 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6570 Class->getVisibility() == HiddenVisibility)
6571 Visibility shoud be: HiddenVisibility;
6572 else
6573 Visibility shoud be: DefaultVisibility;
6574 */
6575
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006576 Result += "\n";
6577 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6578 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006579 if (Context->getLangOpts().MicrosoftExt)
6580 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6581
6582 if (!Context->getLangOpts().MicrosoftExt ||
6583 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006584 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006585 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006586 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006587 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006588 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006589 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6590 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006591 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6592 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006593 }
6594}
6595
Fariborz Jahanianae932952012-02-10 20:47:10 +00006596static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6597 ASTContext *Context, std::string &Result,
6598 ArrayRef<ObjCIvarDecl *> Ivars,
6599 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006600 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006601 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006602 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006603
Fariborz Jahanianae932952012-02-10 20:47:10 +00006604 Result += "\nstatic ";
6605 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6606 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006607 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006608 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6609 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6610 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6611 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6612 ObjCIvarDecl *IvarDecl = Ivars[i];
6613 if (i == 0)
6614 Result += "\t{{";
6615 else
6616 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006617 Result += "(unsigned long int *)&";
6618 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006619 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006620
6621 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6622 std::string IvarTypeString, QuoteIvarTypeString;
6623 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6624 IvarDecl);
6625 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6626 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6627
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006628 // FIXME. this alignment represents the host alignment and need be changed to
6629 // represent the target alignment.
6630 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6631 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006632 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006633 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6634 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006635 if (i == e-1)
6636 Result += "}}\n";
6637 else
6638 Result += "},\n";
6639 }
6640 Result += "};\n";
6641 }
6642}
6643
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006644/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006645void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6646 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006647
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006648 // Do not synthesize the protocol more than once.
6649 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6650 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006651 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006652
6653 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6654 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006655 // Must write out all protocol definitions in current qualifier list,
6656 // and in their nested qualifiers before writing out current definition.
6657 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6658 E = PDecl->protocol_end(); I != E; ++I)
6659 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006660
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006661 // Construct method lists.
6662 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6663 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6664 for (ObjCProtocolDecl::instmeth_iterator
6665 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6666 I != E; ++I) {
6667 ObjCMethodDecl *MD = *I;
6668 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6669 OptInstanceMethods.push_back(MD);
6670 } else {
6671 InstanceMethods.push_back(MD);
6672 }
6673 }
6674
6675 for (ObjCProtocolDecl::classmeth_iterator
6676 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6677 I != E; ++I) {
6678 ObjCMethodDecl *MD = *I;
6679 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6680 OptClassMethods.push_back(MD);
6681 } else {
6682 ClassMethods.push_back(MD);
6683 }
6684 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006685 std::vector<ObjCMethodDecl *> AllMethods;
6686 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6687 AllMethods.push_back(InstanceMethods[i]);
6688 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6689 AllMethods.push_back(ClassMethods[i]);
6690 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6691 AllMethods.push_back(OptInstanceMethods[i]);
6692 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6693 AllMethods.push_back(OptClassMethods[i]);
6694
6695 Write__extendedMethodTypes_initializer(*this, Context, Result,
6696 AllMethods,
6697 "_OBJC_PROTOCOL_METHOD_TYPES_",
6698 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006699 // Protocol's super protocol list
6700 std::vector<ObjCProtocolDecl *> SuperProtocols;
6701 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6702 E = PDecl->protocol_end(); I != E; ++I)
6703 SuperProtocols.push_back(*I);
6704
6705 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6706 "_OBJC_PROTOCOL_REFS_",
6707 PDecl->getNameAsString());
6708
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006709 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006710 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006711 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006712
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006713 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006714 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006715 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006716
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006717 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006718 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006719 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006720
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006721 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006722 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006723 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006724
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006725 // Protocol's property metadata.
6726 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6727 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6728 E = PDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00006729 ProtocolProperties.push_back(&*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006730
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006731 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006732 /* Container */0,
6733 "_OBJC_PROTOCOL_PROPERTIES_",
6734 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006735
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006736 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006737 Result += "\n";
6738 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006739 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006740 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006741 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006742 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6743 Result += "\t0,\n"; // id is; is null
6744 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006745 if (SuperProtocols.size() > 0) {
6746 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6747 Result += PDecl->getNameAsString(); Result += ",\n";
6748 }
6749 else
6750 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006751 if (InstanceMethods.size() > 0) {
6752 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6753 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006754 }
6755 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006756 Result += "\t0,\n";
6757
6758 if (ClassMethods.size() > 0) {
6759 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6760 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006761 }
6762 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006763 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006764
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006765 if (OptInstanceMethods.size() > 0) {
6766 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6767 Result += PDecl->getNameAsString(); Result += ",\n";
6768 }
6769 else
6770 Result += "\t0,\n";
6771
6772 if (OptClassMethods.size() > 0) {
6773 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6774 Result += PDecl->getNameAsString(); Result += ",\n";
6775 }
6776 else
6777 Result += "\t0,\n";
6778
6779 if (ProtocolProperties.size() > 0) {
6780 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6781 Result += PDecl->getNameAsString(); Result += ",\n";
6782 }
6783 else
6784 Result += "\t0,\n";
6785
6786 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6787 Result += "\t0,\n";
6788
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006789 if (AllMethods.size() > 0) {
6790 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6791 Result += PDecl->getNameAsString();
6792 Result += "\n};\n";
6793 }
6794 else
6795 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006796
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006797 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006798 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006799 Result += "struct _protocol_t *";
6800 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6801 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6802 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006803
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006804 // Mark this protocol as having been generated.
6805 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6806 llvm_unreachable("protocol already synthesized");
6807
6808}
6809
6810void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6811 const ObjCList<ObjCProtocolDecl> &Protocols,
6812 StringRef prefix, StringRef ClassName,
6813 std::string &Result) {
6814 if (Protocols.empty()) return;
6815
6816 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006817 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006818
6819 // Output the top lovel protocol meta-data for the class.
6820 /* struct _objc_protocol_list {
6821 struct _objc_protocol_list *next;
6822 int protocol_count;
6823 struct _objc_protocol *class_protocols[];
6824 }
6825 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006826 Result += "\n";
6827 if (LangOpts.MicrosoftExt)
6828 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6829 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006830 Result += "\tstruct _objc_protocol_list *next;\n";
6831 Result += "\tint protocol_count;\n";
6832 Result += "\tstruct _objc_protocol *class_protocols[";
6833 Result += utostr(Protocols.size());
6834 Result += "];\n} _OBJC_";
6835 Result += prefix;
6836 Result += "_PROTOCOLS_";
6837 Result += ClassName;
6838 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6839 "{\n\t0, ";
6840 Result += utostr(Protocols.size());
6841 Result += "\n";
6842
6843 Result += "\t,{&_OBJC_PROTOCOL_";
6844 Result += Protocols[0]->getNameAsString();
6845 Result += " \n";
6846
6847 for (unsigned i = 1; i != Protocols.size(); i++) {
6848 Result += "\t ,&_OBJC_PROTOCOL_";
6849 Result += Protocols[i]->getNameAsString();
6850 Result += "\n";
6851 }
6852 Result += "\t }\n};\n";
6853}
6854
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006855/// hasObjCExceptionAttribute - Return true if this class or any super
6856/// class has the __objc_exception__ attribute.
6857/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6858static bool hasObjCExceptionAttribute(ASTContext &Context,
6859 const ObjCInterfaceDecl *OID) {
6860 if (OID->hasAttr<ObjCExceptionAttr>())
6861 return true;
6862 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6863 return hasObjCExceptionAttribute(Context, Super);
6864 return false;
6865}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006866
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006867void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6868 std::string &Result) {
6869 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6870
6871 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006872 if (CDecl->isImplicitInterfaceDecl())
6873 assert(false &&
6874 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006875
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006876 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006877 SmallVector<ObjCIvarDecl *, 8> IVars;
6878
6879 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6880 IVD; IVD = IVD->getNextIvar()) {
6881 // Ignore unnamed bit-fields.
6882 if (!IVD->getDeclName())
6883 continue;
6884 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006885 }
6886
Fariborz Jahanianae932952012-02-10 20:47:10 +00006887 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006888 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006889 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006890
6891 // Build _objc_method_list for class's instance methods if needed
6892 SmallVector<ObjCMethodDecl *, 32>
6893 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6894
6895 // If any of our property implementations have associated getters or
6896 // setters, produce metadata for them as well.
6897 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6898 PropEnd = IDecl->propimpl_end();
6899 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00006900 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006901 continue;
David Blaikie262bc182012-04-30 02:36:29 +00006902 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006903 continue;
David Blaikie262bc182012-04-30 02:36:29 +00006904 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006905 if (!PD)
6906 continue;
6907 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00006908 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006909 InstanceMethods.push_back(Getter);
6910 if (PD->isReadOnly())
6911 continue;
6912 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00006913 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006914 InstanceMethods.push_back(Setter);
6915 }
6916
6917 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6918 "_OBJC_$_INSTANCE_METHODS_",
6919 IDecl->getNameAsString(), true);
6920
6921 SmallVector<ObjCMethodDecl *, 32>
6922 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6923
6924 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6925 "_OBJC_$_CLASS_METHODS_",
6926 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006927
6928 // Protocols referenced in class declaration?
6929 // Protocol's super protocol list
6930 std::vector<ObjCProtocolDecl *> RefedProtocols;
6931 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6932 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6933 E = Protocols.end();
6934 I != E; ++I) {
6935 RefedProtocols.push_back(*I);
6936 // Must write out all protocol definitions in current qualifier list,
6937 // and in their nested qualifiers before writing out current definition.
6938 RewriteObjCProtocolMetaData(*I, Result);
6939 }
6940
6941 Write_protocol_list_initializer(Context, Result,
6942 RefedProtocols,
6943 "_OBJC_CLASS_PROTOCOLS_$_",
6944 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006945
6946 // Protocol's property metadata.
6947 std::vector<ObjCPropertyDecl *> ClassProperties;
6948 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6949 E = CDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00006950 ClassProperties.push_back(&*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006951
6952 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006953 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006954 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006955 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006956
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006957
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006958 // Data for initializing _class_ro_t metaclass meta-data
6959 uint32_t flags = CLS_META;
6960 std::string InstanceSize;
6961 std::string InstanceStart;
6962
6963
6964 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6965 if (classIsHidden)
6966 flags |= OBJC2_CLS_HIDDEN;
6967
6968 if (!CDecl->getSuperClass())
6969 // class is root
6970 flags |= CLS_ROOT;
6971 InstanceSize = "sizeof(struct _class_t)";
6972 InstanceStart = InstanceSize;
6973 Write__class_ro_t_initializer(Context, Result, flags,
6974 InstanceStart, InstanceSize,
6975 ClassMethods,
6976 0,
6977 0,
6978 0,
6979 "_OBJC_METACLASS_RO_$_",
6980 CDecl->getNameAsString());
6981
6982
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006983 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006984 flags = CLS;
6985 if (classIsHidden)
6986 flags |= OBJC2_CLS_HIDDEN;
6987
6988 if (hasObjCExceptionAttribute(*Context, CDecl))
6989 flags |= CLS_EXCEPTION;
6990
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006991 if (!CDecl->getSuperClass())
6992 // class is root
6993 flags |= CLS_ROOT;
6994
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006995 InstanceSize.clear();
6996 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006997 if (!ObjCSynthesizedStructs.count(CDecl)) {
6998 InstanceSize = "0";
6999 InstanceStart = "0";
7000 }
7001 else {
7002 InstanceSize = "sizeof(struct ";
7003 InstanceSize += CDecl->getNameAsString();
7004 InstanceSize += "_IMPL)";
7005
7006 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7007 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007008 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007009 }
7010 else
7011 InstanceStart = InstanceSize;
7012 }
7013 Write__class_ro_t_initializer(Context, Result, flags,
7014 InstanceStart, InstanceSize,
7015 InstanceMethods,
7016 RefedProtocols,
7017 IVars,
7018 ClassProperties,
7019 "_OBJC_CLASS_RO_$_",
7020 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007021
7022 Write_class_t(Context, Result,
7023 "OBJC_METACLASS_$_",
7024 CDecl, /*metaclass*/true);
7025
7026 Write_class_t(Context, Result,
7027 "OBJC_CLASS_$_",
7028 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007029
7030 if (ImplementationIsNonLazy(IDecl))
7031 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007032
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007033}
7034
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007035void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7036 int ClsDefCount = ClassImplementation.size();
7037 if (!ClsDefCount)
7038 return;
7039 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7040 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7041 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7042 for (int i = 0; i < ClsDefCount; i++) {
7043 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7044 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7045 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7046 Result += CDecl->getName(); Result += ",\n";
7047 }
7048 Result += "};\n";
7049}
7050
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007051void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7052 int ClsDefCount = ClassImplementation.size();
7053 int CatDefCount = CategoryImplementation.size();
7054
7055 // For each implemented class, write out all its meta data.
7056 for (int i = 0; i < ClsDefCount; i++)
7057 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7058
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007059 RewriteClassSetupInitHook(Result);
7060
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007061 // For each implemented category, write out all its meta data.
7062 for (int i = 0; i < CatDefCount; i++)
7063 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7064
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007065 RewriteCategorySetupInitHook(Result);
7066
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007067 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007068 if (LangOpts.MicrosoftExt)
7069 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007070 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7071 Result += llvm::utostr(ClsDefCount); Result += "]";
7072 Result +=
7073 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7074 "regular,no_dead_strip\")))= {\n";
7075 for (int i = 0; i < ClsDefCount; i++) {
7076 Result += "\t&OBJC_CLASS_$_";
7077 Result += ClassImplementation[i]->getNameAsString();
7078 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007079 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007080 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007081
7082 if (!DefinedNonLazyClasses.empty()) {
7083 if (LangOpts.MicrosoftExt)
7084 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7085 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7086 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7087 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7088 Result += ",\n";
7089 }
7090 Result += "};\n";
7091 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007092 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007093
7094 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007095 if (LangOpts.MicrosoftExt)
7096 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007097 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7098 Result += llvm::utostr(CatDefCount); Result += "]";
7099 Result +=
7100 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7101 "regular,no_dead_strip\")))= {\n";
7102 for (int i = 0; i < CatDefCount; i++) {
7103 Result += "\t&_OBJC_$_CATEGORY_";
7104 Result +=
7105 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7106 Result += "_$_";
7107 Result += CategoryImplementation[i]->getNameAsString();
7108 Result += ",\n";
7109 }
7110 Result += "};\n";
7111 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007112
7113 if (!DefinedNonLazyCategories.empty()) {
7114 if (LangOpts.MicrosoftExt)
7115 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7116 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7117 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7118 Result += "\t&_OBJC_$_CATEGORY_";
7119 Result +=
7120 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7121 Result += "_$_";
7122 Result += DefinedNonLazyCategories[i]->getNameAsString();
7123 Result += ",\n";
7124 }
7125 Result += "};\n";
7126 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007127}
7128
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007129void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7130 if (LangOpts.MicrosoftExt)
7131 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7132
7133 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7134 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007135 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007136}
7137
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007138/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7139/// implementation.
7140void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7141 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007142 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007143 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7144 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007145 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007146 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7147 CDecl = CDecl->getNextClassCategory())
7148 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7149 break;
7150
7151 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007152 FullCategoryName += "_$_";
7153 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007154
7155 // Build _objc_method_list for class's instance methods if needed
7156 SmallVector<ObjCMethodDecl *, 32>
7157 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7158
7159 // If any of our property implementations have associated getters or
7160 // setters, produce metadata for them as well.
7161 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7162 PropEnd = IDecl->propimpl_end();
7163 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007164 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007165 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007166 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007167 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007168 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007169 if (!PD)
7170 continue;
7171 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7172 InstanceMethods.push_back(Getter);
7173 if (PD->isReadOnly())
7174 continue;
7175 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7176 InstanceMethods.push_back(Setter);
7177 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007178
Fariborz Jahanian61186122012-02-17 18:40:41 +00007179 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7180 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7181 FullCategoryName, true);
7182
7183 SmallVector<ObjCMethodDecl *, 32>
7184 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7185
7186 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7187 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7188 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007189
7190 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007191 // Protocol's super protocol list
7192 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007193 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7194 E = CDecl->protocol_end();
7195
7196 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007197 RefedProtocols.push_back(*I);
7198 // Must write out all protocol definitions in current qualifier list,
7199 // and in their nested qualifiers before writing out current definition.
7200 RewriteObjCProtocolMetaData(*I, Result);
7201 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007202
Fariborz Jahanian61186122012-02-17 18:40:41 +00007203 Write_protocol_list_initializer(Context, Result,
7204 RefedProtocols,
7205 "_OBJC_CATEGORY_PROTOCOLS_$_",
7206 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007207
Fariborz Jahanian61186122012-02-17 18:40:41 +00007208 // Protocol's property metadata.
7209 std::vector<ObjCPropertyDecl *> ClassProperties;
7210 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7211 E = CDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00007212 ClassProperties.push_back(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007213
Fariborz Jahanian61186122012-02-17 18:40:41 +00007214 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007215 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007216 "_OBJC_$_PROP_LIST_",
7217 FullCategoryName);
7218
7219 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007220 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007221 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007222 InstanceMethods,
7223 ClassMethods,
7224 RefedProtocols,
7225 ClassProperties);
7226
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007227 // Determine if this category is also "non-lazy".
7228 if (ImplementationIsNonLazy(IDecl))
7229 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007230
7231}
7232
7233void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7234 int CatDefCount = CategoryImplementation.size();
7235 if (!CatDefCount)
7236 return;
7237 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7238 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7239 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7240 for (int i = 0; i < CatDefCount; i++) {
7241 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7242 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7243 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7244 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7245 Result += ClassDecl->getName();
7246 Result += "_$_";
7247 Result += CatDecl->getName();
7248 Result += ",\n";
7249 }
7250 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007251}
7252
7253// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7254/// class methods.
7255template<typename MethodIterator>
7256void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7257 MethodIterator MethodEnd,
7258 bool IsInstanceMethod,
7259 StringRef prefix,
7260 StringRef ClassName,
7261 std::string &Result) {
7262 if (MethodBegin == MethodEnd) return;
7263
7264 if (!objc_impl_method) {
7265 /* struct _objc_method {
7266 SEL _cmd;
7267 char *method_types;
7268 void *_imp;
7269 }
7270 */
7271 Result += "\nstruct _objc_method {\n";
7272 Result += "\tSEL _cmd;\n";
7273 Result += "\tchar *method_types;\n";
7274 Result += "\tvoid *_imp;\n";
7275 Result += "};\n";
7276
7277 objc_impl_method = true;
7278 }
7279
7280 // Build _objc_method_list for class's methods if needed
7281
7282 /* struct {
7283 struct _objc_method_list *next_method;
7284 int method_count;
7285 struct _objc_method method_list[];
7286 }
7287 */
7288 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007289 Result += "\n";
7290 if (LangOpts.MicrosoftExt) {
7291 if (IsInstanceMethod)
7292 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7293 else
7294 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7295 }
7296 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007297 Result += "\tstruct _objc_method_list *next_method;\n";
7298 Result += "\tint method_count;\n";
7299 Result += "\tstruct _objc_method method_list[";
7300 Result += utostr(NumMethods);
7301 Result += "];\n} _OBJC_";
7302 Result += prefix;
7303 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7304 Result += "_METHODS_";
7305 Result += ClassName;
7306 Result += " __attribute__ ((used, section (\"__OBJC, __";
7307 Result += IsInstanceMethod ? "inst" : "cls";
7308 Result += "_meth\")))= ";
7309 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7310
7311 Result += "\t,{{(SEL)\"";
7312 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7313 std::string MethodTypeString;
7314 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7315 Result += "\", \"";
7316 Result += MethodTypeString;
7317 Result += "\", (void *)";
7318 Result += MethodInternalNames[*MethodBegin];
7319 Result += "}\n";
7320 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7321 Result += "\t ,{(SEL)\"";
7322 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7323 std::string MethodTypeString;
7324 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7325 Result += "\", \"";
7326 Result += MethodTypeString;
7327 Result += "\", (void *)";
7328 Result += MethodInternalNames[*MethodBegin];
7329 Result += "}\n";
7330 }
7331 Result += "\t }\n};\n";
7332}
7333
7334Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7335 SourceRange OldRange = IV->getSourceRange();
7336 Expr *BaseExpr = IV->getBase();
7337
7338 // Rewrite the base, but without actually doing replaces.
7339 {
7340 DisableReplaceStmtScope S(*this);
7341 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7342 IV->setBase(BaseExpr);
7343 }
7344
7345 ObjCIvarDecl *D = IV->getDecl();
7346
7347 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007348
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007349 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7350 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007351 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007352 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7353 // lookup which class implements the instance variable.
7354 ObjCInterfaceDecl *clsDeclared = 0;
7355 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7356 clsDeclared);
7357 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7358
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007359 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007360 std::string IvarOffsetName;
7361 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7362
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007363 ReferencedIvars[clsDeclared].insert(D);
7364
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007365 // cast offset to "char *".
7366 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7367 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007368 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007369 BaseExpr);
7370 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7371 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7372 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007373 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7374 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007375 SourceLocation());
7376 BinaryOperator *addExpr =
7377 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7378 Context->getPointerType(Context->CharTy),
7379 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007380 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007381 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7382 SourceLocation(),
7383 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007384 QualType IvarT = D->getType();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007385
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007386 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007387 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007388 RD = RD->getDefinition();
7389 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007390 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007391 ObjCContainerDecl *CDecl =
7392 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7393 // ivar in class extensions requires special treatment.
7394 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7395 CDecl = CatDecl->getClassInterface();
7396 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007397 RecName += "_IMPL";
7398 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7399 SourceLocation(), SourceLocation(),
7400 &Context->Idents.get(RecName.c_str()));
7401 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7402 unsigned UnsignedIntSize =
7403 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7404 Expr *Zero = IntegerLiteral::Create(*Context,
7405 llvm::APInt(UnsignedIntSize, 0),
7406 Context->UnsignedIntTy, SourceLocation());
7407 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7408 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7409 Zero);
7410 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7411 SourceLocation(),
7412 &Context->Idents.get(D->getNameAsString()),
7413 IvarT, 0,
7414 /*BitWidth=*/0, /*Mutable=*/true,
7415 /*HasInit=*/false);
7416 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7417 FD->getType(), VK_LValue,
7418 OK_Ordinary);
7419 IvarT = Context->getDecltypeType(ME, ME->getType());
7420 }
7421 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007422 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007423 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007424
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007425 castExpr = NoTypeInfoCStyleCastExpr(Context,
7426 castT,
7427 CK_BitCast,
7428 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007429
7430
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007431 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007432 VK_LValue, OK_Ordinary,
7433 SourceLocation());
7434 PE = new (Context) ParenExpr(OldRange.getBegin(),
7435 OldRange.getEnd(),
7436 Exp);
7437
7438 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007439 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007440
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007441 ReplaceStmtWithRange(IV, Replacement, OldRange);
7442 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007443}